text
stringlengths 37
1.41M
|
---|
import turtle
#lander initial position
x0=0
y0=0
#lander position
x=0
y=0
#lander initial velocity
vx0=10
vy0=0
#lander velocity
vx=10
vy=0
#lander initial acceleration
ax0=0
ay0=-10
#lander acceleration
ax=0
ay=-10
#time step
dt=1/20
ground_level=-200
body=turtle.Turtle()
body.shape('circle')
body.color('red')
bts = body.turtlesize()
print(bts)
def do_step():
global x, y, vx, vy, ax, ay, dt, body
x=x+vx*dt
y=y+vy*dt
vx=vx+ax*dt
vy=vy+ay*dt
if y<=ground_level+10:
vy= -vy
body.up()
def update():
global x,y,dt
do_step()
body.setpos(x,y)
turtle.ontimer(update,int(dt*1000))
update()
def return_back():
global x0,y0,x,y,vx0,vy0,vx,vy,ax0,ay0,ax,ay
x=x0
y=y0
vx=vx0
vy=vy0
ax=ax0
ay=ay0
def draw_ground():
turtle.up()
turtle.setpos(-1000,ground_level)
turtle.down()
turtle.color('green')
turtle.begin_fill()
turtle.setpos(1000, ground_level)
turtle.end_fill()
turtle.onkeypress( return_back,'space')
turtle.listen( )
draw_ground()
turtle.mainloop()
|
import turtle
import math
turtle.speed('fastest')
#lander initial position
x0=0
y0=0
#lander position
x=0
y=0
#lander initial velocity 7 angle
angle0 = 0
velocity0 = 50
vx0=10
vy0=0
#lander velocity
vx=10
vy=0
#lander initial acceleration
ax0=0
ay0=-10
#lander acceleration
ax=0
ay=-10
#time step
dt=1./20
ground_level=-200
i=0
#Other variables
is_running = False
aimbot = turtle.Turtle()
body=turtle.Turtle()
body.shape('square')
body.color('purple')
bts = body.turtlesize()
print(bts)
def do_step():
global x, y, vx, vy, ax, ay, dt, body, i
x=x+vx*dt
y=y+vy*dt
vx=vx+ax*dt
vy=vy+ay*dt
if y<=ground_level+10:
vy= -vy
body.up()
def update():
global x,y,dt
if is_running == True:
do_step()
body.setpos(x,y)
turtle.ontimer(update,int(dt*1000))
def onspace():
global x, y, vy
x = y = 0
vy = 0
def drawground():
# draw ground line
turtle.color("green")
global ground_level
turtle.penup()
turtle.setpos(-500, ground_level)
turtle.pendown()
turtle.setpos(500, ground_level)
turtle.penup()
# draw marks
ruler_x = -500
ruler_y = ground_level
while ruler_x - 500:
turtle.setpos (ruler_x, ruler_y)
turtle.pendown()
turtle.setpos(ruler_x, ruler_y - 10)
turtle.write(ruler_x)
turtle.penup()
ruler_x = ruler_x + 50
def pause():
global is_running
if is_running == True:
is_running = False
else:
is_running = True
def draw_aim():
global x0, y0, angle0, velocity0
aimbot.up()
aimbot.setpos(x0, y0)
aimbot.down()
aimbot.setheading(angle0)
aimbot.forward(velocity0)
def increase_angle():
turtle.onkey(None, 'Up') #Disable more calls while running
global angle0, aimbot, x0, y0, angle0, velocity0
angle0 = angle0 + 10
aimbot.undo()
draw_aim()
turtle.onkey(increase_angle, 'Up') #Renable more calls once finished
modify_vx_vy()
def decrease_angle():
turtle.onkey(None, 'Down') #Disable more calls while running
global angle0, aimbot, x0, y0, angle0, velocity0
angle0 = angle0 - 10
aimbot.undo()
draw_aim()
turtle.onkey(decrease_angle, 'Down') #Renable more calls once finished
modify_vx_vy()
def modify_vx_vy():
global vx0, vy0, velocity0, angle0
vx0 = velocity0 * math.cos(angle0)
vy0 = velocity0 * math.sin(angle0)
def reset():
# reset square coordinates to initial position
global x, y, x0, y0, vx, vy, vx0, vy0
x = x0
y = y0
vx = vx0
vy = vy0
drawground()
draw_aim()
update()
# The turtle.py for Python 2.7 only defines onkey() -- the onkey() variant was added in Python 3
# (as was a synonym for onkey() called onkeyrelease())
turtle.onkey(pause, 'p' )
turtle.onkey(reset, 'space')
turtle.onkey(increase_angle, 'Up' )
turtle.onkey(decrease_angle, 'Down' )
turtle.listen( )
turtle.mainloop()
|
from connection import connect
def create_db(db_name):
sql = f"""
CREATE DATABASE {db_name}
"""
conn = connect()
cursor = conn.cursor()
try:
cursor.execute(sql)
except:
return 'This database name is already in use'
conn.close()
def create_table(table_name, columns_names_types):
sql = f"""
CREATE TABLE {table_name} ({columns_names_types})
"""
conn = connect()
cursor = conn.cursor()
try:
cursor.execute(sql)
except:
return 'This table name is already in use'
conn.close()
|
# 1.For Loop Basic work
even_list = list(range(2, 10, 2))
for i in range(3):
print(i)
# 2. Printing a Patteren
# *
# * *
# * * *
# * * * *
# * * * * * [ Like That ]
for i in range(1, 5):
for j in range(i):
print('*', end=" ")
print("")
# Here i learned one thing Identation is really matter @ time of code
# Other Langauge having a proper paranthesis then code is proper maintain but in python complete code being a part Identation otherwise it will produced a wrong result
i = 0
while i < 5:
print(i)
i += 1
|
"""
Queue implemented with a resizing List
"""
from .queue import Queue
class QueueWithListIterator(object):
def __init__(self, items, front_index, back_index):
super(QueueWithListIterator, self).__init__()
self._items = items
self._current_index = front_index
self._back_index = back_index
def __iter__(self):
return self
def next(self):
if self._current_index == self._back_index:
raise StopIteration()
item = self._items[self._current_index]
self._current_index = (self._current_index + 1) % len(self._items)
return item
class QueueWithList(Queue):
def __init__(self):
"""
Using a pre-initilized List to store the items in the Queue in order to illistrate the resizing logic
"""
super(QueueWithList, self).__init__()
self._front_index = 0
self._back_index = 0
self._items = [None]
def __iter__(self):
return QueueWithListIterator(self._items, self._front_index, self._back_index)
def _do_enqueue(self, item):
if self.size == len(self._items):
self._resize_items(2)
self._items[self._back_index] = item
self._size += 1
self._back_index = (self._back_index + 1) % len(self._items)
def _do_dequeue(self):
item = self._items[self._front_index]
self._items[self._front_index] = None
self._size -= 1
self._front_index = (self._front_index + 1) % len(self._items)
if self.size == (len(self._items) / 4):
self._resize_items(.5)
return item
def _get_front(self):
return self._items[self._front_index]
def _resize_items(self, resize_factor):
max_items = len(self._items)
new_items = [None] * int(max_items * resize_factor)
for index in range(self.size):
mapped_index = (self._front_index + index) % max_items
new_items[index] = self._items[mapped_index]
self._items = new_items
self._front_index = 0
self._back_index = self.size
|
import calendar
import datetime
import time
ticks= time.time()
print(ticks)
#获取当前时间
localtime = time.localtime(time.time())
print(localtime)
print(time.localtime())
#格式化时间 Tue Apr 23 15:08:53 2019
formattime= time.asctime(time.localtime(time.time()))
print(formattime)
#格式化成2016-03-20 11:45:39形式
formatdate=time.strftime("%Y-%m-%d %H:%M:%S",time.localtime())
print(formatdate)
# 格式化成Sat Mar 28 22:24:24 2016形式
formatdate1=time.strftime("%a %b %H:%M:%S %Y",time.localtime())
print(formatdate1)
#将字符串转为日期
a="2019-01-21 17:03:20"
strdate=time.strptime(a,"%Y-%m-%d %H:%M:%S")
print(strdate)
print(time.mktime(strdate)) #将日期转换为时间戳
#获取2019年1月的日历
cal = calendar.month(2019,1)
print(cal)
#获取cpu的时钟时间,第一次调用返回的是程序运行的实际时间
#第二次之后的调用,返回的是自第一次调用后,到这次调用的时间间隔
print(time.clock())
time.sleep(2)
print(time.clock())
print(calendar.isleap(2019)) #判断2019年是否闰年
print(calendar.month(2019,1,2,1)) #返回一个多行字符串格式的year年month月日历,两行标题,一周一行
print(calendar.monthcalendar(2019,1)) #返回一个整数的单层嵌套列表。每个子列表装载代表一个星期的整数。Year年month月外的日期都设为0
print(calendar.monthrange(2019,1)) #第一个是该月的星期几的日期码,第二个是该月的日期码
#计算今天后的n天
n_days = 4
now = datetime.datetime.now()
n_date = datetime.timedelta(days=n_days)
n_day = now + n_date
print(n_day.strftime("%Y-%m-%d"))
|
import json
'''
json.dumps() //将字典转换为json字符串
json.dump() //可以将内容序列化写入文件中
'''
dict01 = dict(name="lisi",age=20)
print(json.dumps(dict01))
dict011 = [ { 'a' : 1, 'b' : 2, 'c' : 3, 'd' : 4, 'e' : 5 } ]
print(json.dumps(dict011,indent=2,separators=(',',':')))
json01= '{"name": "lisi", "age": 20}'
dict02 = json.loads(json01)
print(dict02)
class Student:
def __init__(self,name,age):
self.name = name
self.age = age
def dict2Student(d):
return Student(d['name'],d['age'])
stu = Student("张三",20)
#将对象转为json字符串
print(json.dumps(stu,ensure_ascii=False,default=lambda obj: obj.__dict__)) #ensure_ascii=False将转换的编码变为utf-8的编码,不用ascii
#将json字符串转为对象
stu1 = json.loads(json01,object_hook=dict2Student)
print(stu1)
|
total = 0
def count(n):
global total
total = total + n
if n == 1:
print(total)
return
n = n - 1;
count(n)
count(10)
|
print("Welcome to Pizza Deliveries")
size = input("What size pizza do you want S, M, L? ").upper()
pep = input("Do you want pepperoni? Y or N: ").upper()
cheese = input("Do you want extra cheese? Y or N: ").upper()
bill = 0
if size == 'S':
bill = 15
if pep == 'Y':
bill = bill + 2
if cheese == 'Y':
bill = bill + 1
elif size == 'M':
bill = 20
if pep == 'Y':
bill = bill + 3
if cheese == 'Y':
bill = bill + 1
elif size == 'L':
bill = 25
if pep == 'Y':
bill = bill + 3
if cheese == 'Y':
bill = bill + 1
print("Your Order")
print(f'Pizza Size: {size}\nPepperoni: {pep}\nExtra Cheese: {cheese}')
print(f"Your final bill is: ${bill}")
|
#importing everything we need from colorama
from colorama import init
from colorama import Fore, Back, Style
#making a loop
while True:
#activating colorama
init()
#choosing the operator
print(Fore.BLUE)
operator = input ("Choose an operator (+, -, *, /, **)")
#choosing the numbers
num1 = float(input("Choose the first number:"))
num2 = float(input("Choose the second number:"))
#math calculations
if operator == "+":
num3 = num1 + num2
print("Result: " + str(num3))
elif operator == "-":
num3 = num1 - num2
print("Result: " + str(num3))
elif operator == "*":
num3 = num1 * num2
print("Result: " + str(num3))
elif operator == "/":
num3 = num1 / num2
print("Result: " + str(num3))
elif operator == "**":
num3 = num1 ** num2
print("Result: " + str(num3))
#incorrrect configuration
else:
print(Fore.RED)
|
# MISSING VALUES
# No R os valores faltantes são codificados como NA
import numpy # Importa a biblioteca NumPy para ser utilizada no código
vector1 = [188.2, 181.3, 193.4, numpy.nan] # Cria um vetor dinâmico com tamanho variado com um dos valores sendo NaN
print(vector1) # Printa o vetor no console
print(numpy.isnan(vector1)) # Verifica onde que há valores NaN dentro do vetor criado anteriormente, retornando um valor booleano para cada posição do vetor, indicando FALSE para onde não tem valor NaN e TRUE para onde tem, depois printa
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Dec 2 12:34:03 2018
@author: bpiwowar
"""
import sys
import os
import csv
# Relative path to folder containing raw files
# This can be used instead of passing an argument to the script
FOLDER_PATH = "SubjectData25Nov"
# return a list of files contained in a folder
# path: relative path to folder from the program
def get_files(path):
trial_files = os.listdir(path)
return trial_files
# main function to reformat all files contanined the files list
# list: list of files
def covert_files(files,raw_folder):
#name of the new folder that will contain formatted files
new_folder = "new_{0}".format(raw_folder)
#check if folder exists, otherwise create new one
if not os.path.exists(new_folder):
os.makedirs(new_folder)
print("Created new folder for formatted files: {}".format(new_folder))
# tries to format each file and save it into new_folder
for f in files:
reformat_file(f,raw_folder,new_folder)
return
# reformas a text file to proper csv format with ',' as delimiter
# saves each new file into new_folder
def reformat_file(file,raw_folder,new_folder):
print("Starting to format: {}".format(file))
# First we open original files as csv with a space delimiter
with open("{0}/{1}".format(raw_folder,file)) as csv_file:
csv_reader = csv.reader(csv_file, delimiter=' ')
# Second we open a new file to write as csv format with ',' delimeter
with open("{0}/{1}.csv".format(new_folder,file), mode='w') as formated_file:
file_writer = csv.writer(formated_file, delimiter=',')
# for each line/row in the orginal file we writ eto new file
# Here we elimanate extra spaces so everything aligns
for row in csv_reader:
# here we reduce the number of spaces in the orignal file
# they written as '' values in the list
reduced_row = [x for x in row if x != '']
# writes a new row to the new file
file_writer.writerow(reduced_row)
return
if __name__ == '__main__':
# check if folder path of raw files has been passed as an argument
if len(sys.argv) > 1:
print(sys.argv[1])
raw_folder = sys.argv[1]
else:
# otherwise use static folder path instead
raw_folder = FOLDER_PATH
# get list of raw files
files = get_files(raw_folder)
#reformat and save new files
covert_files(files,raw_folder)
|
'''price = 1000000
has_good_credit = True
if has_good_credit:
down_payment = 0.1 * price
else:
down_payment= 0.2 * price
print(f"Down Pament: ${down_payment}")'''
#temperature = 35
#if temperature < 30 print("It's a hot day")#else:
# print("It's not a hot day")
'''name = "Pd"
if len(name) < 3:
print("name must be atleast 3 chart")
elif len(name) > 50:
print("name can be max of 50 character")
else:
print("name looks good!")
'''
'''weight = int(input("weight: "))
unit = input ("(L)bs or (K)g: ")
if unit.upper() == "L":
converted = weight * 0.45
print(f"You are {converted} kilos")
else:
converted = weight /0.45
print(f"You are {converted} pounds")'''
'''i = 1
while i <= 5:
print('*' * i)
i += 1
print("Done")'''
'''secret_number = 9
i = 0
guess_limit = 3
while i < guess_limit:
guess = int(input('Guess: '))
i += 1
if guess == secret_number:
print('You Won!')
break
else:
print("failed, sorry")'''
|
# -*- coding: utf-8 -*-
class upair:
# If y != None, constructs the unordered pair (x, y)
# If y == None, constructs an unordered pair from iterable x, e.g. a tuple
def __init__(self, x, y=None):
if y is not None:
self._x = x
self._y = y
else:
self._x, self._y = tuple(x)
def some(self):
return self._x
def other(self, x):
if (self._x == x):
return self._y
else:
return self._x
def count(self, x):
if x not in self:
return 0
elif self.other(x) != x:
return 1
else:
return 2
def __eq__(self, other):
return ((self._x == other._x and self._y == other._y) or
(self._x == other._y and self._y == other._x))
def __ne__(self, other):
return (self != other)
def __len__(self):
return 2
def __contains__(self, elem):
return (self._x == elem or self._y == elem)
def __iter__(self):
yield self._x
yield self._y
def __hash__(self):
return hash(hash((self._x, self._y)) + hash((self._y, self._x)))
def __str__(self):
return "⟅{}, {}⟆".format(self._x, self._y)
def __repr__(self):
return str(self)
|
# The challange consisted of checking string format which I've done
# using regex and then doing a simple calculation
def get_check_digit(input):
import re
r = re.compile('\d-\d{2}-\d{6}-x')
if len(input) == 13:
if r.match(input):
stripped = input[:-2].replace("-","")
s = 0
for index, num in enumerate(stripped):
s += int(num) * (index+1)
return(s % 11)
return -1
print(get_check_digit("-19-852663-x"))
|
'''Write a program containing a function which returns a transposed matrix.
Have it accept non-square matrices as well.
Write a unit test.'''
import unittest
def transpose(M):
row = len(M[0])
col = len(M)
l2 = []
l3 = []
for i in range(0,row):
for j in range(0,col):
l2.append(M[j][i])
l3+=[l2]
l2=[]
return l3
# unit test
class Test(unittest.TestCase):
def test_transpose(self):
mT1 = ([1,2,3],[4,5,6],[7,8,9])
mT2 = ([10,11],[12,13],[14,15])
mT3 = ([20,21,22],[23,24,25])
self.assertEqual(transpose(mT1),[[1,4,7],[2,5,8],[3,6,9]])
self.assertEqual(transpose(mT2),[[10,12,14],[11,13,15]])
self.assertEqual(transpose(mT3),[[20,23],[21,24],[22,25]])
unittest.main()
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import random
a_list = range(30)
random.shuffle(a_list)
print a_list
# 使用选择排序对列表进行排序
for i in range(len(a_list) - 1):
for j in range(i + 1, len(a_list)):
if a_list[i] > a_list[j]:
a_list[i], a_list[j] = a_list[j], a_list[i]
print a_list
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import random
a = range(1, 6)
print a[::2]
print a[-2:]
print sum([i + 3 if a.index(i) % 2 == 0 else i for i in a])
random.shuffle(a)
b = a[:]
b.sort()
print a
print b
print zip(a, b)
print dict(zip(a, b))
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import random
class Node(object):
"""树节点类
"""
def __init__(self, value):
self.value = value
self.left_child = None
self.right_child = None
class BST(object):
"""二叉查找树
"""
def __init__(self, node_list):
self.root = Node(node_list[0])
for i in node_list[1:]:
self.insert(i)
def search(self, node, parent, value):
"""查找二叉树中的子节点
Args:
node type(Node) 查询起始节点对象
parent type(Node) node的父节点对象
value type(int, str...) 需要查找的子节点的value属性值
"""
if node is None:
return False, node, parent
if node.value == value:
return True, node, parent
if node.value > value:
return self.search(node.left_child, node, value)
return self.search(node.right_child, node, value)
def insert(self, value):
"""往二叉树中插入子节点
Args:
value type(int, str...) 需要插入的子节点的value属性值
"""
flag, node, parent = self.search(self.root, self.root, value)
if not flag:
node = Node(value)
if value > parent.value:
parent.right_child = node
else:
parent.left_child = node
def delete(self, value):
"""删除二叉树中的子节点
Args:
value type(int, str...) 需要删除的子节点的value属性值
"""
flag, node, parent = self.search(self.root, self.root, value)
if not flag:
print 'Not find node by value: %s' % value
return
if node.left_child is None or node.right_child is None:
if node == parent.left_child:
parent.left_child = node.left_child or node.right_child
else:
parent.right_child = node.left_child or node.right_child
else:
next_child = node.right_child
if next_child.left_child is None:
node.value = next_child.value
node.right_child = next_child.right_child
else:
next_parent = None
while next_child.left_child is not None:
next_parent = next_child
next_child = next_child.left_child
node.value = next_child.value
next_parent.left_child = next_child.right_child
def pre_order_traversal(self, node):
"""先序遍历
Args:
node type(Node) 需要遍历的起始节点对象
"""
if node is not None:
print node.value
self.pre_order_traversal(node.left_child)
self.pre_order_traversal(node.right_child)
def in_order_traversal(self, node):
"""中序遍历
Args:
node type(Node) 需要遍历的起始节点对象
"""
if node is not None:
self.pre_order_traversal(node.left_child)
print node.value
self.pre_order_traversal(node.right_child)
def post_order_traversal(self, node):
"""后序遍历
Args:
node type(Node) 需要遍历的起始节点对象
"""
if node is not None:
self.pre_order_traversal(node.left_child)
self.pre_order_traversal(node.right_child)
print node.value
if __name__ == '__main__':
a_list = range(30)
random.shuffle(a_list)
print a_list
bst = BST(a_list)
f, n, p = bst.search(bst.root, bst.root, 20)
print 'node.value:', n.value
bst.pre_order_traversal(bst.root)
|
#DFS ITERATIVA
"""
busqueda en profundidad
"""
def dfs(G,s):
N= len(G)
visited=[0 for _ in G]
stack=[s]; visited[s]=1
while len(stack)!=0:
u=stack.pop()
assert visited[u]==1
for v in G[u]:
if visited[v]==0:
stack.append(v); visited[v]=1
visited[u]=2
return visited
G=[
[1],
[0,2,6,3],
[1,3],
[1,2,4],
[5,3],
[4,7,6],
[1,5],
[5],
[],
]
print(dfs(G,5))
|
#Nombre: Tania C. Obando S.
#Codigo: 6036110
"""
Código de Honor
Como miembro de la comunidad académica de la Pontificia Universidad Javeriana Cali me comprometo
a seguir los más altos estándares de integridad académica.
Integridad académica se refiere a ser honesto, dar crédito a quien lo merece y respetar el trabajo de los demás. Por eso
es importante evitar plagiar, engañar, ‘hacer trampa’, etc. En particular, el acto de entregar un programa de computador
ajeno como propio constituye un acto de plagio; cambiar el nombre de las variables, agregar o eliminar comentarios
y reorganizar comandos no cambia el hecho de que se está copiando el programa de alguien más.
"""
from sys import stdin
def encontrarUnoAi(a,EI): #Funcion que encuentra el uno del extremo izquiendo
partea=(EI>>(k-a+1)) #Saca la parte desde 0 hasta ai-1
uno1=(partea&-partea).bit_length()-1 #devuelve la posición del uno más a la izquierda de ai
if uno1==-1: #si devuelve -1 no hay ningun uno en la parte a
ai=uno1
else:
ai=(k-1)-(uno1+(k-a+1)) #transforma la posicion del uno encontrado en la parte a en terminos de las posiciones de la cadena EI
return (ai)
def encontrarUnoBi(b,EI):#Funcion que encuntra el uno del extremo derecho
AUX=1
AUX=(AUX<<(k-b))
AUX=AUX-1
parteb=(EI&AUX) #Saca la parte desde bi+1 hasta K
uno2=parteb.bit_length()-1 #devuelve la posición del uno mas a la derecha de bi
if uno2==-1:#devuelve -1 en caso de no encontrar un uno
bi=uno2
else:
bi=(k-uno2-1)#transforma la posicion del uno encontrado en la parte b en terminos de las posiciones de la cadena EI
return (bi)
def negarCadena(ai,bi,EI):#Función que niega desde el limite ai hasta bi dado un número decimal EI que representa una cadena binaria
"""
pone unos en las posiciones que quiren ser cambiadas y ceros en las que no luego se hace un xor que haces las veces de negar desde ai hasta bi
"""
Mascara=1
Mascara=(Mascara<<(bi-ai+1))# saca el numero de bits a ser cambiados mas uno (1000)
Mascara=Mascara-1 #le resta uno con el fin de que queden todos en uno (111) pero entonces se le resta un bit por eso es la cantidad de los que quieren ser cambiados más uno
Mascara=(Mascara<<(k-bi-1)) #completo con ceros la parte derecha restante
Nestado=Mascara^EI #realizo el xor entre la el decimal que representa el estado acutual con la mascara para tener como resultado la negación
return (Nestado)
def lights():
EI=int(CI,16) #Estado inicial
for i in range(0,M): #en este for recorro todos los estados dados por los m segundos
ai,bi=lista[i]
ZI=((EI>>(k-ai)) & 1) #realiza k-ai corrimientos a la derecha con el fin de que el ultimo bit del número decimal representado en binario sea el que esta en la posicion ai.Luego se hace un and con 1 para saber si lo que hay en esa posicion es un 1 o un 0
if ZI == 0: # si en la posición ai hay un cero entonces busco el primer uno a la izquirda de ai-1(ai-1 porque inicia en cero)
tmpAi=encontrarUnoAi(ai,EI) #Busco si hay un uno
if tmpAi==-1: # en caso de no encontrar un uno la función encontrarUnoAi devuelve -1
ai=ai-1 # el extremo ai se cambia a ai-1 debido a que las posiciones empiezan en 0
else:
ai=tmpAi#en caso de encontrar el uno a la izquierda ai sera la posición donde se encontro el uno
else:
ai=ai-1#si en la posición ai no hay un cero entonces solo le resto uno a ai porque empiezan en 0 las posiciones.
ZD=(EI>>(k-bi) & 1)#realiza k-bi corrimientos a la derecha con el fin de que el ultimo bit del número decimal representado en binariosea el que esta en la posicion bi . Luego se hace un and con 1 para saber si lo que hay en la posición bi es un 0 o un 1
if ZD == 0: #si en la posición bi hay un cero entonces busco el primer uno a la derecha de bi-1
tmpBi=encontrarUnoBi(bi,EI)#Busco si hay un uno
if tmpBi==-1:#en caso de no encotrar un uno la función encontrarUnoBi devuelve -1
bi=bi-1 # el extremo bi se cambia a bi-1 debido a que las posiciones empieza en 0 pero los limites empiezan desde 1
else:
bi=tmpBi#en caso de encontrar el uno a la derecha bi sera la posición en la cual se encontro el uno
else:
bi=bi-1 # si en la posición bi no hay un cero entonces solo le resto uno a bi porque empiezan en 0 las posiones.
EI=negarCadena(ai,bi,EI) #se niega la cadena despues de establecer los limites según el enunciado del proyecto
EF=hex(EI)[2:].upper()#pasar de decimal a hexadecimal (Estado final)
print(EF)
def main():
global k,M,lista,CI
tcnt = int(stdin.readline())
while tcnt!=0:
k,M=map(int,stdin.readline().split()) # K es el número de bombillos y m el numero de segundos a considerar
CI= stdin.readline()#Configuración inicial de las luces dada en hexadecimal.
lista=[]
for i in range(0,M):
ai,bi=map(int,stdin.readline().split()) # K es el número de bombillos y m el numero de segundos a considerar
lista.append((ai,bi))
lights()
tcnt=tcnt-1
main()
|
n = int(input())
is_Even = n % 2 == 0
print(is_Even)
|
password = "1234"
count = 1
quess = input("Please, enter password: ")
while quess != password:
count += 1
print("Wrong password")
quess = input("Please, enter password: ")
print("You have used", count, "attempts")
|
def denklem1 (x):
return x*(x+1)/2
def denklem2 (x):
return x*((3*x)-1)/2
def denklem3 (x):
return x* ((2*x)-1)
a=b=c=1
denklem_a=denklem1(a)
denklem_b=denklem2(b)
denklem_c=denklem3(c)
print("eşit durumlar:")
while True:
if denklem_a==denklem_b and denklem_b==denklem_c:
print("A({})=B({}),C({})={}".format(a,b,c,denklem_a))
if denklem_a <= denklem_b and denklem_a <= denklem_c:
a +=1
denklem_a = denklem1(a)
elif denklem_b <= denklem_a and denklem_b <= denklem_c:
b +=1
denklem_b = denklem2(b)
elif denklem_c <= denklem_a and denklem_c <= denklem_b:
c +=1
denklem_c = denklem3(c)
else:
print("eşitlik bitti")
assert(False);
break
|
a = input("cümle giriniz?")
print (a[::-1])
print (a.split(" "))
harfler = []
sayisi = []
for i in(a):
if not (i in harfler):
harfler.append(i)
sayisi.append(1)
else:
sayisi[harfler.index(i)] = sayisi[harfler.index(i)]+1
print ("her harften kac tane;")
for j in range(len(harfler)):
print(harfler[j],"'den ",sayisi[j],"tane")
tersten = a[::-1]
ayrılmis = tersten.split(" ")
print("kendi içinde ters çevrilmiş:",ayrılmis[::-1])
unluler = ["a","e","o","ö","u","ü","ı","i"]
unlu = []
unsuz = []
for i in a:
if i == unluler[0]or i == unluler[1]or i == unluler[2]or i == unluler[3]or i==unluler[4]or i==unluler[5]or i==unluler[6]or i==unluler[7]:
unlu.append(i)
else:
unsuz.append(i)
print("ünlüharfler",unlu)
print("ünsüzharfler",unsuz)
|
#!/usr/bin/env python
# encoding: utf-8
'''
@author: Jason Lee
@license: (C) Copyright @ Jason Lee
@contact: [email protected]
@file: jianzhi_offer_17.py
@time: 2019/5/4 14:36
@desc:
'''
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
# 返回合并后列表
def Merge(self, pHead1, pHead2):
'''@type pHead1: ListNode
@type pHead2: ListNode'''
if not pHead1:
return pHead2
if not pHead2:
return pHead1
root = None
if pHead1.val <= pHead2.val:
root = pHead1
pHead1 = pHead1.next
else:
root = pHead2
pHead2 = pHead2.next
res = root
while pHead1 and pHead2:
if pHead1.val <= pHead2.val:
res.next = pHead1
pHead1 = pHead1.next
else:
res.next = pHead2
pHead2 = pHead2.next
res = res.next
if pHead1:
res.next = pHead1
if pHead2:
res.next = pHead2
return root
|
#!/usr/bin/env python
# encoding: utf-8
'''
@author: Jason Lee
@license: (C) Copyright @ Jason Lee
@contact: [email protected]
@file: jianzhi_offer_16.py
@time: 2019/5/7 13:57
@desc:
'''
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
# 返回ListNode
def ReverseList1(self, pHead):
if not pHead:
return None
stack = []
while pHead:
stack.append(pHead)
pHead = pHead.next
head = stack.pop()
temp = head
while stack:
temp.next = stack.pop()
temp = temp.next
temp.next = None ### Important !!!!! otherwise, the result will be a circle
return head
# better solution
def ReverseList(self, pHead):
# use two pointers to reverse the list
if not pHead:
return None
pre = None
while pHead:
cur = pHead.next
pHead.next = pre
pre = pHead
pHead = cur
return pre
if __name__ == '__main__':
head = ListNode(1)
head.next = ListNode(3)
head.next.next = ListNode(4)
res = Solution()
a = res.ReverseList(head)
while a:
print(a.val)
a = a.next
|
#!/usr/bin/env python
# encoding: utf-8
'''
@author: Jason Lee
@license: (C) Copyright @ Jason Lee
@contact: [email protected]
@file: jianzhi_offer_61.py
@time: 2019/4/17 14:04
@desc:
'''
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
# use stack to store nodes
class Solution:
def Print(self, pRoot): # @type pRoot: TreeNode
if not pRoot:
return []
stack_left = []
stack_right = []
result = []
# print(pRoot.val)
result.append([pRoot.val])
if pRoot.left:
stack_left.append(pRoot.left)
if pRoot.right:
stack_left.append(pRoot.right)
while stack_left or stack_right:
temp = []
while stack_left:
node = stack_left.pop() # type: TreeNode
# print(node.val)
temp.append(node.val)
if node.right:
stack_right.append(node.right)
if node.left:
stack_right.append(node.left)
if temp:
result.append(temp)
temp = []
while stack_right:
node = stack_right.pop() # type: TreeNode
# print(node.val)
temp.append(node.val)
if node.left:
stack_left.append(node.left)
if node.right:
stack_left.append(node.right)
if temp:
result.append(temp)
return result
if __name__ == '__main__':
n1 = TreeNode(1)
n2 = TreeNode(2)
n3 = TreeNode(3)
n4 = TreeNode(4)
n5 = TreeNode(5)
n6 = TreeNode(6)
n7 = TreeNode(7)
n8 = TreeNode(8)
n9 = TreeNode(9)
n1.left = n2
n1.right = n3
n2.left = n4
n2.right = n5
n3.left = n6
n3.right = n7
n4.left = n8
n4.right = n9
res = Solution()
x = res.Print(n1)
print(x)
|
#!/usr/bin/env python
# encoding: utf-8
'''
@author: Jason Lee
@license: (C) Copyright @ Jason Lee
@contact: [email protected]
@file: jianzhi_offer_65.py
@time: 2019/4/25 13:00
@desc:
'''
class Solution:
def maxInWindows(self, num, size):
if not num or size <= 0:
return []
if size > len(num):
return []
if size == 1:
return num
f = max(num[0:size-1])
res = []
for i in range(size-1, len(num)):
temp = max(f, num[i])
res.append(temp)
if temp != f:
f = temp
else:
f = max(num[i-size+2:i+1])
return res
if __name__ == '__main__':
num = [2,3,4,2,6,2,5,1]
res = Solution()
a = res.maxInWindows(num, 3)
print(a)
|
#!/usr/bin/env python
# encoding: utf-8
'''
@author: Jason Lee
@license: (C) Copyright @ Jason Lee
@contact: [email protected]
@file: jianzhi_offer_15.py
@time: 2019/3/27 22:06
@desc:
链表中倒数第k个结点:
输入一个链表,输出该链表中倒数第k个结点。
'''
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
def FindKthToTail(head, k):
if not head or k <= 0:
return None
dummy = head
i = 1
while head.next:
i += 1
head = head.next
if k > i:
return None
head = dummy
j = 0
while j < i-k:
j += 1
head = head.next
return head.val
if __name__ == '__main__':
head = ListNode(1)
dummy = head
dummy.next = ListNode(2)
dummy = dummy.next
dummy.next = ListNode(3)
print(FindKthToTail(head, 1))
|
#!/usr/bin/env python
# encoding: utf-8
'''
@author: Jason Lee
@license: (C) Copyright @ Jason Lee
@contact: [email protected]
@file: merge_sort.py
@time: 2019/3/24 20:21
@desc:
'''
import numpy as np
def merge_sort(data):
return sort(data)
def sort(data):
if len(data) <= 1:
return data
mid = len(data) // 2
left = sort(data[:mid])
right = sort(data[mid:])
return merge(left, right)
def merge(left, right):
temp = []
i = 0
j = 0
while i < len(left) and j < len(right):
if left[i] < right[j]:
temp.append(left[i])
i = i + 1
else:
temp.append(right[j])
j = j + 1
while i < len(left):
temp.append(left[i])
i = i + 1
while j < len(right):
temp.append(right[j])
j = j + 1
return temp
if __name__ == '__main__':
a = np.random.randint(10, size=10)
b = merge_sort(a)
print(a)
print(b)
print(a)
|
#!/usr/bin/python
# HW 2 - problem 1 (list_concat)
# Author: Chris Kasper
import sys
from cell import *
def list_concat(A,B):
# Connect A.next's last element to the beginning of B
end = A
while end.next is not None:
end = end.next
end.next = B
return A
def main():
x = Cell( 13 )
y = Cell(15,x)
a = Cell( 1 )
b = Cell(2,a)
print "x is holding: " + list2string( x )
print "y is holding: " + list2string( y )
print "a is holding: " + list2string( a )
print "b is holding: " + list2string( b )
test1 = list_concat(b,y)
print "list_concat(b,y) returns: " + list2string(test1)
if __name__ == '__main__':
main()
|
##count = 0
##a = [11,7,10,6,4,5,9,8]
##while count < 2:
## temp =a[0]
## for i in range(1, len(a)):
## if temp < a[i]:
## temp = a[i]
## a.remove(temp)
## count+=1
##print temp
def prime(num):
for i in range(2, num):
if num % 2 == 0:
return False
break
else:
return True
num = input("Enter the number")
#print "prime" if prime(num) return "Prime" else: "Not a prime"
prime(num)
print "Prime" if prime(num) else "Not a prime"
|
__all__ = ['coin']
class coin():
__side = ''
def __init__(self):
self.__side = ''
def side(self):
return self.__side
def flip(self):
import numpy as np
value = np.random.randint(2)
if value == 0:
self.__side = 'tails'
else:
self.__side = 'heads'
return self.__side
|
sequence=[1,3,5,9]
doubled=[(lambda x:x*2)(x) for x in sequence]
doubled=list(map(lambda x:x*2,sequence))
print(doubled)
|
N = int(input())
distance = [0 for _ in range(N+1)]
for x, current in enumerate(distance):
if x<2 : continue
distance[x] = distance[x-1]+1
if (x % 3) == 0 : distance[x] = min(distance[int(x/3)]+1, distance[x])
if (x%2) == 0 : distance[x] = min(distance[int(x/2)]+1, distance[x])
print(distance[N])
|
#!/usr/bin/env python
#coding:utf-8
def movable(w,h,x,y,maps):
result = []
rx = x + 1
lx = x - 1
uy = y - 1
dy = y + 1
if (-1 < uy) and (maps[uy][x] == 1):
result.append((x,uy))
if (dy < h) and (maps[dy][x] == 1):
result.append((x,dy))
if (rx < w):
if (maps[y][rx] == 1):
result.append((rx,y))
if (-1 < uy) and (maps[uy][rx] == 1):
result.append((rx,uy))
if (dy < h) and (maps[dy][rx] == 1):
result.append((rx,dy))
if (-1 < lx):
if (maps[y][lx] == 1):
result.append((lx,y))
if (-1 < uy) and (maps[uy][lx] == 1):
result.append((lx,uy))
if (dy < h) and (maps[dy][lx] == 1):
result.append((lx,dy))
return result
def walk(w,h,x,y,maps):
result = set()
target = set()
target.add((x,y))
while (len(target) != 0):
(px,py) = target.pop()
result.add((px,py))
for each in movable(w,h,px,py,maps):
if (not each in result) and (not each in target):
target.add(each)
return result
def solve(w,h,maps):
visited = []
cnt = 0
for y,line in enumerate(maps):
for x,tile in enumerate(line):
if (tile == 1) and all([(not ((x,y) in land)) for land in visited]):
island = walk(w,h,x,y,maps)
if not (island in visited):
cnt += 1
visited.append(island)
return cnt
def main():
while True:
(w,h) = map(int,raw_input().split(" "))
if (w,h) == (0,0): break
maps = []
for y in xrange(h):
maps.append(map(int,raw_input().split(" ")))
print solve(w,h,maps)
if __name__ == "__main__":
main()
|
#!/usr/bin/env python
#coding:utf-8
def primep(n):
if ( n < 2): return False
if (n == 2): return True
if (n % 2 == 0) : return False
acc = 3
while (n >= acc * acc):
if (n % acc == 0) : return False
acc += 2
return True
def solve(a,d,n):
"""
simple way and slow
"""
cnt = 0
val = a
while True:
if (primep(val)) :
cnt += 1
if (cnt == n) : return val
val += d
def main():
while True:
(a,d,n) = map(int,raw_input().split(" "))
if (a == 0) and (d == 0) and (n == 0) : break
print solve(a,d,n)
if __name__ == "__main__":
main()
|
import time
def shift_char(char,index):
if not (char.isalpha() and char.islower()):
return char
code = ord(char) + index
if code > 122:
return chr(code % 122 + 96)
else:
return chr(code)
def shift_text(text,index):
return "".join(map(lambda x: shift_char(x,index),text))
def decrypt_text(text):
tmp = ""
i = 0
while not (("the" in tmp) or ("this" in tmp) or ("that" in tmp)):
tmp = shift_text(text,i)
i += 1
return tmp
while True:
try:
print decrypt_text(raw_input().strip())
except (EOFError):break
|
import random
print("1: Throw dice 0: Exit")
while True:
# We ask user to press a button
x=int(input("Press a button "))
if x==0:
print('Bye, see you !')
break
elif x==1:
print(random.randint(1,6))
else:
print("I don't understand")
|
N=int(input())
even=0
odd=0
for i in range(N+N+1):
if i % 2 == 0:
even+=i
else:
odd+=i
print(f"{odd} {even}")
|
# Loop Notes
# FOR LOOPS
for i in range(10):
print("Python")
for i in range(10):
print(i)
for i in range(1, 11):
print(i)
# prints 1-11
for i in range(5, 50, 3):
print(i)
for i in range(100, 0, -5):
print(i)
for i in range(1, 21):
print(1/i)
print("{}".format(i/1))
# IF STATEMENT
x = 4
if x > 10:
print("x is greater than 10")
elif x > 5:
print("x is greater than 5")
else:
print("Neither")
# RANDOM NUMBERS
import random # normally at top of program
print(random.randrange(10)) # random int from 0 to 9
print(random.randrange(10, 20)) # from 10 to 19
print(random.randrange(5, 101, 5)) # counting 5 to 100 by fives
print(random.random()) # float form 0 to 1
print(random.random() * 5 + 5) # float from 5 to 10
# BREAK
# automatically exits from nearest loop
for i in range(100):
print(i)
if i > 50:
break
for i in range(10000):
n = random.randrange(1000)
if n == 0:
print(i)
break
# FOR ELSE
# if you complete the FOR loop, you do the else
for i in range(1000):
n = random.randrange(1000)
if n == 0:
print(i)
break
else:
print("Else statement was triggered")
# CONTINUE
# continue ends the current iteration and skips to the next
for i in range(100):
n = random.randrange(100)
if n % 2:
continue
print(n) # skipped over for odd numbers
for a in range(1, 10):
for b in range(10):
print(str(a) + str(b))
|
import pandas as pd
import numpy as np
web_status = {
"Day": [ 1, 2, 3, 4, 5, 6],
"Visitors": [56, 33, 223, 56, 142, 229],
"Bar_tag": [245, 345, 334, 566, 432, 444]
}
df = pd.DataFrame(web_status)
#print df
#
#print df.head(3)
#
#print df.tail(2)
#
#print df.set_index('Day')
#
#
#print df
#
#
#print df.set_index('Day', inplace=True)
#
#print df
print df.Day
print df[['Day', 'Visitors']]
print df.Day.tolist()
web_status2 = np.array(df[['Day', 'Visitors']])
print web_status2
#
|
class Student :
subjectN = ["Calculus", "Software", "English"]
def __init__(self, name) :
self.name = name
self.dict = {'A+' : 4.5, 'A0' : 4.0, 'B+' : 3.5, 'B0' : 3.0, 'C+' : 2.5, 'C0' : 2.0, 'D+' : 1.5, 'D0' : 1.0, 'F' : 0}
self.score = [0, 0, 0]
self.grade = ['F', 'F', 'F']
self.avg = [0, 0, 0]
def __str__ (self) :
info = "\n"+self.name + '\n'
for a in range(0, 3):
self.avg[a] = self.dict[self.grade[a]]
for a in range(0, 3):
info += self.subjectN[a] + " " + str(self.score[a]) + " " +self.grade[a] + "\n"
info += "Average " +str((self.avg[0] + self.avg[1] + self.avg[2]) / 3.0) +"\n========"
return info
def input_score(self, subject, score):
for a in range(0, 3) :
if subject == self.subjectN[a] :
self.score[a] = score
if score >= 95 :
self.grade[a] = 'A+'
elif score >= 90 :
self.grade[a] = 'A0'
elif score >= 85 :
self.grade[a] = 'B+'
elif score >= 80 :
self.grade[a] = 'B0'
elif score >= 75 :
self.grade[a] = 'C+'
elif score >= 70 :
self.grade[a] = 'C0'
elif score >= 65 :
self.grade[a] = 'D+'
elif score >= 60 :
self.grade[a] = 'D0'
else :
self.grade[a] = 'F'
Students = ['', '', '']
for a in range(0, 3) :
Students[a] = Student(input ("Student name : "))
for b in range(0, 3) :
Students[a].input_score(Students[a].subjectN[b], int(input(Students[a].subjectN[b] +" Score : ")))
for a in range(0, 3) :
print(Students[a])
|
import os
import sys
from operator import itemgetter
# Your code here
ignore = ['"', ':', ';', ',', '.', '-', '+', '=', '/',
'\\', '|', '[', ']', '{', '}', '(', ')', '*', '^', '&']
def histo(filename):
my_dict = {}
# Open file and read
with open(os.path.join(sys.path[0], filename)) as f:
# Read file
words = f.read()
f.close()
words = words.split()
# Loop through words
for word in words:
if not word:
continue
# Remove ignored characters
word = "".join(i.lower() for i in word if not i in ignore)
if not word in my_dict.keys():
my_dict[word] = 1
else:
my_dict[word] += 1
items = list(my_dict.items())
items.sort(key=lambda e: (-e[1], e[0]))
print(items)
for tup in items:
print(f'{tup[0]:20} {"#" * tup[1]}')
histo('robin.txt')
|
number = int(input(''))
list = []
for i in range(0,number):
newNo = int(input(''))
a = list.append(newNo)
print("Elements are",list[i],i)
|
import math
import copy
class Vector(list):
""" Vector.py
6/24/2009 by Travis Jones
simple list-based vector class
Notes:
- Inspired by http://code.activestate.com/recipes/52272/
- Supports 2D and 3D vectors
- Constructor takes either a tuple or a list
- Has properties x, y and z for ease of use
- Allows for Vector add/mul with a scalar or another Vector
"""
def __init__(self, *vec):
if len(vec) == 0:
super(Vector, self).__init__([0.0, 0.0, 0.0])
else:
if type(vec[0]) is list:
super(Vector, self).__init__(vec[0])
else:
if type(vec) is tuple:
super(Vector, self).__init__([i for i in vec])
def __add__(self, other):
if type(other) is list or type(other) is Vector:
return Vector(map(lambda x, y: x + y, self, other))
else:
return Vector([self[i] + other for i in range(len(self))])
def __sub__(self, other):
if type(other) is list or type(other) is Vector:
return Vector(map(lambda x, y: x - y, self, other))
else:
return Vector([self[i] + other for i in range(len(self))])
def __mul__(self, other):
if type(other) is list or type(other) is Vector:
return Vector(map(lambda x, y: x * y, self, other))
else:
return Vector([self[i] * other for i in range(len(self))])
# Properties of X, Y, Z for convenience
def __GetX(self):
return self[0]
def __SetX(self, value):
self[0] = value
x = property(fget=__GetX, fset=__SetX, doc="what?")
def __GetY(self):
return self[1]
def __SetY(self, value):
self[1] = value
y = property(fget=__GetY, fset=__SetY, doc="what?")
def __GetZ(self):
return self[2]
def __SetZ(self, value):
self[2] = value
z = property(fget=__GetZ, fset=__SetZ, doc="what?")
def out(self):
print self
def Normalized(self):
if len(self) > 3 or len(self) < 2:
raise Exception("Normalization not supported on this Vector")
temp = copy.deepcopy(self)
if len(self) == 2:
length = math.sqrt(temp[0] * temp[0] + temp[1] * temp[1])
temp[0] /= length
temp[1] /= length
else:
length = math.sqrt(temp[0] * temp[0] + temp[1] * temp[1] + temp[2] * temp[2])
temp[0] /= length
temp[1] /= length
temp[2] /= length
return temp
def Normalize(self):
n = self.Normalized()
for i in range(len(n)):
self[i] = n[i]
if __name__ == "__main__":
a = Vector()
a = Vector([2.0, 2.0, 2.0])
a.x = 4.0
b = a * Vector(3, 3, 3)
c = Vector(2.0, 2.0)
d = Vector(9.0, 7.0)
dist = d - c
print dist
dist.Normalize()
print dist
print c + dist
|
import random
#import maths
def jump():
print("---------------------")
print("Combat jump initiated. \n")
astro_mods = input("Astrogation+EDU skill modifier: ")
astro_mods = int(astro_mods)
dice = random.randint(1, 6) + random.randint(1, 6)
dice_total = dice
dice_total_2 = dice_total+(astro_mods-2)
if dice_total_2 < 4:
print("Astrogation plot failed. Try again next turn.")
jump()
else:
astro_effect = dice_total_2-4
jump_mods = input("Course has been successfully plotted. Engineer J-Drive+EDU skill modifier: ")
jump_mods = int(jump_mods)
dice_2 = random.randint(1, 6) + random.randint(1, 6)
dice_total = dice_2
dice_total_3 = dice_total + (jump_mods-2) + astro_effect
maint = input("Is the ships maintenance up to date? y/n ")
if maint == "y":
maint = 0
else:
maint = -1
fuel = input("Are you using refined fuel? y/n ")
if fuel == "y":
fuel = 0
else:
fuel = -2
diam = input("are you outside the 100D limit of a planetary body? y/n ")
if diam == "y":
diam = 0
vbj_mod = -4
else:
diam = -4
vbj_mod = +2
dice_total_3 = dice_total_3 + maint + fuel + diam
eng_effect = dice_total_3 - 4
distance_var = random.randint(1, 6) + random.randint(1, 6) + astro_effect
print("distance var")
print(distance_var)
time_var = random.randint(1, 6) + random.randint(1, 6) + eng_effect
print("time var")
print(time_var)
vbj_dice = random.randint(1, 6) + random.randint(1, 6) + vbj_mod
vbj_drive = random.randint(1, 6) + random.randint(1, 6)
vbj_table = {
2: "\tNo additional effects.",
3: "\tJump drive requires lengthy recalibration, taking" + str(vbj_drive) + "days after emergence.",
4: "\tJump drive requires lengthy recalibration, taking" + str(vbj_drive) + "days after emergence.",
5: "\tJump drive requires lengthy recalibration, taking" + str(vbj_drive) + "days after emergence.",
6: "\tJump drive requires minor repairs after emergence.",
7: "\tJump drive requires minor repairs after emergence.",
8: "\tJump drive requires major repairs at a port after emergence.",
9: "\tJump drive requires major repairs at a port after emergence.",
10: "\tJumpspace intrusions occur, dealing " + str(vbj_drive-2) + "% Hull damage every day whilst in jumpspace.",
11: "\tJumpspace intrusions occur, dealing " + str(vbj_drive-2) + "% Hull damage every day whilst in jumpspace. Jumpdrive is destroyed.",
12: "\tJumpspace intrusions occur, dealing " + str(vbj_drive-2) + "% Hull damage every day whilst in jumpspace. Jumpdrive is destroyed.",
13: "\tSevere jumpspace intrusions occur, dealing " + str(vbj_drive+5) + "% Hull damage every day whilst in jumpspace. Jumpdrive is destroyed.",
}
if distance_var <= 5 or time_var <= 5:
bad_jump = ("\tSomething went wrong with the transition into jumpspace. Each Traveller must make an END and INT check. One of the checks needs 6+, the other 10+. Traveller chooses which."
+"\nEND check determines physical effects like nausea and possible vomiting. INT check determines mental effects like paranoia and instability."
+"\nNote the EFFECT of each roll and consult the GM for repercussions. (Traveller Companion pg. 142)")
else:
bad_jump = ""
if distance_var <=5 and time_var <= 5:
vbj_result = vbj_table.get(vbj_dice)
bad_jump = ""
very_bad_jump = ("\tSomething went very wrong with the transition into jumpspace. Each Traveller must make an END and INT check. One of the checks needs 8+, the other 12+. Traveller chooses which."
+"\nEND check determines physical effects like nausea and possible vomiting. INT check determines mental effects like paranoia and instability."
+"\nNote the EFFECT of each roll and consult the GM for repercussions. (Traveller Companion pg. 143)")
else:
very_bad_jump = ""
vbj_result = ""
distance_variance = {
2: 110-(random.randint(1, 6) + random.randint(1, 6) + random.randint(1, 6)),
3: 110-(random.randint(1, 6) + random.randint(1, 6)),
4: 105-(random.randint(1, 6)),
5: 100+((random.randint(1, 6) + random.randint(1, 6))*10),
6: 100+((random.randint(1, 6) + random.randint(1, 6))*5),
7: 100+(random.randint(1, 6) + random.randint(1, 6) + random.randint(1, 6)+ random.randint(1, 6)),
8: 100+(random.randint(1, 6) + random.randint(1, 6) + random.randint(1, 6)),
9: 100+(random.randint(1, 6) + random.randint(1, 6)),
10: 100+(random.randint(1, 6)),
11: 100+(random.randint(1, 3)),
12: 100
}
if distance_var <= 2:
distance_var = 2
elif distance_var >= 12:
distance_var = 12
distance_var_2 = distance_variance.get(distance_var)
if distance_var_2 <= 100:
distance_var_2 = 100
precipitation = "Your ship tried to exit Jumpspace within 100D of a planetary body. The jump drive has overheated and needs to cool for " + str(random.randint(6, 24)) + " hours before it can be used again."
else:
precipitation = ""
time_variance = {
2: (random.randint(1, 6) +(random.randint(1, 6) +(random.randint(1, 6) +(random.randint(1, 6)))))*4,
3: (random.randint(1, 6) +(random.randint(1, 6) +(random.randint(1, 6) +(random.randint(1, 6)+(random.randint(1, 6))))))*2,
4: (random.randint(1, 6) +(random.randint(1, 6) +(random.randint(1, 6) +(random.randint(1, 6)))))*2,
5: (random.randint(1, 6) +(random.randint(1, 6) +(random.randint(1, 6))))*2,
6: (random.randint(1, 6) +(random.randint(1, 6) +(random.randint(1, 6) +(random.randint(1, 6)+(random.randint(1, 6)))))),
7: (random.randint(1, 6) +(random.randint(1, 6) +(random.randint(1, 6) +(random.randint(1, 6))))),
8: (random.randint(1, 6) +(random.randint(1, 6) +(random.randint(1, 6)))),
9: (random.randint(1, 6) +(random.randint(1, 6))),
10: (random.randint(1, 6)),
11: (random.randint(1, 3)),
12: 160
}
if time_var < 2:
time_var = 2
elif time_var >= 12:
time_var = 12
time_var_2 = time_variance.get(time_var)
if time_var_2 != 160:
o_e_check = random.randint(1, 6)
if o_e_check % 2 == 0:
odd_even = 0+time_var_2
else:
odd_even = 0-time_var_2
else:
odd_even = 0
#six_d = random.randint(1, 6) + random.randint(1, 6) + random.randint(1, 6) + random.randint(1, 6) + random.randint(
# 1, 6) + random.randint(1, 6)
misjump_time = 160 + (random.randint(1, 6) * 24) #+ odd_even
#misjump_days = round((misjump_time / 24), 2)
jump_time = 160 + odd_even
#jump_days = round((jump_time / 24), 2)
seconds_mj = (misjump_time * 60 * 60) + random.randint(1, 3599)
seconds = (jump_time * 60 * 60) + random.randint(1, 3599)
if dice_total_3 < 4:
print("Jump error detected!")
if dice_total_3 == 3:
m, s = divmod(seconds_mj, 60)
h, m = divmod(m, 60)
d, h = divmod(h, 24)
print("The jump takes slightly longer than usual (d/h/m/s): " + "%d:%d:%02d:%02d" % (d, h, m, s))
print("You are " + str(distance_var_2) + " diameters away from your target.")
if precipitation:
print(precipitation)
if bad_jump:
print(bad_jump)
if very_bad_jump:
print(very_bad_jump)
if vbj_result:
print(vbj_result)
elif dice_total_3 == 2 or 1:
m, s = divmod(seconds, 60)
h, m = divmod(m, 60)
d, h = divmod(h, 24)
print("The jump takes (d/h/m/s): " + "%d:%d:%02d:%02d" % (d, h, m, s))
print("The plotted course had an error. You arrive in the desired system " + str(random.randint(1, 6) * random.randint(100, 150)) + " diameters away from your target.")
if bad_jump:
print(bad_jump)
if very_bad_jump:
print(very_bad_jump)
if vbj_result:
print(vbj_result)
elif dice_total_3 <= 0:
print("It's all gone wrong. Catastrophic misjump. Consult the GM on exactly what has happened.")
else:
print("Jump successful.")
m, s = divmod(seconds, 60)
h, m = divmod(m, 60)
d, h = divmod(h, 24)
print("The jump takes (d/h/m/s): " + "%d:%d:%02d:%02d" % (d, h, m, s))
print("You are " + str(distance_var_2) + " diameters away from your target.")
if precipitation:
print(precipitation)
if bad_jump:
print(bad_jump)
if very_bad_jump:
print(very_bad_jump)
if vbj_result:
print(vbj_result)
jump()
jump()
|
from Crypto.Hash import SHA256
def RSA_sign(sk,code):
'''Uses the RSA secret key sk to return a signature (as a string) for the string code.
Preconditions: sk is an RSA secret key, code is a string'''
code = code.encode('utf-8')
hash = SHA256.new(code).digest()
signature = sk.sign(hash,'')
return str(signature[0])
def RSA_verify(pk,code,sig):
'''Returns True if sig is a valid signature for code when signed by the counterpart
to the RSA public key object pk.
Preconditions: pk is an RSA public key, code and sig are strings'''
sig = int(sig)
sig = (sig,) #for some reason, sig needs to be a tuple
code = code.encode('utf-8')
hash = SHA256.new(code).digest()
return pk.verify(hash,sig)
|
#With a given integral number n, write a program to generate a dictionary
# that contains (i, i*i) such that is an integral number between 1 and n (both included).
# and then the program should print the dictionary.
#Suppose the following input is supplied to the program:
#8
#Then, the output should be:
#{1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64}
user_input = int(input("Please enter an integer : "))
res = {i: i*i for i in range(1, user_input+1)}
print(res)
|
#Write a program that accepts a comma separated sequence of words as input and prints the words
# in a comma-separated sequence after sorting them alphabetically.
#Suppose the following input is supplied to the program:
#without,hello,bag,world
#Then, the output should be:
#bag,hello,without,world
user_input = input("Please enter a comma-separated sequence of words : ").split(",")
user_input.sort()
print(",".join(user_input))
|
# Reverse Cipher
# http://www.nostarch.com/Crackingcodes (BSD Licensed)
# input only works for Python 3, we'll use raw_input() instead
#message = input('Enter message: ')
message = raw_input('Enter message: ')
translated = ''
i = len(message) - 1
while i >= 0:
translated = translated + message[i]
i = i - 1
print(translated)
|
cake = float(input("Enter the pieces of cake you have eaten:"))
kilometers= float(input("Enter the Kilometers you have run:"))
kilometers_ran = kilometers*100
cake_jog= ((225*cake)-kilometers_ran)
print ("This is how many calories you have lost:" + str(cake_jog))
|
import multiprocessing
from concurrent.futures import ThreadPoolExecutor, wait, FIRST_COMPLETED
#Creating a thread pool to manage calls equal to
class ThreadPool(object):
def __init__(self, machine):
self.outlets = machine.outlets_getter()
self.pool = ThreadPoolExecutor(max_workers=self.outlets)
m = multiprocessing.Manager()
self.lock = m.Lock()
self.machine = machine
#futures denote number of threads running in parallel
self.futures = []
def make_beverage(self, name):
try:
future = self.pool.submit(self.machine.make_beverage, name, self.lock)
if not future.done():
self.futures.append(future)
except:
print("Something is wrong with the machine")
#This function returns true if there are less beverages being made in parallel than outlets number, else false
def isPoolAvailable(self):
#We remove finished threads from futures variables
self.futures = [future for future in self.futures if future._state=="RUNNING"]
#If there are already n(outlets) number of beverages being brewed, we don't want to brew more
if len(self.futures) >= self.outlets:
return False
else:
return True
|
# -*- coding: utf-8 -*-
"""
Created on Sat May 7 19:39:32 2016
@author: coste
"""
def det(matriz):
det = 1
for i in range(len(matriz)):
det *= matriz[i][i]
return det
matriz = [[88, 27, 46], [0, 57, 20], [0, 0, 15]]
print(det(matriz))
|
print("Welcome to our programme!")
age = float(input("Please enter your age:"))
if 0 < age <= 19:
if 0 < age < 1:
print("You are an infants.")
if 10 < age <= 19:
print("You are an adolescent.")
else:
print("You are a child.")
elif age > 19:
print("You are an adult.")
else:
print("Please enter a valid age.")
|
def readSudoku(name):
with open(name, "r") as puzzle:
return [[int(i) for i in line.split(",")] for line in puzzle]
def processRij(x, num):
for y in range(0,9):
if num in mogelijkNum[x][y]:
mogelijkNum[x][y].remove(num)
def processColumn(y, num):
for x in range(0,9):
if num in mogelijkNum[x][y]:
mogelijkNum[x][y].remove(num)
def processBox(x, y, num):
boxX = int(x/3)
boxY = int(y/3)
for x in range(3*boxX, 3*boxX + 3):
for y in range(3*boxY, 3*boxY + 3):
if num in mogelijkNum[x][y]:
mogelijkNum[x][y].remove(num)
def checkMogelijkeNum(sudoku):
mogelijkNum = []
for line in sudoku:
rij = []
for num in line:
if(num == 0):
rij.append([1,2,3,4,5,6,7,8,9])
else:
rij.append([num])
mogelijkNum.append(rij)
return mogelijkNum
def isSudokuNotFull():
for x in range(0,9):
for y in range(0,9):
if sudoku[x][y] == 0:
return True
return False
sudoku = readSudoku("puzzle1.sudoku")
mogelijkNum = checkMogelijkeNum(sudoku)
while(isSudokuNotFull()):
for x in range(0,9):
for y in range(0,9):
if len(mogelijkNum[x][y])== 1:
value = mogelijkNum[x][y][0]
print(value, "is value")
sudoku[x][y] = value
processRij(x, value)
processColumn(y, value)
processBox(x, y, value)
for line in sudoku:
print(line)
|
#find the first non-repeating character in a string
def first_nonrepeat(str):
for i, c in enumerate(str):
if c not in str[:i] + str[i+1:]:
return c
else:
print "None"
|
penny = {'value': 1}
nickel = {'value': 5}
dime = {'value': 10}
quarter = {'value': 25}
dollar = {'value': 100}
class CoinChanger():
def make_change(self, p):
current_pouch = []
coins = [dollar, quarter, dime, nickel, penny]
for coin in coins:
(p, current_pouch) = self.find_coins(coin, p, current_pouch)
return current_pouch
def find_coins(self, coin, amount_left, coin_list):
if coin['value'] <= amount_left:
while coin['value'] <= amount_left:
coin_list.append(coin)
amount_left -= coin['value']
return (amount_left, coin_list)
|
#comparison_operator
statement1=input("Enter first statement")
statement2=input("Enter second statement")
print(len(statement1))
print(len(statement2))
#==
print(len(statement1)==len(statement2))
#!=
print(len(statement1)!=len(statement2))
#<
print(len(statement1)<len(statement2))
#>
print(len(statement1)>len(statement2))
#<=
print(len(statement1)<=len(statement2))
#>=
print(len(statement1)>=len(statement2))
|
class Calorie:
'''
formula: 10 * weight + 6.25 * height - 5 * age + 5 - 10 * temperature
'''
def __init__(self, weight, height, age, temperature):
self.weight = weight
self.height = height
self.age = age
self.temperature = temperature
def calculate(self):
calorie_to_consume = (10 * self.weight) + (6.25 * self.height) - (5 * self.age) + 5 - (10 * self.temperature)
return calorie_to_consume
my_intake = Calorie(91, 187, 32, 32)
|
# Import argv from module 'sys'
from sys import argv
# Split parameters to each variable
script, input_file = argv
# Create function 'print_all' passing argument 'f'. f will be a file
def print_all(f):
# Print output result read the file 'f'
print(f.read())
# Create funciton 'rewind' passing a file 'f'
def rewind(f):
# Move cursor to first lines of file
f.seek(0)
# Create function print_a_line passing 2 arguments:
# number of line toread and a file
def print_a_line(line_count, f):
# Print numberof line and its content
print(line_count, f.readline())
# Store on variable 'current_file' the file opened
current_file = open(input_file)
print("First let's print the whole file:\n")
# Call function 'print_all' passing opened file
print_all(current_file)
print("Now let's rewind, kind of like a tape.")
# Call 'rewind' function passing opened file
rewind(current_file)
print("Let's print three lines:")
# Set number of line to 1
current_line = 1
# Call function 'print_a_line'
print_a_line(current_line, current_file)
current_line = current_line + 1
print_a_line(current_line, current_file)
current_line = current_line + 1
print_a_line(current_line, current_file)
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
#title :ex15.py
#description :http://learnpythonthehardway.org/book/ex15.html
#author :Gon
#date :20160618
#version :1.0
#usage :python ex15.py
#notes :
#python_version :2.7.6
#==============================================================================
from sys import argv
script, filename = argv
txt = open(filename)
print "Here's your file %r:" % filename
print txt.read()
print "Type the filename again:"
file_again = raw_input("> ")
txt_again = open(file_again)
print txt_again.read()
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
#title :readline.py
#description :read lines from a textfile
#author :Gon
#date :20160619
#version :1.0
#usage :python readline.py
#notes :
#python_version :2.7.6
#==============================================================================
from sys import argv
script, input_file = argv
def print_a_line(filename):
for i in range(0,5):
print filename.readline()
current_file = open(input_file)
current_file.seek(0)
print_a_line(current_file)
|
# 52198150
import copy
def bubble_sort(n, array):
for j in range(n-1):
flag = False
for i in range(n-1-j):
if array[i] > array[i+1]:
array[i], array[i+1] = array[i+1], array[i]
flag = True
if flag is False:
return array
print(*array)
return array
if __name__ == '__main__':
n = int(input())
arr = [int(i) for i in input().split()]
sort_arr = copy.deepcopy(arr)
sort_arr = bubble_sort(n, sort_arr)
if arr == sort_arr:
print(*arr)
|
# 52073600
def String(word1, word2):
word1 = sorted(list(word1))
word2 = sorted(list(word2))
k = 0
extra_symbols = []
while len(word1) != len(word2):
if len(word1) < len(word2):
for x, y in zip(word1, word2):
if x != y:
word1.insert(k, '0')
break
k += 1
if len(word1) != len(word2):
word1.append('0')
else:
for x, y in zip(word1, word2):
if x != y:
word2.insert(k, '0')
break
k += 1
if len(word1) != len(word2):
word2.append('0')
for x, y in zip(word1, word2):
if x == '0':
extra_symbols.append(y)
if y == '0':
extra_symbols.append(x)
return extra_symbols
if __name__ == '__main__':
print(*String(input(), input()))
|
# 52168257
def phone_buttons(prefix, sequence, cur_button_in_sequence, n, i):
if n == 0:
sequence.append(prefix)
i = 0
for j in range(11):
if n == j:
for ch in cur_button_in_sequence[i]:
phone_buttons(prefix + ch, sequence,
cur_button_in_sequence, n-1, i+1)
return sequence
if __name__ == '__main__':
prefix = ''
number = [*map(int, input())]
buttons = {
2: 'abc',
3: 'def',
4: 'ghi',
5: 'jkl',
6: 'mno',
7: 'pqrs',
8: 'tuv',
9: 'wxyz'}
cur_button_in_sequence = []
for i in range(len(number)):
cur_button_in_sequence.append(buttons[number[i]])
n = len(cur_button_in_sequence)
result = phone_buttons('', [], cur_button_in_sequence, n, 0)
print(*result)
|
# 52113132
class Stack:
def __init__(self):
self.items = []
def is_empty(self):
return self.items == []
def push(self, item):
self.items.append(item)
def pop(self):
return self.items.pop()
def peek(self):
return (self.items[-1])
def is_correct_bracket_seq(brackets):
stack = Stack()
for i in brackets:
if i in '([{':
stack.push(i)
else:
try:
first = stack.peek()
except BaseException:
return False
if i == ')' and first == '(':
stack.pop()
elif i == ']' and first == '[':
stack.pop()
elif i == '}' and first == '{':
stack.pop()
else:
return False
if stack.is_empty():
return True
else:
return False
if __name__ == '__main__':
print(is_correct_bracket_seq(input()))
|
from tree import Tree
treeVals = [3, 9, 20, None, None, 15, 7]
tree = Tree(treeVals)
root = tree.root
class Solution():
# use a global variable to track if any subtree is unbalanced
ans = True
def isBalanced(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
def helper(node):
if node is None:
return 0
l_depth = helper(node.left)
r_depth = helper(node.right)
if abs(l_depth - r_depth) > 1:
self.ans = False
return max(l_depth, r_depth) + 1
helper(root)
return self.ans
# without using class property: return tuple instead
class Solution2:
def isBalanced(self, root: TreeNode) -> bool:
def helper(node):
if not node:
return 0, True
leftDepth, leftBalanced = helper(node.left)
rightDepth, rightBalanced = helper(node.right)
depth = max(leftDepth, rightDepth) + 1
if abs(leftDepth - rightDepth) > 1:
return depth, False
return depth, leftBalanced and rightBalanced
return helper(root)[1]
solver = Solution()
print(solver.isBalanced(root))
|
# Your previous Plain Text content is preserved below:
#
# This is just a simple shared plaintext pad, with no execution capabilities.
#
# When you know what language you'd like to use for your interview,
# simply choose it from the dropdown in the top bar.
#
# You can also change the default language your pads are created with
# in your account settings: https://coderpad.io/settings
#
# Enjoy your interview!
#
# Hello
#
# Hi there!
#
# Python please.
# Can you call me at 650 283 6267? Ok! That works too. Nice to e-meet you!
# My first question is which language you prefer ?
# Did you get my email where I wrote we'll be doing text only?
# NP. So let's switch to the python language (top right pulldown)
#
#
# You can click on the Run button to see how it works.
# OK, let me copy the exercise....
# got it!
#
# A simple coding exercise problem (no tricks here):
#
# Find the sum of (the fibonacci series) in any given range
# ---------------------------------------------------------
#
# First, the fibonacci series definition:
#
# The n-th Fibonacci number fib(n) is a number in a series defined
# recursively this way:
#
# fib(0) may be defined as 0 (for convenience)
# fib(1) the 1st number in the series, is 1
# fib(n) is the sum of the previous 2 fibonacci numbers
#
# The first 10 numbers in the fib(n) series (fib(1), ..., fib(10)) are:
#
# 1, 1, 2, 3, 5, 8, 13, 21, 34, 55
#
# Calculating fib(n) where n is a natural number can be solved
# in more than one way. Pick whichever you feel comfortable with
# Likewise, pick the programming language you feel comfortable with.
#
# Now to the problem we want to solve:
# A sum of fibonacci numbers between two natural numbers M and N
# Is the sum of the sub-series between fib(M) and fib(N) inclusive.
#
# The sum_fib(m, n) function returns the sum of fibonacci numbers
# between m and n (inclusive):
#
# Notes/tips:
# - Try writing a few input->output examples first,
# to make sure you understand the problem.
# - Please pay attention to correctness above all
# - Please pay attention to edge cases
# - Bonus points if you can solve this efficiently
# - Bonus points if your solution is clear/simple/straightforward
# - Bonus points for style and neatliness, spacing, indentation
# - Bonus points for modularity/refactoring (no code repetitions)
# - Bonus points for good abstractions/APIs that makes the most sense
# - Bonus points for good var/func naming (code does what it says)
# - You must test your solution online by using a main() that will
# call your solution in a convincing way to establish correctness.
# - Most bonus points for GOOD self-testing (not just a particular case)
# Feel free to add assertions to make sure what you write is correct.
#
# Feel free to ask any question at any time.
#
#
# NOTE: you are allowed to add as many functions as you need
"""
Let me write block comment to walk through the problem.
First make sure I get the question:
A series F is Fibonacci if F[1] = 1, F[2] = 1, F[3] = 2, ... F[n] = F[n - 1] + F[n - 2].
Given m, n where m <= n (equal allowed), we want to find sum(F[i] for i in range(m, n + 1)) (ending index exclusive).
A few example:
sum_fib(2, 4) = F[2] + F[3] + F[4] = 1 + 2 + 3 = 6
So we need to:
(1) calculate Fibonacci number efficiently (F[n]). This can be done with dynamic programming.
(2) sum them up in desired range. This step can be done by saving F[1] to F[n] in an array, or more efficiently, keep a running total for F[1] ... F[n], then take two snapshots at n = m and n = n. Subtract the two to get the sum between F[m], F[n].
"""
def F(m):
"""
Write a function that compute Fibbo number at index m.
"""
large, small = 1, 0
# dynamically update the two variables
for i in range(m):
large, small = large + small, large
return small
def sum_fib(m, n):
"""
Let me start simple. Just call F() for n in a range and see if we can simplify further.
I Believe we can simplify it. Because when computing F[n] (larger number), we have computed F[n-1], F[n-2] ... F[m].
"""
if m > n:
m, n = n, m
return sum(F(i) for i in range(m, n + 1)) # inclusive.
def sum_fib_dp(m, n):
"""
A dynamic programming version.
"""
if m > n:
m, n = n, m
large, small = 1, 0
# a running sum for Fibbo m ~ n + 1
running = 0
# dynamically update the two variables
for i in range(n):
large, small = large + small, large
# note that (i + 1) -> small is basically mapping m -> F[m]
if m <= i + 1 <= n:
running += small
return running
def main():
# for ... :
# # THOROUGHLY test your solution
# ...
# Test Fibonacci computation
assert(F(0) == 0)
assert(F(4) == 3)
assert(F(5) == 5)
assert(F(6) == 8)
assert(F(7) == 13)
# test Fibbonacci sum in range (pass test)
assert(sum_fib(1, 1) == 1)
assert(sum_fib(1, 2) == 2)
assert(sum_fib(1, 3) == 4)
assert(sum_fib(1, 5) == 12)
# test DP against normal version
assert(sum_fib(1, 1) == sum_fib_dp(1, 1))
assert(sum_fib(1, 2) == sum_fib_dp(1, 2))
assert(sum_fib(1, 3) == sum_fib_dp(1, 3))
assert(sum_fib(1, 5) == sum_fib_dp(1, 5))
# large m, n
for n in range(1000, 1100):
m = n + 10
assert(sum_fib(n, m) == sum_fib_dp(n, m))
# m == n
for n in range(1000, 1100):
assert(sum_fib(n, n) == sum_fib_dp(n, n))
main()
|
"""
Problem Description:
Given a matrix of letters, and a word. Check whether the word
`exists` in the matrix.
The word can start at any position of the matrix. Every next letter
is connected in three possibe dicrections:
(1) right
(2) down
(3) lower right
Example:
[["C", "B", "A", "N"],
["A", "O", "O", "L"],
["N", "N", "N", "A"]]
"BON" -> True
"BAN" -> True
"COOL" -> True
"ANNA" -> True
"ANNNA" -> True
"LOOB" -> False
"""
def dfs(board, r, c, word):
# base case (r, c can be out of bound here)
if word == "": return True
if r >= len(board) or c >= len(board[0]): return False
# check for out-of-bound after base case
return any(dfs(board, r + dr, c + dc, word[1:])
for dr, dc in [(1, 0), (0, 1), (1, 1)]
if word[0] == board[r][c])
def exist(board, word):
return any(dfs(board, r, c, word)
for r in range(len(board))
for c in range(len(board[0])))
|
class Solution:
"""
A node must have two children: missing one is marked as #.
"#" does not have children.
_9_
/ \
3 2
/ \ / \
4 1 # 6
/ \ / \ / \
# # # # # #
Serialization: [9,3,4,#,#,1,#,#,2,#,6,#,#]
"""
def isValidSerialization(self, preorder: str) -> bool:
"""
:type preorder: str
:rtype: bool
"""
stack = []
for c in preorder.split(','):
stack.append(c)
# while stack[-2:] == ['#', '#']:
# must use >=, because stack = [#, #] should return False
# case: [1,#,#,#,#]
while len(stack) >= 2 and stack[-2] == stack[-1] == u'#':
stack.pop()
stack.pop()
if not stack:
return False
# once a node is checked, it's marked "#" in stack.
# It's children are removed from stack
stack[-1] = u'#'
# breakpoint
print(stack)
return stack == [u'#']
"""
Trace
stack = [9]
stack = [9, 3]
stack = [9, 3, 4]
stack = [9, 3, 4, #]
_9_
/ \
3 2
/ \ / \
# 1 # 6
/ \ / \
# # # #
stack = [9, 3, 4, #, #] -> [9, 3, #]
stack = [9, 3, #, 1]
stack = [9, 3, #, 1, #]
_9_
/ \
3 2
/ \ / \
# # # 6
/ \
# #
_9_
/ \
# 2
/ \
# 6
/ \
# #
stack = [9, 3, #, 1, #, #] -> [9, 3, #, #] -> [9, #]
stack = [9, #, 2]
stack = [9, #, 2, #]
stack = [9, #, 2, #, 6]
stack = [9, #, 2, #, 6, #]
_9_
/ \
# 2
/ \
# #
_9_
/ \
# #
stack = [9, #, 2, #, 6, #, #] -> [9, #, 2, #, #] -> [9, #, #] -> [#]
return True
"""
|
import pygame
from tkinter import Tk, Canvas, ALL
###########################################
# Animation class
###########################################
class Animation(object):
# Override these methods when creating an animation
def mousePressed(self, event): pass
def keyPressed(self, event): pass
def timerFired(self): pass
def init(self): pass
def redrawAll(self): pass
def run(self, width=1000, height=600):
# create the root and the canvas
root = Tk()
self.width = width
self.height = height
self.boardDim = self.width - 400
self.canvas = Canvas(root, width=width, height=height)
self.canvas.pack()
# set up events
def redrawAllWrapper():
self.canvas.delete(ALL)
self.redrawAll()
def mousePressedWrapper(event):
self.mousePressed(event)
redrawAllWrapper()
def keyPressedWrapper(event):
self.keyPressed(event)
redrawAllWrapper()
root.bind("<Button-1>", mousePressedWrapper)
root.bind("<Key>", keyPressedWrapper)
# set up timerFired events
self.timerFiredDelay = 50
def timerFiredWrapper():
self.timerFired()
redrawAllWrapper()
# pause, then call timerFired again
self.canvas.after(self.timerFiredDelay, timerFiredWrapper)
# init and get timerFired running
self.init()
timerFiredWrapper()
pygame.init()
# launch the app
root.mainloop()
|
numbers = ['4', '5','3']
s = 0
for n in numbers:
s = s + int(n)
print (s)
|
"""
CtCi
10.5 Given a sorted array of strings that is interspersed with empty strings, write a method
to find the location of a given string.
BRUTE FORCE:
linearly search the element.
Time: O(n) Space: O(1)
better
Keep searching both sides of the arr if mid is empty string
if element found, search either side
"""
def sparse_search(arr, element):
"""
Time avg: O(nlgn)
Time worst: O(n)
Space: O(1)
"""
if not arr:
return -1
return binary_search(arr, element, 0, len(arr)-1)
def binary_search(arr, element, low, high):
if low > high:
return -1
mid = (low + high) / 2
if arr[mid] == element:
return mid
if arr[mid] == "":
res = binary_search(arr, element, low, mid-1) # search left
if res == -1:
res = binary_search(arr, element, mid+1, high) # search right
return res
elif element < arr[mid]:
return binary_search(arr, element, low, mid-1)
else:
return binary_search(arr, element, mid+1, high)
def sparse_search2(arr, element):
"""
Time avg: O(nlgn)
Time worst: O(n)
Space: O(1)
"""
if not arr:
return -1
return binary_search2(arr, element, 0, len(arr)-1)
def binary_search2(arr, element, low, high):
if low > high:
return -1
mid = (low + high) / 2
if arr[mid] == "":
left = mid-1
right = mid+1
while True:
if left < low and right > high:
return -1
elif left >= low and arr[left] != "":
mid = left
break
elif right <= high and arr[right] != "":
mid = right
break
left -= 1
right += 1
if arr[mid] == element:
return mid
elif element < arr[mid]:
return binary_search2(arr, element, low, mid-1)
return binary_search2(arr, element, mid+1, high)
if __name__ == '__main__':
arr1 = ["at", "", "", "", "ball", "", "", "car", "", "", "dad", "", ""]
print sparse_search(arr1, "at") # 0
print sparse_search(arr1, "ball") # 4
print sparse_search(arr1, "car") # 7
print sparse_search(arr1, "dad") # 10
print sparse_search2(arr1, "at") # 0
print sparse_search2(arr1, "ball") # 4
print sparse_search2(arr1, "car") # 7
print sparse_search2(arr1, "dad") # 10
|
"""
Implement stack data structure with 2 queues.
"""
class Queue(object):
"""Queue Data Structure"""
def __init__(self, queue=[]):
super(Queue, self).__init__()
self.queue = queue
def enqueue(self, item):
self.queue.append(item)
def dequeue(self):
if not self.queue:
return
return self.queue.pop(0)
def peek_last(self):
"""return the last inserted element in the queue"""
if not self.queue:
return
return self.queue[-1]
def is_empty(self):
return len(self.queue) == 0
def print_queue(self):
print self.queue
class Stack(object):
"""docstring for Stack"""
def __init__(self):
self.queue1 = Queue([])
self.buffer = Queue([])
def push(self, item):
"""
Put item into queue 1.
"""
self.queue1.enqueue(item)
return
def pop(self):
"""
We want to pop the last element in queue1, so we keep popping queue1 items
and put in queue2(acts as a holding container) until the last element in queue1.
put the last element into a variable and return it.
then we put queue2 items back into queue1.
"""
if self.queue1.is_empty():
return
# move queue1 elements into buffer queue except for last element
while True:
value = self.queue1.dequeue()
if not self.queue1.is_empty():
self.buffer.enqueue(value)
else:
break
# put elements in buffer queue back into queue 1
while not self.buffer.is_empty():
element = self.buffer.dequeue()
self.queue1.enqueue(element)
return value
def top(self):
"""
Look at the last element in queue1
"""
if not self.queue1:
return
return self.queue1.peek_last()
def print_stack(self):
print "queue 1 is", self.queue1.print_queue()
print "queue 2 is", self.buffer.print_queue()
def main():
stack1 = Stack()
stack1.push(1)
stack1.push(3)
stack1.push(5)
stack1.push(7)
stack1.print_stack()
print stack1.pop()
stack1.print_stack()
print stack1.pop()
stack1.print_stack()
print stack1.pop()
stack1.print_stack()
print stack1.pop()
stack1.print_stack()
if __name__ == '__main__':
main()
|
"""
Implementing binary search tree with parent pointer
"""
class Node(object):
def __init__(self, value):
self.value = value
self.parent = None
self.left = None
self.right = None
class BinarySearchTreeWithParent(object):
"""docstring for BinarySearchTreeWithParent"""
def __init__(self, value):
self.root = Node(value)
def insert(self, value):
node = Node(value)
if self.root is None:
self.root = node
return
return self.insert_node(self.root, node)
def insert_node(self, parent, node):
if node.value < parent.value:
if parent.left is None:
parent.left = node
node.parent = parent
else:
return self.insert_node(parent.left, node)
else:
if parent.right is None:
parent.right = node
node.parent = parent
else:
return self.insert_node(parent.right, node)
def search(self, value):
if self.root is None:
return
curr = self.root
while curr is not None:
if value == curr.value:
return curr
elif value < curr.value:
curr = curr.left
else:
curr = curr.right
return
def delete(self, value):
if self.root is None:
return
node = self.search(value)
parent = node.parent
if node is None:
return
if node.left is None and node.right is None:
# case 1: 0 child node
if node.parent is None:
self.root = None
return
if parent.left == node:
parent.left = None
else:
parent.right = None
node.parent = None
elif node.left is None or node.right is None:
# case 2: 1 child node
if node.left is not None:
if parent is None:
self.root = node.left
return
if parent.left == node:
parent.left = node.left
else:
parent.right = node.left
else: # node.right is not None
if parent is None:
self.root = node.right
return
if parent.left == node:
parent.left = node.right
else:
parent.right = node.right
node.parent = None
else:
# case 3: 2 child nodes
trav_parent = node
trav_curr = node.right
while trav_curr.left is not None:
trav_parent = trav_curr
trav_curr = trav_curr.left
temp = node.value
node.value = trav_curr.value
trav_curr.value = temp
if trav_parent == node:
trav_parent.right = trav_curr.right
trav_curr.parent = None
else:
trav_parent.left = trav_curr.right
trav_curr.parent = None
def preorder(self, node):
if node is None:
return
print node.value,
self.preorder(node.left)
self.preorder(node.right)
def inorder(self, node):
if node is None:
return
self.inorder(node.left)
print node.value,
self.inorder(node.right)
def postorder(self, node):
if node is None:
return
self.postorder(node.left)
self.postorder(node.right)
print node.value,
def levelorder(self, node):
if node is None:
return
queue = [node]
while len(queue) > 0:
curr = queue.pop(0)
print curr.value,
if curr.left is not None:
queue.append(curr.left)
if curr.right is not None:
queue.append(curr.right)
print ""
return
def get_root(self):
return self.root
if __name__ == "__main__":
bst = BinarySearchTreeWithParent(8)
bst.insert(3)
bst.insert(10)
bst.insert(1)
bst.insert(6)
bst.insert(4)
bst.insert(7)
bst.insert(14)
bst.insert(13)
root = bst.get_root()
bst.preorder(root)
print ""
bst.inorder(root)
print ""
bst.postorder(root)
print ""
bst.levelorder(root)
print "------------------"
# print bst.search(8).value
# print bst.search(3).value
# print bst.search(10).value
# print bst.search(1).value
# print bst.search(6).value
# print bst.search(4).value
# print bst.search(7).value
# print bst.search(14).value
# print bst.search(13).value
bst.delete(13)
bst.preorder(root)
print ""
bst.inorder(root)
print ""
bst.postorder(root)
print ""
|
"""
Selection sort
Sorts an array by repeatedly finding the minimum element from unsorted part and put it at the beginning
Time: O(n^2)
Space: O(1)
"""
def selection_sort(array):
if len(array) < 2:
return array
unsorted = 0
for i in xrange(len(array)):
min_index = i
min_value = array[i]
j = i+1
while j < len(array):
if array[j] < min_value:
min_index = j
min_value = array[j]
j += 1
array[unsorted], array[min_index] = array[min_index], array[unsorted]
unsorted += 1
return array
def selection_sort_recursive(array, start, end):
"""
Recursive implementation of selection sort
"""
if start >= end:
return
index = min_index(array, start, end)
temp = array[start]
array[start] = array[index]
array[index] = temp
selection_sort_recursive(array, start+1, end)
return array
def min_index(arr, start, end):
min_index = start
for i in xrange(start+1, end+1):
if arr[i] < arr[min_index]:
min_index = i
return min_index
if __name__ == "__main__":
arr1 = [4,3,2,10,12,1,5,6]
arr2 = [64, 25, 12, 22, 11]
print selection_sort(arr1)
print selection_sort(arr2)
print selection_sort_recursive(arr1, 0, len(arr1)-1)
print selection_sort_recursive(arr2, 0, len(arr2)-1)
|
"""
CtCi
2.8 Given a circular linked list, implement an algorithm that returns the node at the beginning
of the loop.
Circular linked list: A(corrupt) linked list in which a node's next pointer points to an earlier node,
so as to make a loop in the linked list.
Eg.
Input: A -> B -> C -> D -> E -> C(the same C as earlier)
Output: C
"""
"""
Singly linked list implementation.
"""
class Node(object):
"""docstring for Node"""
def __init__(self, value, next=None):
self.value = value
self.next = next
class LinkedList(object):
"""docstring for LinkedList"""
def __init__(self, value):
self.head = Node(value)
def insert_front(self, value):
"""
Insert node at front of the list
"""
node = Node(value)
node.next = self.head
self.head = node
return
def insert_back(self, value):
"""
Insert node at back of the list
"""
curr = self.head
while curr.next is not None:
curr = curr.next
node = Node(value)
curr.next = node
return
def delete(self, value):
"""
Delete the node which contains the value
"""
prev = None
curr = self.head
while curr is not None:
if curr.value == value:
if prev is None:
self.head = self.head.next
return
prev.next = curr.next
del curr
break
prev = curr
curr = curr.next
return
def get_head(self):
return self.head
def print_list(self):
curr = self.head
while curr is not None:
print curr.value,
curr = curr.next
print ""
return
def find(self, value):
curr = self.head
while curr is not None:
if curr.value == value:
return curr
curr = curr.next
return False
def loop_detection(head):
"""
Tortise and hare strategy.
1. tortise goes through 1 node at a time
2. hare goes through 2 ndoes at a time
3. if either tortise or hare hits a None, there's no loop,exit and return None
4. if there is a loop, tortise and hare will meet at some point
5. when tortise and hare meets, reset the hare to head node.
6. now both tortise and hare move 1 node at a time.
7. when tortise and hare meets again at a node, that node is the start of the loop.
8. return the loop
"""
if not head:
return None
tortise = head
hare = head
traversed = False
# tortise move 1 node while hare moves 2 nodes
while tortise is not None and hare is not None:
# tortise and hare met again but not at the starting node
if tortise == hare and traversed:
break
traversed = True
tortise = tortise.next
hare = hare.next
if hare is not None:
hare = hare.next
else:
# if none is found, means there's no loop. return None
return None
hare = head
while hare is not None:
if tortise == hare:
return hare
tortise = tortise.next
hare = hare.next
return None
def construct_circular_list(head):
curr = head
node = None
while curr.next is not None:
if curr.value == 'C':
node = curr
curr = curr.next
curr.next = node
return head
if __name__ == '__main__':
a_list = LinkedList('A')
a_list.insert_back('B')
a_list.insert_back('C')
a_list.insert_back('D')
a_list.insert_back('E')
head = a_list.get_head()
head = construct_circular_list(head)
print loop_detection(head).value
|
"""
Singly linked list implementation.
"""
class Node(object):
"""docstring for Node"""
def __init__(self, value, next=None):
self.value = value
self.next = next
class LinkedList(object):
"""docstring for LinkedList"""
def __init__(self, value):
self.head = Node(value)
def insert_front(self, value):
"""
Insert node at front of the list
"""
node = Node(value)
node.next = self.head
self.head = node
return
def insert_back(self, value):
"""
Insert node at back of the list
"""
curr = self.head
while curr.next is not None:
curr = curr.next
node = Node(value)
curr.next = node
return
def delete(self, value):
"""
Delete the node which contains the value
"""
prev = None
curr = self.head
while curr is not None:
if curr.value == value:
if prev is None:
self.head = self.head.next
return
prev.next = curr.next
del curr
break
prev = curr
curr = curr.next
return
def get_head(self):
return self.head
def print_list(self):
curr = self.head
while curr is not None:
print curr.value,
curr = curr.next
print ""
return
def find(self, value):
curr = self.head
while curr is not None:
if curr.value == value:
return curr
curr = curr.next
return False
def main():
linked_list = LinkedList(1)
linked_list.insert_back(2)
linked_list.insert_back(3)
linked_list.print_list()
print linked_list.find(2)
linked_list.delete(2)
linked_list.print_list()
if __name__ == '__main__':
main()
|
"""
CtCi
10.4 You are given an array-like data structure. Listy which lacks a size method.
It does, however have an elementAt(i) method that returns the element at index i
in O(1) time. If i is beyond the bound of the data structure, it returns -1.(For
this reason, the data structure only supports positive integers.) Given a Listy which contains
sorted, positive integers, find the index at which an element x occurs. If x occurs
multiple times, you may return any index.
"""
def search(arr, element):
"""
Time: O(lgn)
Space: O(1)
"""
if arr.elementAt(0) == -1:
return -1
idx = 1
while arr.elementAt(idx) != -1:
idx *= 2
return binary_search(arr, element, 0, idx)
def binary_search(arr, element, low, high):
if low > high:
return -1
mid = (low + high) / 2
if arr.elementAt(mid) == element:
return mid
elif arr.elementAt(mid) == -1 or element < arr.elementAt(mid):
return binary_search(arr, element, low, mid-1)
else:
return binary_search(arr, element, mid+1, high)
if __name__ == '__main__':
arr1 = [1, 3, 4, 5, 7, 10, 14, 15, 16, 19, 20, 25]
print search(arr1, 5) # 3
|
"""
CtCi
1.2 Given two strings, write a method to decide if one is a permutation of the other.
"""
def check_permutation(str1, str2):
"""
Time: O(mn)
Space: O(max(m, n))
where m is the size of str1, n size of str2.
"""
if not str1 or not str2:
return False
table = {}
for value in str1:
if value in table:
table[value] += 1
else:
table[value] = 1
for value in str2:
if value not in table:
return False
else:
table[value] -= 1
if table[value] == 0:
del table[value]
return len(table) == 0
def check_permutation_with_sort(str1, str2):
"""
Time: O(nlgn + mlgm)
Space: O(n+m)
where m is the size of str1, n size of str2
"""
if not str1 or not str2 or len(str1) != len(str2):
return False
list1 = list(str1)
list2 = list(str2)
list1.sort()
list2.sort()
for i in xrange(len(list1)):
if list1[i] != list2[i]:
return False
return True
if __name__ == '__main__':
str1 = "abc"
str2 = "cba"
str3 = "test"
str4 = "estt"
str5 = "testt"
str6 = "estt"
print check_permutation(str1, str2) # True
print check_permutation(str3, str4) # True
print check_permutation(str5, str6) # False
print check_permutation_with_sort(str1, str2)
print check_permutation_with_sort(str3, str4)
print check_permutation_with_sort(str5, str6)
|
"""
CtCi
8.5 Write a recursive function to multiply two positive integers without using the
* operator. You can use addition, subtraction, and bit shifting, but you should minimize
the number of those operations.
"""
def multiply_by_addition(a, b):
sign = "+"
if (a < 0 and b > 0) or (a > 0 and b < 0):
sign = "-"
result = 0
for i in xrange(abs(b)):
result += abs(a)
if sign == "-":
result = 0 - result
return result
def multiply_by_addition_recursive(a, b):
return multiply_by_addition_recursive_util(a, b, 0, 0)
def multiply_by_addition_recursive_util(a, b, i, result):
if i >= abs(b):
if (a < 0 and b > 0) or (a > 0 and b < 0):
return 0 - result
return result
result += a
return multiply_by_addition_recursive_util(a, b, i+1, result)
def min_product(a, b):
"""
Time: O(lgs)
Space: O(1)
where s is the value of smaller integer
"""
is_positive = True
if (a < 0 and b > 0) or (a > 0 and b < 0):
is_positive = False
bigger = b if a < b else a # a < b? b : a
smaller = a if a < b else b # a < b? a : b
result = min_product_util(abs(smaller), abs(bigger))
if is_positive:
return result
return 0 - result
def min_product_util(smaller, bigger):
if smaller == 0:
return 0
elif smaller == 1:
return bigger
s = smaller >> 1 # divide by 2
half_prod = min_product_util(s, bigger)
if smaller % 2 == 0:
return half_prod + half_prod
return half_prod + half_prod + bigger
if __name__ == '__main__':
print multiply_by_addition(3, 5), multiply_by_addition_recursive(3, 5)
print multiply_by_addition(6, 8), multiply_by_addition_recursive(6, 8)
print multiply_by_addition(-6, 8), multiply_by_addition_recursive(-6, 8)
print multiply_by_addition(6, -5), multiply_by_addition_recursive(6, -5)
print min_product(3, 5)
print min_product(6, 8)
print min_product(-6, 8)
print min_product(6, -5)
|
"""
CtCi
3.4 Implement a MyQueue class which implements a queue using two stacks
"""
class MyQueue(object):
def __init__(self):
self.stack1 = []
self.stack2 = []
def enqueue(self, item):
self.stack1.append(item)
return
def dequeue(self):
if len(self.stack1) < 1:
return None
while len(self.stack1) > 0:
value = self.stack1.pop()
self.stack2.append(value)
result = self.stack2.pop()
while len(self.stack2) > 0:
value = self.stack2.pop()
self.stack1.append(value)
return result
def peek(self):
if len(self.stack1) < 1:
return None
return self.stack1[-1]
def is_empty(self):
return len(self.stack1) == 0
if __name__ == '__main__':
queue = MyQueue()
queue.enqueue(1)
queue.enqueue(2)
queue.enqueue(3)
queue.enqueue(4)
print queue.dequeue()
print queue.dequeue()
print queue.dequeue()
print queue.dequeue()
print queue.dequeue()
|
"""
CtCi
10.2 Write a method to sort an array of strings so that all the anagrams are next to each other.
"""
def sort_strings(arr):
"""
hash table to order elements
key: value
string: [anagrams of the string]
Time: O(mnlgn)
Space: O(m)
where m is size of array, n is size of longest word in array
"""
if not arr:
return []
table = {}
for item in arr:
base = sort_chars(item)
anagram = "".join(base)
if anagram in table:
table[anagram].append(item)
else:
table[anagram] = [item]
result = []
for key in table.keys():
result.extend(table[key])
return result
def sort_chars(chars):
"""
mergesort
Time: O(nlgn)
Space: O(1)
"""
arr = mergesort(list(chars), 0, len(chars)-1)
return "".join(arr)
def mergesort(arr, low, high):
if low < high:
mid = (low + high) / 2
mergesort(arr, low, mid)
mergesort(arr, mid+1, high)
merge(arr, low, mid, high)
return arr
def merge(arr, low, mid, high):
temp = arr[:]
left_i = low
right_i = mid + 1
idx = low
while left_i <= mid and right_i <= high:
if temp[left_i] < temp[right_i]:
arr[idx] = temp[left_i]
left_i += 1
else:
arr[idx] = temp[right_i]
right_i += 1
idx += 1
while left_i <= mid:
arr[idx] = temp[left_i]
left_i += 1
idx += 1
while right_i <= high:
arr[idx] = temp[right_i]
right_i += 1
idx += 1
return
def sort_strings2(arr):
"""
Time: O(mn)
Space: O(m)
where m is the size of array, n the size of longest string in array
"""
if not arr:
return []
table = {}
for item in arr:
anagram_key = get_anagram_key(item)
if anagram_key in table:
table[anagram_key].append(item)
else:
table[anagram_key] = [item]
result = []
for key in table.keys():
result.extend(table[key])
return result
def get_anagram_key(chars):
"""
Time: O(n)
Space: O(1)
"""
if not chars:
return ""
freq_table = [0 for _ in range(26)]
for char in chars:
idx = ord(char) - 97
freq_table[idx] += 1
result = ""
for i in range(len(freq_table)):
if freq_table[i] != 0:
result += chr(i+97) + str(freq_table[i])
return result
if __name__ == '__main__':
arr1 = ["cat", "dog", "tac", "god", "act"]
print sort_strings(arr1)
print sort_strings2(arr1)
|
"""
This file contains a list of method references for a dictionary
"""
# initialize a dictionary
stuff = {
'name': 'Zed',
'age': 35,
'height': 4 * 12
}
# set key to value
stuff['hair_color'] = 'black'
# check if key is in dict
print 'hair_color' in stuff # true
# delete key and its value from dict. Raises KeyError if key is not in map
del stuff['hair_color']
print 'hair_color' in stuff # false
# return an iterator over the keys of the dictionary, this is a shortcut for iterkeys()
iterator = iter(stuff)
# return a copy of the dictionary's list of (key, value) pairs
print "items are: ",
print stuff.items()
# clear all items from the dictionary
# stuff.clear()
# update the dictionary with key value pairs or another dictionary, return None
a = {'a': 1}
b = {'b': 2}
a.update(b) # a = {'a': 1, 'b': 2}
a.update(c=3, d=4)
# if key is in dictionary. remvoe and return its value, else return default
stuff.pop('height')
# you can also build a dictionary directly from sequence of key value pairs
new_stuff = dict([('sape', 4139), ('guido', 4217), ('jack', 4098)])
# you can also create dictionaries with dict comprehension
new_stuff_2 = {x: x**2 for x in [2, 4, 6]} # {2: 4, 4: 16, 6: 36}
# access an item in dictionary by key
print stuff['name']
# delete a key value pair from dictionary
del stuff['height']
print stuff
# get a list of keys in the dictionary
print stuff.keys()
# check if a key is in dictionary
print 'name' in stuff
print 'height' in stuff
# loop over a dictionary
knights = {'gallahad': 'the pure', 'robin': 'the brave'}
for k, v in knights.iteritems():
print k, v
# check number of items in dictionary
len(knights)
|
"""
CtCi
3.5 Write a program to sort a stack such that the smallest items are on top.
You can use an additional temporary stack, but you may not copy the elements into
any other data structure(such as an array), The stack supports the following
operations: push, pop, peek and isEmpty.
"""
def sort_stack(stack):
"""
Time: O(n^2)
Space: O(n)
where n is the size of the stack
"""
if len(stack) <= 1:
return stack
aux = []
while len(stack) > 0:
value = stack.pop()
if len(aux) < 1:
aux.append(value)
continue
while len(aux) > 0 and value < aux[-1]:
stack.append(aux.pop())
aux.append(value)
while len(aux) > 0:
stack.append(aux.pop())
return stack
if __name__ == '__main__':
stack1 = [25, 12, 22, 11, 64]
stack2 = [4,3,2,10,12,1,5,6]
print sort_stack(stack1)
print sort_stack(stack2)
|
"""
CtCi
10.6 Imagine you have a 20GB file with one string per line. Explain how you
would sort the file.
"""
# 1. break up to 20GB into 20,000 files of 1MB file size each.
# 2. use mergesort to sort each 1MB file.
# 3. after all files are independently sorted, we use the merge procedure(from mergesort) to merge
# each pairs of files together. after step 3, we would have 10,000 files independently merged
# 4. we repeatedly use merge procedure to merge each pairs of files until we have 1 file left of 20GB
# size.
# 5. now the file is sorted
# This algorithm is known as external sort
# Time: O(nlgn)
# Space: O(20GB)
|
"""
CtCi
4.8 Design an algorithm and write code to find the first common ancestor of two
nodes in a binary tree. Avoid storing additional nodes in a data structure. Note:
This is not necessarily a binary search tree.
"""
from BinarySearchTreeWithParent import BinarySearchTreeWithParent
def first_common_ancestor(node1, node2):
"""
Assume there is a parent pointer for each node.
Time: O(lgn)
Space: O(1)
where n is the size of the binary tree
"""
if not node1 or not node2:
return None
count1 = get_length_to_root(node1)
count2 = get_length_to_root(node2)
curr1, curr2 = node1, node2
while count1 > count2:
count1 -= 1
curr1 = curr1.parent
while count2 > count1:
count2 -= 1
curr2 = curr2.parent
# now curr1 and curr2 are same length towards root node
while curr1 is not None:
if curr1 == curr2:
return curr1
curr1 = curr1.parent
curr2 = curr2.parent
return None
def get_length_to_root(node):
count = 0
while node is not None:
count += 1
node = node.parent
return count
def first_common_ancestor_2(root, node1, node2):
"""
Assume there is no parent pointer for each node.
We traverse down starting from the root node.
If n1 and n2 are on same side, we traverse down that side
on the first occurence of n1 on 1 side and n2 on the other. we return that node.
Time: O(lgn)
Space: O(lgn)
where n is the size of the binary tree at root.
"""
if not root or not node1 or not node2:
return None
elif not covers(root, node1) or not covers(root, node2):
return None
curr = root
while curr is not None:
n1_left = covers(curr.left, node1)
n2_left = covers(curr.left, node2)
if n1_left != n2_left:
return curr
if n1_left:
curr = curr.left
else:
curr = curr.right
def covers(root, node):
if not root or not node:
return False
if root is node:
return True
return covers(root.left, node) or covers(root.right, node)
if __name__ == '__main__':
bst = BinarySearchTreeWithParent(4)
bst.insert(2)
bst.insert(6)
bst.insert(1)
bst.insert(3)
bst.insert(5)
bst.insert(7)
root = bst.get_root()
node1 = bst.search(1)
node2 = bst.search(2)
node3 = bst.search(3)
node5 = bst.search(5)
node6 = bst.search(6)
print first_common_ancestor(node1, node3).value
print first_common_ancestor(node1, node5).value
print first_common_ancestor(node1, node6).value
print first_common_ancestor(node1, node2).value
print first_common_ancestor_2(root, node1, node3).value
print first_common_ancestor_2(root, node1, node5).value
print first_common_ancestor_2(root, node1, node6).value
print first_common_ancestor_2(root, node1, node2).value
|
"""
CtCi
T1 and T2 are two very large binary trees, with T1 much bigger than T2. Create
an algorithm to determine if T2 is a subtree of T1.
A tree T2 is a subtree of T1 if there exists a node n in T1 such that the subtree
of n is identical of T2. THat is, if you cut off the tree at node n, the two trees
would be identical.
"""
from BinarySearchTree import BinarySearchTree
def check_subtree(root1, root2):
"""
Return True if tree at root2 is a subtree of tree at root1. False otherwise
Time: O(mn)
Space: O(lgn + lgm)
where m is the size of tree with root1, n is size of tree with root2
"""
candidates = []
get_nodes_with_value(root1, root2.value, candidates)
if not candidates:
return False
for node in candidates:
if is_same_tree(node, root2):
return True
return False
def get_nodes_with_value(node, value, candidates):
if node is None:
return
if node.value == value:
candidates.append(node)
get_nodes_with_value(node.left, value, candidates)
get_nodes_with_value(node.right, value, candidates)
return
def is_same_tree(root1, root2):
"""
Return True if both trees are the same, else return false
Time: O(n)
Space: O(n)
where n is the size of tree with root2
"""
if root1 is None and root2 is None:
return True
elif root1 is None or root2 is None:
return False
if root1.value != root2.value:
return False
return is_same_tree(root1.left, root2.left) and is_same_tree(root1.right, root2.right)
def check_subtree_2(root1, root2):
"""
Time: O(n+m)
Space: O(n+m)
"""
order1, order2 = [], []
preorder(root1, order1)
preorder(root2, order2)
str1 = "".join(str(e) for e in order1)
str2 = "".join(str(e) for e in order2)
return str2 in str1
def preorder(node, order):
if node is None:
order.append("X")
return
order.append(node.value)
preorder(node.left, order)
preorder(node.right, order)
if __name__ == '__main__':
bst1 = BinarySearchTree(50)
bst1.insert(20)
bst1.insert(60)
bst1.insert(10)
bst1.insert(25)
bst1.insert(70)
bst1.insert(5)
bst1.insert(15)
bst1.insert(65)
bst1.insert(80)
root1 = bst1.get_root()
bst2 = BinarySearchTree(60)
bst2.insert(70)
bst2.insert(65)
bst2.insert(80)
root2 = bst2.get_root()
print check_subtree(root1, root2)
print check_subtree_2(root1, root2)
|
"""
Given two strings s and t, determine whether some anagram of t is a substring of s. For example: if
s = “udacity” and t = “ad”, then the function returns True. Your function definition should look
like: “question1(s, t)”, and return a boolean True or False.
"""
def question1(s, t):
#creates a dict of {character:character_frequency} pairs for all characters in a given string
def create_dict(string):
string_dict = {}
for character in string:
if character in string_dict:
string_dict[character] += 1
else:
string_dict[character] = 1
return string_dict
#case where one does not exist
if s == None or t == None:
return False
#case where strings are the same
if s == t:
return True
#impossible for t to have an anagram substring of s if t is longer than s
if len(s) < len(t):
return False
s = s.lower()
t = t.lower()
#create dicionaries from the strings
t_dict = create_dict(t)
s_dict = create_dict(s)
#no anagram of t is a substring of s if s has less occurences of a character than t
for character in t_dict:
if character not in s_dict:
return False
if s_dict[character] < t_dict[character]:
return False
#an anagram substring exists if s has >= the number of occurences of each of t's characters as t
return True
print question1(None, 'a') #False
print question1('a', None) #False
print question1(None, None) #False
print question1('', '') #True
print question1('', 'a') #False
print question1('a', '') #True
print question1('abcd', 'abcde') #False
print question1("Udacty", "AD") #True
print question1("I am Sam", "Sam") #True
print question1("abc@#$", "@#$") #True
print question1("abc", "def") #False
|
""" Working with mixed datatypes (2)
You have just used np.genfromtxt() to import data containing mixed datatypes. There is also another function np.recfromcsv() that behaves similarly to np.genfromtxt(), except that its default dtype is None. In this exercise, you'll practice using this to achieve the same result. """
# Assign the filename: file
file = 'titanic.csv'
# Import file using np.recfromcsv: d
d = np.recfromcsv(file, delimiter=',', names=True, dtype=None)
# Print out first three entries of d
print(d[:3])
|
""" The structure of .mat in Python
Here, you'll discover what is in the MATLAB dictionary that you loaded in the previous exercise.
The file 'albeck_gene_expression.mat' is already loaded into the variable mat. The following libraries have already been imported as follows:
import scipy.io
import matplotlib.pyplot as plt
import numpy as np
Once again, This file contains (gene expression data)[https://www.mcb.ucdavis.edu/faculty-labs/albeck/workshop.htm] from the Albeck Lab at UC Davis. You can find the data and some great documentation (here)[https://www.mcb.ucdavis.edu/faculty-labs/albeck/workshop.htm]. """
# continued from 9_
# Print the keys of the MATLAB dictionary
print(mat.keys())
# Print the type of the value corresponding to the key 'CYratioCyt'
print(type(mat['CYratioCyt']))
# Print the shape of the value corresponding to the key 'CYratioCyt'
print(np.shape(mat['CYratioCyt']))
# Subset the array and plot it
data = mat['CYratioCyt'][25, 5:]
fig = plt.figure()
plt.plot(data)
plt.xlabel('time (min.)')
plt.ylabel('normalized fluorescence (measure of expression)')
plt.show()
|
# -*- coding: utf-8 -*-
# https://docs.python.org/3.5/library/datetime.html ler depois
class MvpView:
def __init__(self, name):
self.mvp = name
self.queued = []
self.time = []
def add_entry(self, mvp_list):#linkar mvp_list com o controller
"""
Ask user for input and store its values
"""
mvp_name = self.mvp
while mvp_name.lower() not in mvp_list:#mvp_list:
print("Mvp not found, please, write the name again.\n")
mvp_name = input("Name: ")
self.deathtime = input("Death time (hh:mm:ss): ")
self.time = [int(self.deathtime[:-6]),
int(self.deathtime[-5:-3]),
int(self.deathtime[-2:])]
def next_on_list(self,mvp_time = []):
"""
Print list of mvps in ascending respawn time order
"""
self.queued = mvp_time
return self.queued
|
#Recursive
class Solution:
def isSymmetric(self, root: TreeNode) -> bool:
def isMirror(t1,t2):
if t1==None and t2 ==None: return True
if t1==None or t2 == None: return False
return t1.val==t2.val and isMirror(t1.right,t2.left) and isMirror(t1.left,t2.right)
return isMirror(root,root)
# Iteration
|
# 125. Valid Palindrome
# My solution: Two pointers
class Solution:
def isPalindrome(self, s: str) -> bool:
i = 0
j = len(s)-1
while(i<j):
if s[i].isalnum()==False:
i +=1
continue
if s[j].isalnum()==False:
j -=1
continue
if s[i].lower()!=s[j].lower():
return False
i+=1
j-=1
return True
|
import time
n = 6
result_matrix = [[0 for x in range(n)] for y in range(n)]
def print_matrix( r):
for i in range(n):
for j in range(n):
print(r[i][j], end = '\t')
print()
counter = 1
k = n
# row left to right
print("the middle is" + str((n//2+1)))
for i in range(n//2+1):
time.sleep(2)
print("********************************************")
print("i: " + str(i) + " k: " + str(k))
for di in range(i,k):
print("[" + str(i) + "]" + "[" + str(di) + "]", end=' ')
result_matrix[i][di] = counter
counter+=1
print()
#print_matrix(result_matrix)
for di in range(i+1,k):
print("[" + str(di) + "]" + "[" + str(k-1) + "]", end=' ')
result_matrix[di][k-1] = counter
counter+=1
print()
#print_matrix(result_matrix)
for di in range(-(i+2), -(k+1),-1):
print("[" + str(k-1) + "]" + "[" + str(di) + "]", end=' ')
result_matrix[k-1][di] = counter
counter+=1
print()
#print_matrix(result_matrix)
for di in range(-(i+2),-k,-1):
print("[" + str(di) + "]" + "[" + str(i) + "]", end=' ')
result_matrix[di][i] = counter
counter+=1
print()
#print()
#print_matrix(result_matrix)
k = k-1
print("\n\n\n--------------------")
#print_matrix(result_matrix)
print(result_matrix[5][-2])
|
class Item(object):
def __init__(self, n, v, w):
self.name = n
self.value = v
self.weight = w
def getName(self):
return self.name
def getValue(self):
return self.value
def getWeight(self):
return self.weight
def __str__(self):
return self.name + ": <" + str(self.value) + ", " + str(self.weight) + ">"
def buildItems():
names = ["clock", "painting", "radio", "vase", "book", "computer"]
values = [175, 90, 20, 50, 10, 200]
weights = [10, 9, 4, 2, 1, 20]
items = []
for i in range(len(names)):
item = Item(names[i], values[i], weights[i])
items.append(item)
return items
def chooseBest(itemsPowerset, maxWeight, getVal, getWeight):
bestSet = None
bestVal = 0.0
for items in itemsPowerset:
itemsVal = 0.0
itemsWeight = 0.0
for item in items:
itemsVal += getVal(item)
itemsWeight += getWeight(item)
if (itemsWeight <= maxWeight) and (itemsVal > bestVal):
bestVal = itemsVal
bestSet = items
return (bestSet, bestVal)
def getPowerset(L):
res = []
if len(L) == 0:
return [[]] # list of empty list
smaller = getPowerset(L[:-1]) # all subsets without last element
extra = L[-1:] # create a list of just last element
new = []
for small in smaller: # for all smaller solutions, add one with last element
new.append(small+extra)
return smaller+new # combine those with last element and those without
def testBest(maxWeight=20):
items = buildItems()
itemsPowerset = getPowerset(items)
takenItems, itemsVal = chooseBest(itemsPowerset, maxWeight,
Item.getValue, Item.getWeight)
print("Total value of items taken is:", itemsVal)
for item in takenItems:
print(item)
testBest()
|
# 3 types of data in python
10
# numbers
"Mosh"
# strings
True
# booleans
birth_year = input("Enter your birth year: ")
# input returns a string. You can't subtract a String from an int, so you get a type error
# below you will see Pythons equivalent to casting in Java (int and str)
age = 2020 - int(birth_year)
print("You are " + str(age) + " years old.")
# built-in functions for converting values:
int()
float()
bool()
str()
# Python doesn't know how to concatenate different type values. So these are important.
|
class Quantity:
def __init__(self,storage_name):
self.storage_name = storage_name
def __set__(self, instance, value):
if type(value) is not str:
if value >0:
instance.__dict__[self.storage_name] = value
else:
raise ValueError('value must be > 0')
else:
if len(value) > 5:
instance.__dict__[self.storage_name] = value
else:
raise ValueError('the length must be > 5')
class LineItem:
weight = Quantity('weight')
price = Quantity('price')
description = Quantity('description')
def __init__(self,description,weight,price):
self.description = description
self.weight = weight
self.price = price
def subtotal(self):
return self.weight * self.price
if __name__=='__main__':
obj = LineItem("test instance",10,-30.6)
#obj 是一个LineItem的实例
print(obj.subtotal())
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.