text
stringlengths 37
1.41M
|
---|
# Sensor Sleep Mode Example.
# This example demonstrates the sensor sleep mode. The sleep mode saves around
# 40mA when enabled and it's automatically cleared when calling sensor reset().
import sensor, image, time, pyb
from pyb import LED
led = LED(1) # red led for running check
def test():
sensor.sleep(False)
led.on()
sensor.reset() # Reset and initialize the sensor.
sensor.set_pixformat(sensor.RGB565) # Set pixel format to RGB565 (or GRAYSCALE)
sensor.set_framesize(sensor.QVGA) # Set frame size to QVGA (320x240)
sensor.skip_frames(time = 3000) # Capture frames for 3000ms.
sensor.sleep(True) # Enable sensor sleep mode (saves about 40mA)
led.off()
######## Configure external wakeup pin for sleep ######
extint = pyb.ExtInt("P7", pyb.ExtInt.IRQ_RISING, pyb.Pin.PULL_DOWN, test)
#######################################################
test()
while True:
time.sleep(100)
pass
|
class RegressionModels:
'Simplifying Model Creation to Use Very Efficiently.'
def linear_regression (train, target):
'''Simple Linear Regression
Params :-
train - Training Set to train
target - Target Set to predict'''
from sklearn.linear_model import LinearRegression
model = LinearRegression()
model.fit(train, target)
return model
def knn_regressor (train, target, n_neighbors):
'''KNearestNeighbors Regressor
Params :-
train - Training Set to train
target - Target Set to predict
n_neighbors - no. of nearest neighbors to take into consideration for prediction'''
from sklearn.neighbors import KNeighborsRegressor
model = KNeighborsRegressor(n_neighbors = n_neighbors)
model.fit(train, target)
return model
def d_tree (train, target, max_depth = 8, max_features = None, max_leaf_nodes = 31, random_state = 17):
'''DecisionTree Regressor
Params :-
train - Training Set to train
target - Target Set to predict
max_depth - maximum depth that tree can grow (default set to 8)
max_features - maximum number of features that a tree can use (default set to None)
max_leaf_nodes - maximum number of leaf nodes that a tree can contain (default set to 31)
random_state - A arbitary number to get same results when run on different machine with same params (default set to 17)'''
from sklearn.tree import DecisionTreeRegressor
model = DecisionTreeRegressor(max_depth = max_depth, max_leaf_nodes = max_leaf_nodes, max_features = max_features, random_state = random_state)
model.fit(train, target)
return model
def random_forest (train, target, n_estimators = 100, max_depth = 8, max_features = None, max_leaf_nodes = 31, random_state = 17):
'''RandomForest Regressor
Params :-
train - Training Set to train
target - Target Set to predict
n_estimators - no. of trees to predict (default set to 100)
max_depth - maximum depth that tree can grow (default set to 8)
max_features - maximum number of features that a tree can use (default set to None)
max_leaf_nodes - maximum number of leaf nodes that a tree can contain (default set to 31)
random_state - A arbitary number to get same results when run on different machine with same params (default set to 17)'''
from sklearn.ensemble import RandomForestRegressor
model = RandomForestRegressor(n_estimators = n_estimators, max_depth = max_depth, max_leaf_nodes = max_leaf_nodes,
max_features = max_features, random_state = random_state, n_jobs = -1)
model.fit(train, target)
return model
def xgboost (train, target, n_estimators = 100, max_depth = 8, random_state = 17, learning_rate = 0.1, colsample_bytree = 0.9, colsample_bynode = 0.9,
colsample_bylevel = 0.9, importance_type = 'gain', reg_alpha = 2, reg_lambda = 2):
'''XGBoost Regressor
Params :-
train - Training Set to train
target - Target Set to predict
n_estimators - no. of trees to predict (default set to 100)
max_depth - Maximum depth that a tree can grow (default set to 8)
random_state - A arbitary number to get same results when run on different machine with same params (default set to 17)
learning_rate - size of step to to attain towards local minima
colsample_bytree, colsample_bynode, colsample_bylevel - part of total features to use bytree, bynode, bylevel
importance_type - metric to split samples (default set to split)
reg_alpha, reg_lambda - L1 regularisation and L2 regularisation respectively'''
from xgboost import XGBRegressor
model = XGBRegressor(n_estimators = n_estimators, max_depth = max_depth, random_state = random_state, learning_rate = learning_rate,
colsample_bytree = colsample_bytree, colsample_bynode = colsample_bynode, colsample_bylevel = colsample_bylevel,
importance_type = importance_type, reg_alpha = reg_alpha, reg_lambda = reg_lambda)
model.fit(train, target)
return model
def xgrfboost (train, target, n_estimators = 100, max_depth = 8, random_state = 17, learning_rate = 0.1, colsample_bytree = 0.9, colsample_bynode = 0.9,
colsample_bylevel = 0.9, importance_type = 'gain', reg_alpha = 2, reg_lambda = 2):
'''XGRFBoost Regressor
Params :-
train - Training Set to train
target - Target Set to predict
n_estimators - no. of trees to predict (default set to 100)
max_depth - Maximum depth that a tree can grow (default set to 8)
random_state - A arbitary number to get same results when run on different machine with same params (default set to 17)
learning_rate - size of step to to attain towards local minima
colsample_bytree, colsample_bynode, colsample_bylevel - part of total features to use bytree, bynode, bylevel
importance_type - metric to split samples (default set to split)
reg_alpha, reg_lambda - L1 regularisation and L2 regularisation respectively'''
from xgboost import XGBRFRegressor
model = XGBRFRegressor(n_estimators = n_estimators, max_depth = max_depth, random_state = random_state, learning_rate = learning_rate,
colsample_bytree = colsample_bytree, colsample_bynode = colsample_bynode, colsample_bylevel = colsample_bylevel,
importance_type = importance_type, reg_alpha = reg_alpha, reg_lambda = reg_lambda)
model.fit(train, target)
return model
def catboost (train, target, n_estimators = 100, max_depth = 8, random_state = 17, learning_rate = 0.1, colsample_bylevel = 0.9, reg_lambda = 2):
'''CatBoost Regressor
Params :-
train - Training Set to train
target - Target Set to predict
n_estimators - no. of trees to predict (default set to 100)
max_depth - Maximum depth that a tree can grow (default set to 8)
random_state - A arbitary number to get same results when run on different machine with same params (default set to 17)
learning_rate - size of step to to attain towards local minima
colsample_bylevel - part of total features to use bylevel
importance_type - metric to split samples (default set to split)
reg_lambda - L2 regularisation'''
from catboost import CatBoostRegressor
model = CatBoostRegressor(n_estimators = n_estimators, max_depth = max_depth, learning_rate = learning_rate,
colsample_bylevel = colsample_bylevel, reg_lambda = reg_lambda, random_state = random_state, verbose = 0)
model.fit(train, target)
return model
def lightgbm (train, target, num_leaves = 32, max_depth = 8, learning_rate = 0.1, n_estimators = 100, colsample_bytree = 1.0,
reg_alpha = 2, reg_lambda = 2, random_state = 17, importance_type = 'split'):
'''LightGBM Regressor
Params :-
train - Training Set to train
target - Target Set to predict
num_leaves - maximum number of leaves that a tree can have
max_depth - Maximum depth that a tree can grow (default set to 8)
learning_rate - size of step to to attain towards local minima
n_estimators - no. of trees to predict (default set to 100)
colsample_bytree - part of total features to use bytree
reg_alpha, reg_lambda - L1 regularisation and L2 regularisation respectively
random_state - A arbitary number to get same results when run on different machine with same params (default set to 17)
importance_type - metric to split samples (default set to split)'''
from lightgbm import LGBMRegressor
model = LGBMRegressor(num_leaves = num_leaves, max_depth = max_depth, learning_rate = learning_rate, n_estimators = n_estimators,
colsample_bytree = colsample_bytree, reg_alpha = reg_alpha, reg_lambda = reg_lambda,
random_state = random_state, importance_type = importance_type)
model.fit(train, target)
return model |
print("What is your name?")
name = input()
print("What is your address?")
address = input()
print("What is your phone number?")
number = input()
print("What is your major?")
major = input()
print("Your name: ", name)
print("Your address: ", address)
print("Your number: ", number)
print("Your major: ", major) |
#!/usr/bin/python2
#use at your own risk
#I do not guarantee the correctness of this program
#I mainly made this to try and generate an already known solution
#we will need to do square roots later
#we are using cmath because the normal
#math module gives an error when we it sqrt(-1)
from cmath import sqrt
#We're going to explain the problem to the user:
print(" # ")
print(" ### ")
print(" # # # ")
print(" # # # ")
print(" # # # ")
print("1 -> # # # <- 2 ")
print(" # # # ")
print(" # # <- 3 # ")
print(" # # # ")
print(" # # # ")
print("##################### ")
print(" ^ ^ ")
print(" | | ")
print(" c/2 c/2 ")
print("In this program we will return the length of side c")
#now gather user input
print("Enter the length of side one: ")
side1 = float(input())
print("Enter the length of side two: ")
side2 = float(input())
print("Enter the length of the median(side three): ")
median = float(input())
#To solve this problem we need:
#
#the law of cosines:
# c^2 = a^2 + b^2 -2ab cos(theta)
#
#and a system of equations built from the law of cosines:
#for the triangle consisting of side 3, side 2, and side c/2 which we will call E1 (short for equation one)
#E1: side3^2 = side2^2 + (c/2)^2 - 2(side2)(c/2)cos(theta)
#for the triangle consisting of side 1, side 3, and side c which we will call E2
#E2: side1^2 = side2^2 + c^2 - 2(side1)(c)cos(theta)
#########
# FOR E2 (we are using the a b and c variable names from the law of cosines here..)
#########
#c^2
c_2 = side1**2
#a^2
a_2 = side2**2
#the coefficient of b * cos(theta)
coeff = -2.0 * side2
#########
# FOR E1 (same as prev but with _1 to mean equation one)
#########
#c^2
c_1 = median**2
#a^2
a_1 = side2**2
#the coefficient of b * cos(theta)
coeff = -2.0 * side2
#The following will be done to solve our system of equations by elimination
#
# E2: c^2 = a^2 + b^2 -2ab cos(theta)
# -2 * E1: c^2 = a^2 + b^2 -2ab cos(theta)
# -----------------------------------
# c_3 = a_3 + -2 * a_3
#as shown multiplying E1 by -2 allows us to cancel out cos(theta) and various coefficients of it
############
# -2 * E1
############
#-2 * c^2
c_1 = c_1 * -2
#-2 * a^2
a_1 = a_1 * -2
#coeff of b * cos(theta)
coeff = coeff * -2
######
# Elimination:
######
# E3 = E1 + E2
c_3 = c_1 + c_2
a_3 = a_1 + a_2
c_3 = c_3 + (-1 * a_3)
c_3 = c_3 * 2
c_3 = sqrt(c_3)
print("")
print("Side C is: " + str(c_3) + " units")
print("Note: j = sqrt(-1)")
|
"""
Реализуйте функцию almost_double_factorial(n), вычисляющую произведение всех нечётных натуральных чисел, не превосходящих nnn.
В качестве аргумента ей передаётся натуральное (ноль -- натуральное) число n⩽100n \leqslant 100n⩽100.
Возвращаемое значение - вычисленное произведение.
Комментарий. В случае, если n = 0, требуется вывести 1.
"""
def almost_double_factorial(n):
prod = 1
for i in range(1,n+1):
if i %2 !=0:
#print("i:",i)
prod *=i
#print("prod:",prod)
return prod
|
"""
Напишите функцию, которая находит сумму четных элементов на главной диагонали квадратной матрицы (именно чётных элементов, а не элементов на чётных позициях!). Если чётных элементов нет, то вывести 0. Используйте библиотеку numpy.
"""
import numpy as np
def diag_2k(a):
#param a: np.array[size, size]
#YOUR CODE
diagonal = a.diagonal()
result = sum(filter(lambda x: x%2 == 0, diagonal))
return result
|
x=int(input())
fact=1
if x<=20:
while x>0:
fact=fact*x
x=x-1
print(fact)
else:
print("enter the valid input")
|
class Solution:
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
diff = {}
for i in range(len(nums)):
if (target - nums[i]) in diff:
return [diff[target-nums[i]], i]
elif nums[i] not in diff:
diff[nums[i]] = i
|
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def longestUnivaluePath(self, root):
"""
:type root: TreeNode
:rtype: int
"""
self.longest = 0
def lp(node, pre):
if node:
left = lp(node.left, node.val)
right = lp(node.right, node.val)
self.longest = max(self.longest, left+right)
if node.val == pre:
return 1 + max(left, right)
else:
return 0
else:
return 0
lp(root, None)
return self.longest
|
class Solution:
def merge(self, nums1, m, nums2, n):
"""
:type nums1: List[int]
:type m: int
:type nums2: List[int]
:type n: int
:rtype: void Do not return anything, modify nums1 in-place instead.
"""
last1 = m - 1
last2 = n - 1
last = m + n - 1
while last2 >= 0:
if last1 == -1:
nums1[last] = nums2[last2]
last2 -= 1
else:
if nums1[last1] >= nums2[last2]:
nums1[last] = nums1[last1]
last1 -= 1
else:
nums1[last] = nums2[last2]
last2 -= 1
last -= 1
|
class Solution:
def mergeTrees(self, t1, t2):
"""
:type t1: TreeNode
:type t2: TreeNode
:rtype: TreeNode
"""
root = t1 or t2
if root:
merge = t1 if t1 != root else t2
if merge:
root.val = root.val + merge.val
root.left = self.mergeTrees(root.left, merge.left)
root.right = self.mergeTrees(root.right, merge.right)
return root
|
print "I will now count my chickens:"
print "Hens", 25+30/6
print "Roosters",100-25*3%4
print "Now I will count my eggs:"
print 3+2+1-5+4%2-1/4+6
print "Is it true that 3+2<5-7?"
print 3+2<5-7
print "What is 3+2?",3+2
|
"""
@author: karthikrao
Moves defined for Simulated Annealing.
"""
import random
from tests import *
"""
Swap two adjacent operands.
"""
def move1(exp):
"""
Parameters
----------
exp : list
Input Polish Expression.
Returns
-------
exp : list
Output Polish Expression.
"""
while True:
i = random.randint(0, len(exp)//2)
if exp[i]!='H' and exp[i]!='V':
break
ele1=i
while True:
i+=1
if exp[i]!='H' and exp[i]!='V':
break
ele2=i
exp[ele1], exp[ele2] = exp[ele2], exp[ele1]
return exp
"""
Complement a series of operators in a sublist.
"""
def move2(exp):
"""
Parameters
----------
exp : list
Input Polish Expression.
Returns
-------
exp : list
Output Polish Expression.
"""
start = random.randint(0, len(exp)-1)
end = random.randint(start, len(exp)-1)
for i in range(start, end):
if exp[i] == 'H':
exp[i] = 'V'
elif exp[i] == 'V':
exp[i] = 'H'
return exp
"""
Swap an adjacent operand-operator pair.
"""
def move3(exp):
"""
Parameters
----------
exp : list
Input Polish Expression.
Returns
-------
exp : list
Output Polish Expression.
"""
exp1 = exp.copy()
while True:
i = random.randint(0, len(exp)-2)
if (exp[i]=='H' or exp[i]=='V') and (exp[i+1]!='H' and exp[i+1]!='V'):
break
exp1[i], exp1[i+1] = exp1[i+1], exp1[i]
if test_ballot(exp1, i+1) and test_normalized(exp1):
return exp1
return exp |
from turtle import *
import random
Screen()
speed(0)
shape('circle')
shapesize(2)
pensize(3)
color('black')
down()
def m():
up()
def draw():
down()
def drag():
ondrag(goto)
colors=['red','orange','green','black','brown','cyan']
def sw():
color(random.choice(colors))
def cl():
clear()
def s1():
pensize(4)
def s2():
pensize(5)
def eraser():
shape('square')
color('white','black')
pensize(18)
bg=['red','yellow','green','crimson','white']
def ch_bg():
bgcolor(random.choice(bg))
def back():
shape('circle')
shapesize(2)
pensize(3)
color('black')
listen()
onkeypress(m,'u')
drag()
onkeypress(sw,'c')
onkey(ch_bg,'space')
onkeypress(back,'P')
onkeypress(eraser,'E')
onkeypress(cl,'Escape')
onkey(s1,'1')
onkey(s2,'2')
onkeypress(draw,'d')
mainloop()
|
# user input
#input function
name = input("Hello I will make a sentence on your name and age just do What i say\nType your name: ")
age = input("Type Your Age: ")
print("Hello "+ name + ". \n"+ "Your Age is "+ age + " yrs.")
|
print("Welcome To Kavya's Calculator.You Can Only Add Two Numbers Using This calculator")
num1 = input("type the number: ")
num2 = input("type another number: ")
num3 = int(num1)
num4 = int(num2)
print("total value of "+num1 + " + " + num2 + " is " + str(num3 +num4))
#str function is used to convert number to string
#int function is used to convert string to integer value
#float function is usedto convert string to float value |
"""
Author: Diallo West
Date Created: April 24, 2016
Title: Work log with a Database
Description:
Create a command line application that will allow employees to enter their name, time worked, task worked on, and general notes about the task into a database. There should be a way to add a new entry, list all entries for a particular employee, and list all entries that match a date or search term. Print a report of this information to the screen, including the date, title of task, time spent, employee, and general notes."""
from collections import OrderedDict
from datetime import datetime
import os
from peewee import *
db = SqliteDatabase('worklog.db')
entries = []
class Entry(Model):
pk = PrimaryKeyField()
employee_name = CharField(max_length=75)
task_name = CharField(max_length=75)
time = IntegerField()
date = DateField(default=datetime.now)
notes = TextField(null=True)
class Meta:
database = db
def initialize():
db.connect()
db.create_tables([Entry], safe=True)
def prompt_menu():
"""Shows the main menu"""
choice = None
while choice != 'q':
clear()
print("Enter 'q' to quit.")
for key, value in menu.items():
print('{}) {}'.format(key, value.__doc__))
choice = input("Action: \n").lower().strip()
if choice in menu:
clear()
menu[choice]()
def new_entry():
"""Create a new entry"""
clear()
employee = add_name()
task_ent = add_task()
time_ent = add_time()
date_ent = add_date()
notes_ent = add_notes()
entry = {
'employee_name': employee,
'task_name': task_ent,
'time': time_ent,
'date': date_ent,
'notes': notes_ent,
}
add_entry_summary(entry)
while True:
save = input("Would you like to save? [Y/n] \n").lower().strip()
if save == 'y':
input('\nEntry was saved. Press ENTER to continue.\n')
return entry
else:
input('\nEntry was not saved. Press ENTER to continue. \n')
return None
def add_task():
while True:
clear()
task_ent = input("What do you want to call this task?\n").strip()
if not task_ent:
input("You must enter a task name. Press enter. ")
else:
return task_ent
def add_time():
while True:
clear()
time_ent = input("Enter the number of minutes for the task.\n")
try:
int(time_ent)
except ValueError:
input("You must enter integers only. Press enter. ")
else:
return time_ent
def add_notes():
"""Asks for notes"""
clear()
notes_ent = input("Enter your notes. (ENTER if none)\n")
return notes_ent
def add_name():
clear()
while True:
employee = input("Enter a name. Then hit enter,"
" hit enter [Q] to go back\n").strip()
if employee.lower() == 'q':
prompt_menu()
break
elif not employee:
input("You must enter a name. Press enter.")
else:
return employee
def add_date():
clear()
while True:
date_ent = input("Enter a date "
"Date format MM/DD/YYYY\n").strip()
try:
date_ent = datetime.strptime(date_ent, '%m/%d/%Y').date()
except ValueError:
input("Sorry, that's not a valid date. Use MM/DD/YYYY format.")
continue
if date_ent > datetime.now().date():
input("Sorry you cannot select"
" a date in the futue. Press enter")
continue
else:
return date_ent
def add_entry_summary(entry):
clear()
print("Are these entries correct?\n")
print("""
Name: {employee_name}
Task Name: {task_name}
Time: {time}
Notes: {notes}
Date: {date}
""".format(**entry))
def save_entry():
"""Entry saved in database"""
entry = new_entry()
if entry:
return create_entry(entry)
def create_entry(entry):
"""Creates an entry"""
Entry.create(**entry)
return entry
def get_entries():
"""Gets the entries in the database sorted by date"""
entries = []
entry = Entry.select().order_by(Entry.date.desc())
for ent in entry:
entries.append(ent)
return entries
def get_search_entries(search):
"""Gets the entries for each search"""
entries = []
entry = Entry.select().order_by(Entry.date.desc())
entry = entry.where(search)
for ent in entry:
entries.append(ent)
return entries
def search_key():
"""Search by keyword"""
clear()
print("Search task and notes by a key word.")
while True:
print("Enter a word(s) to search by: ")
enter = input('> ')
if not enter:
input("You must enter a word. Press enter")
continue
else:
enter = Entry.task_name.contains(
enter) | Entry.notes.contains(enter)
entries = get_search_entries(enter)
list_entries(entries, enter)
return entries
def search_date():
"""Search an entry by date"""
while True:
clear()
print("Search by Date\n")
print(("*" * 20) + "\n")
print('n')
enter = add_date()
enter = Entry.date.contains(enter)
entries = get_search_entries(enter)
list_entries(entries, enter)
return entries
def search_time():
"""Search by employee's time spent working"""
clear()
print("Search by Time")
while True:
enter = add_time()
if enter:
enter = Entry.time == enter
entries = get_search_entries(enter)
list_entries(entries, enter)
return entries
def search_name():
"""Search by employee's name"""
clear()
print("Search by employee's name")
name = add_name()
name = Entry.employee_name.contains(name)
entries = get_search_entries(name)
list_entries(entries, name)
return entries
def list_entries(entries, search_info):
"""Shows list of entries"""
clear()
if entries:
return view_entry(entries)
else:
print('\nNo matches found.')
response = input("Would you like to make another"
" search? Y/n\n").lower().strip()
if response.lower() != 'y':
return prompt_menu()
else:
clear()
return lookup()
def view_entry(entries):
"""Displays entries on the screen"""
index = 0
while True:
clear()
print_entries(index, entries)
if len(entries) == 1:
print('\n[E]dit\n[D]elete\n[Q]uit')
sel = input('> ').lower().strip()
if sel == 'e':
return edit_entry(index, entries)
elif sel == 'd':
return delete_entry(index, entries)
elif sel == 'q':
return None
else:
input("Please input a valid command. Press ENTER.\n")
else:
display_option(index, entries)
nav = input("\nSelect an option. \n").lower().strip()
if index >= 0 and nav == 'n':
index += 1
clear()
elif index > 0 and nav == 'p':
index -= 1
clear()
elif nav == 'e':
return edit_entry(index, entries)
elif nav == 'd':
return delete_entry(index, entries)
elif nav == 'q':
return lookup()
else:
input('\nPlease make a valid selection. Press ENTER')
def print_entries(index, entry, display=True):
"""Prints entries"""
if display:
print('\n' + '*' * 20 + '\n')
print('Date: {}\nEmployee: {}\nTask: {}\nTime: {}\nNotes: {}'.format(
date_to_string(entry[index].date),
entry[index].employee_name,
entry[index].task_name,
entry[index].time,
entry[index].notes,
))
def lookup():
"""Look up a previous entry"""
choice = None
while True:
clear()
print("Search Entries\n")
for key, value in search_entries.items():
print("{}) {}".format(key, value.__doc__))
choice = input('\nChoose Search\n').lower().strip()
if choice in search_entries:
clear()
search = search_entries[choice]()
return search
def edit_entry(index, entries):
"""Edit an entry"""
clear()
print('Edit Entry\n')
single_entry(index, entries)
print('\n[T]ask name\n[D]ate\nTime [S]pent\n[N]otes')
sel = input('\nChoose an option to edit\n').lower().strip()
while True:
clear()
if sel == 't':
edit = edit_task(index, entries)
return edit
elif sel == 'd':
edit = edit_date(index, entries)
return edit
elif sel == 's':
edit = edit_time(index, entries)
return edit
elif sel == 'n':
edit = edit_notes(index, entries)
return edit
else:
input('Please make a valid selection. Press ENTER. \n')
def edit_task(index, entry):
"""Edits task name"""
entry[index].task_name = add_task()
ent = Entry.get(Entry.pk == entry[index].pk)
ent.task_name = entry[index].task_name
ent.save()
input("Entry Saved!")
return entry
def edit_date(index, entry):
"""Edits date"""
entry[index].date = add_date()
ent = Entry.get(Entry.pk == entry[index].pk)
ent.date = entry[index].date
ent.save()
input("Entry Saved!")
return entry
def edit_time(index, entry):
"""Edits time"""
entry[index].time = add_time()
ent = Entry.get(Entry.pk == entry[index].pk)
ent.time = entry[index].time
ent.save()
input("Entry Saved!")
return entry
def edit_notes(index, entry):
"""Edits notes"""
entry[index].notes = add_notes()
ent = Entry.get(Entry.pk == entry[index].pk)
ent.notes = entry[index].notes
ent.save()
input("Entry Saved!")
return entry
def delete_entry(index, entries):
"""Delete an entry """
entry = Entry.get(Entry.pk == entries[index].pk)
clear()
print("Delete Entry\n")
single_entry(index, entries)
sel = input("Are you sure you want to DELETE? Y/N\n").lower().strip()
if sel == 'y':
entry.delete_instance()
input("Entry deleted. Press Enter")
return None
else:
input("\nEntry not deleted. Press ENTER. \n")
return lookup()
def single_entry(index, entries):
"""shows a single entry"""
print('Date: {}\nEmployee: {}\nTask: {}\nTime: {}\nNotes: {}'.format(
date_to_string(entries[index].date),
entries[index].employee_name,
entries[index].task_name,
entries[index].time,
entries[index].notes,
))
def date_to_string(date):
"""Convets a datetime to a string"""
date_time = date.strftime('%m/%d/%Y')
return date_time
def clear():
os.system('cls' if os.name == 'nt' else 'clear')
def display_option(index, entries):
"""Displays a menu for paging through the results"""
p = "[P]revious entry"
n = "[N]ext entry"
e = "[E]dit entry"
d = "[D]elete entry"
q = "[Q]uit to menu"
menu = [p, n, e, d, q]
if index == 0:
menu.remove(p)
elif index == len(entries) - 1:
menu.remove(n)
print('\n')
for option in menu:
print(option)
return menu
search_entries = OrderedDict([
('n', search_name),
('d', search_date),
('t', search_time),
('k', search_key),
('q', prompt_menu),
])
menu = OrderedDict([
('n', save_entry),
('l', lookup),
])
if __name__ == "__main__":
initialize()
prompt_menu()
|
import random
# BigNum v1.0
# a game by Dan Sanderson (aka Doc Brown)
#
# Enter bet ('h' for instructions, 'q' to quit, 200 minimum):
# h
#
#
# BigNum is a fairly simple game. You have five places to put
# digits to construct a five digit number. These five digits are
# picked randomly (from 0 to 9), one by one. As they are picked,
# you choose where to put it. Once you place the digit, you can't
# move it. The goal is to construct the largest possible number with
# those digits.
#
# The board looks like this:
#
# a b c d e
# ---------------------
# | | | | | |
# ---------------------
#
# To place a digit, simply press the letter.
#
# If you get the largest number possible, you get back twice
# your bet! If you get the first digit the largest you get 25%
# of your bet back.
#
def instructions():
print("\n")
print("BigNum is a fairly simple game. You have five places to put")
print("digits to construct a five digit number. These five digits are")
print("picked randomly (from 0 to 9), one by one. As they are picked,")
print("you choose where to put it. Once you place the digit, you can't")
print("move it. The goal is to construct the largest possible number with")
print("those digits.")
print("\n")
print(" The board looks like this:")
print("\n")
print(" a b c d e ")
print(" ---------------------")
print(" | | | | | |")
print(" ---------------------")
print("\n")
print(" To place a digit, simply press the letter.")
print("\n")
print("If you get the largest number possible, you get back twice")
print("your bet! If you get the first digit the largest you get 25%")
print("of your bet back.\n")
return
def displayboard():
print(" The board currently looks like:")
print("\n")
print(" a b c d e ")
print(" ---------------------")
print(" | {} | {} | {} | {} | {} |".format(boardnum[0], boardnum[1], boardnum[2], boardnum[3], boardnum[4]))
print(" ---------------------")
print("\n")
return
# Give the player $1000 to start
wallet = 1000
# Initialize variables
bet = 0
minimumbet = 200
playerinput = ""
bignum = [0, 0, 0, 0, 0]
playernum = [0, 0, 0, 0, 0]
boardnum = [" ", " ", " ", " ", " "]
playagain = True
# Title screen
print(" BigNum v1.0")
print(" a game by Dan Sanderson (aka Doc Brown)\n")
print("Ported to Python 3 by Cliff Chipman")
while (playagain == True) & (wallet >= 200):
while (bet < minimumbet) | (bet > wallet):
bignum = [0, 0, 0, 0, 0]
playernum = [0, 0, 0, 0, 0]
boardnum = [" ", " ", " ", " ", " "]
print("You have ${} in your wallet.".format(wallet))
print("Enter your bet (${} minimum), 'h' for instructions, or 'q' to quit:".format(minimumbet))
playerinput = input()
playerinput = playerinput.lower() # Accept both upper & lower case letters
if playerinput == "h":
instructions()
elif playerinput == "q":
playagain = False
break
# exit()
else:
try:
# Did the player enter a valid numeric string?
bet = int(playerinput)
except ValueError:
bet = 0
# print("Bet = " + str(bet))
if playagain == False: break
wallet -= bet # Subtract bet from wallet
occupied = False # Flag that the player already picked a column for a number
goback = False # Flag that the player pressed an invalid key
# Generate bignum
for n in range(0,5):
num = random.randint(0,9) # pick a random number between 0 and 9 (inclusive)
bignum[n] = num
goback = True
while goback == True: # Loops back here if player presses any key besides "a" - "e"
if occupied == True: print("There is already a number there.")
occupied = False # Reset the flag
displayboard()
print("The number is {}".format(num))
playerinput = input("Place:")
playerinput = playerinput.lower() # Convert all incoming letters to lowercase to accept either
if playerinput == "a": # | (playerinput == "A")): # Player picked column a
if boardnum[0] != "":
playernum[0] = num
boardnum[0] = str(num)
goback = False
else:
occupied = True
elif playerinput == "b": # | (playerinput == "B")): # Player picked column b
if boardnum[1] != "":
playernum[1] = num
boardnum[1] = str(num)
goback = False
else:
occupied = True
elif playerinput == "c": # | (playerinput == "C")): # Player picked column c
if boardnum[2] != "":
playernum[2] = num
boardnum[2] = str(num)
goback = False
else:
occupied = True
elif playerinput == "d": # | (playerinput == "D")): # Player picked column d
if boardnum[3] != "":
playernum[3] = num
boardnum[3] = str(num)
goback = False
else:
occupied = True
elif playerinput == "e": # | (playerinput == "E")): # Player picked column e
if boardnum[4] != "":
playernum[4] = num
boardnum[4] = str(num)
goback = False
else:
occupied = True
else: # Player picked some other character!
occupied = True
bignum = sorted(bignum, reverse=True) # Make bignum the biggest number possible
print("The board is full.")
print("Your number is: {}{}{}{}{}".format(playernum[0],playernum[1],playernum[2],playernum[3],playernum[4]))
print("The highest possible number: {}{}{}{}{}".format(bignum[0],bignum[1],bignum[2],bignum[3],bignum[4]))
# Calculate player's score
# If you get the largest number possible, you get back twice your bet!
# If you get the first digit the largest you get 25% of your bet back.
# Otherwise, you get nothing.
if playernum == bignum: # If you get the largest number possible, you get back twice your bet!
print("You made the largest number possible!")
print("You won ${}".format(int(bet * 2)))
wallet += bet * 2
elif playernum[0] == bignum[0]: # If you get the first digit the largest you get 25% of your bet back.
print("You got the first digit!")
print("You won ${}".format(int(bet * 0.25)))
wallet += bet * 0.25
else:
print("Sorry, no money awarded this round.") # Sorry -- you get nothing -- try again
bet = 0
# playagain should be false at this point
print("You are leaving the game with ${}".format(int(wallet)))
if wallet < 200: print("You don't have enough money to place a bet.")
print("Thanks for playing!")
exit() |
def hamming():
dna_1 = raw_input("Enter string 1: ")
dna_2 = raw_input("Enter string 2: ")
d_h = 0
for i in range(len(dna_1)):
if dna_1[i] != dna_2[i]:
d_h += 1
print d_h
hamming()
|
def reverse_complement():
dna = raw_input("String: ")
dna = dna[::-1]
dna = list(dna)
for i in range(len(dna)):
if dna[i] == "A":
dna[i] = "T"
elif dna[i] == "T":
dna[i] = "A"
elif dna[i] == "G":
dna[i] = "C"
elif dna[i] == "C":
dna[i] = "G"
else:
print "Invalid character"
print "".join(dna)
reverse_complement()
|
# a d g
# b e h
# c f
import math
def print_f(string):
list_string = string.split(" ")
list_string = sorted(list_string)
N = len(list_string)
num = math.ceil(N/3)
table=[]
for row in range(num):
temp=[]
for col in range (row, N, 3):
temp.append(list_string [col])
table.append(temp)
for element in table:
print("")
for item in element:
print(item, "\t", end='')
bin
print_f("a b c d e f g")
# print_f("a b c d e f g h")
# Input:
# "elephant cat caterpillar frog zebra rabbit dog cow alligator"
# Output:
# alligator cow frog
# cat dog rabbit
# caterpillar elephant zebra
# Example 2:
# Input:
# "a b c d e f g"
# Output:
# a c e
# b d f
# g
# or
# a d f
# b e g
# c
# PLEASE NOTE: The following output is INCORRECT:
# a d g
# b e
# c f
#
# Example 3:
# Input:
# "a b c d e f g h"
# Output:
# a c f
# b d g
# e h
# or
# a d g
# b e h
# c f
|
# import random
# import os
# import time
# import sys
# terminal_size = os.get_terminal_size()
# def recursive():
# num = 3
# for col in range(terminal_size[0]):
# for position in range(0, terminal_size[1]):
# num *= random.randint(1, 10)
# f = random.randint(1, 2)
# if f == 1:
# print(" ",end=' ')
# sys.stdout.flush()
# time.sleep(0.1)
# print(num,end=' ')
print(pow(2,31) -1 )
# lis = [1]* 1000000
# sum = 0
# def sum_recursive(lis, sum):
# chr_string = lis[0]
# sum += ord(str(chr_string))
# substr = lis[1:]
# if len(substr) == 0:
# return sum
# else:
# return sum_recursive(substr, sum)
# print(sum_recursive(lis, sum))
# print(num,flush=True)
# recursive()
# recursive()
# print('foo', flush=True) )
# num = 3
# for col in range(terminal_size[0]):
# for position in range(0, terminal_size[1]):
# num *= random.randint(1, 10)
# import turtle, random
# colors = ["red","green","blue","orange","purple","pink","yellow"] # Make a list of colors to picvk from
# turtle.width(10) #What does this line do?
# length = 5
# for count in range(100):
# color = random.choice(colors) #Choose a random color
# turtle.forward(length)
# turtle.right(135)
# turtle.color(color) # Why is color spelt like this?
# length = length + 5
# print(num)
# for
# for position in range(terminal_size[0)
# for
# print(random.randint(1, 10)) |
class Node:
def __init__(self, data=None, next=None):
self.data = data
self.next = next
class SingleLinkedList:
def __init__(self):
self.head = None
def add_node(self, data):
newNode = Node(data)
if self.head:
current = self.head
while current.next:
current = current.next
current.next = newNode
else:
self.head = newNode
#NOTE1: or using append, **** BE CAREFUL IN PYTHON****: concat + only applies on the same type. Example: TypeError for concat two different types int and list
def print_ll(self):
current = self.head
ll_data = []
while current:
ll_data += [current.data] #Ref_To NOTE1
current = current.next
return ll_data
# -------------------Brute Force ------------------------
def remove_duplicates_brute_sol(self):
current = self.head
while current:
pointer = current.next
prev_node = None
while pointer:
if prev_node is not None:
if current.data == pointer.data:
prev_node.next = pointer.next
return
prev_node = pointer
pointer = pointer.next
else:
prev_node = self.head
current = current.next
# -------------------Hash Table ------------------------
def remove_duplicates_hashtable_sol(self):
hash_table = set()
current = self.head
prev_node = None
while current:
if prev_node is not None:
if current.data in hash_table:
prev_node.next = current.next
return
prev_node = current
hash_table.add(current.data)
current = current.next
else:
prev_node = self.head
ll = SingleLinkedList()
for item in [13,34,76,8,16,13]:
ll.add_node(item)
print(ll.print_ll())
ll.remove_duplicates_hashtable_sol()
print(ll.print_ll())
|
def recursive_multiply(first_num, second_num):
if second_num == 0 or any(num < 0 for num in (first_num,second_num)):
return 0
return first_num + recursive_multiply(first_num, second_num-1)
print(recursive_multiply(-1, -2)) |
# def get_perm(string):
# perm = []
# if len(string) == 0:
# perm.append(" ")
# return perm
# first = string[0]
# remaining = string[1:]
# words = get_perm(remaining)
# for word in words:
# index = 0
# for letter in word:
# permutation = charAt(word, first, index)
# perm.append(permutation)
# index += 1
# return perm
# def charAt(word, first, index):
# start = word[:index]
# end = word[index:]
# return start + first + end
# def check_palindrome(list_of_perm):
# print(list_of_perm)
# for word in list_of_perm:
# word_nospace = word.strip()
# str_new = ''
# for ind in range(len(word_nospace)-1, -1, -1):
# str_new += word[ind]
# if word_nospace == str_new:
# return True
# else:
# return False
# print(check_palindrome(get_perm("tact coa")))
# def is_palindrome(string):
# table = [0] * 128
# for letter in string:
# table[ord(letter)] += 1
# return check_max_odd_num(table)
# def check_max_odd_num(table):
# index = 0
# for element in table:
# if element % 2 == 1:
# if index ==1:
# return False
# index += 1
# return True
def get_perm(string):
ascii_list = [0] * 128
string = string.lower()
foundOdd = False
for letter in string:
if letter != " ":
ascii_list[ord(letter)] +=1
for item in ascii_list:
if item == 0:
continue
else:
if item % 2 == 1:
if foundOdd:
return False
foundOdd = True
return True
print(get_perm("Tact oa"))
|
# Write a function that rotates a list by k elements.
# For example [1,2,3,4,5,6] rotated by two becomes [3,4,5,6,1,2].
# Try solving this without creating a copy of the list.
# How many swap or move operations do you need?
# step 1 - take in argument k
def Rotate(k, l):
# based on k, we pop the initial value of the list then append to the end.
for i in range(k):
tmp = l[0]
for i in range(len(l)-1):
l[i] = l[i+1]
l[-1] = tmp
return l
#return the list
[2, 3, 4, 5, 6, 6]
alist = [1,2,3,4,5,6]
# print(Rotate(2, alist))
def RotateIt(k,l):
# Try solving this without creating a copy of the list.
result = l[k:] + l[:k]
return result
def Rotate3(k, l):
# based on k, we pop the initial value of the list then append to the end.
tmp = l[:k]
for i in range(len(l)-k):
l[i] = l[i+k]
for i, v in enumerate(tmp):
l[len(l) - k + i] = v
return l
#return the list
print(Rotate(2,[1,2,3,4,5,6]))
print(RotateIt(2,[1,2,3,4,5,6]))
print(Rotate3(2,[1,2,3,4,5,6]))
|
class LinkedListNode:
def __init__(self, value):
self.value = value
self.next = None
def __str__(self):
return self.value
def p(self):
if self.next:
print self.value, self.next.p()
else:
print self.value
def insert(self, v):
if self.next:
self.next.insert(v)
else:
self.next = LinkedListNode(v)
def reverse(node):
_prev = None
while True:
if node.next == None:
node.next = _prev
return node
_next = node.next
node.next = _prev
_prev = node
node = _next
node = LinkedListNode(1)
node.insert(2)
node.insert(3)
node.p()
reverse(node).p()
|
# https://www.interviewcake.com/question/python/find-rotation-point
def solve(alist):
return binary(alist, 0, len(alist))
# the space is O(lgN)
def binary(alist, i, j):
mid = (j-i) / 2
mid_value = alist[mid]
if alist[mid-1] > mid_value:
return mid
if mid_value > alist[0]:
# should be the right side
return binary(alist, mid, j)
if mid_value < alist[-1]:
# should be the left side
return binary(alist, i, mid)
# only O(1)
def solve(alist):
i, j = 0, len(alist)
while True:
mid = (j-i) / 2
mid_value = alist[mid]
if alist[mid-1] > mid_value:
return mid
if mid_value > alist[0]:
i = mid
elif mid_value < alist[-1]:
j = mid
words = [
'ptolemaic',
'retrograde',
'supplant',
'undulate',
'xenoepist',
'asymptote', # <-- rotates here!
'babka',
'banoffee',
'engender',
'karpatka',
'othellolagkage',
]
assert solve(words) == 5
|
x = "hello"
y = "hello"
print(x is y)
print(x == y) |
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def nameLength(self):
return len(self.name)
p1 = Person("John", 36)
print(p1.name)
print(p1.age)
print(p1.nameLength()) |
def filter2(s):
if len(s) == 0: return False
res = True
for c in s:
k = ord(c)
if k < 97 or k > 122:
res = False
break
return res
def filter1(s, t):
res = 0
for c in s:
if c == t: res = res + 1
return res == 1
def filter3(s):
pos1 = s.find('@')
pos2 = s.find('.')
return pos1 < pos2
def solution(s):
res = "No"
if filter1(s, '@') and filter1(s, '.') and filter3(s):
parts = s.split('@')
aaa = parts[0]
part2 = parts[1].split('.')
bbb = part2[0]
ccc = part2[1]
if filter2(aaa) and filter2(bbb) and filter2(ccc):
res = "Yes"
return res
print(solution(input()))
|
import re
txt = "The rain in Spain"
x = re.sub(r"[a-z]", "*", txt)
print(x) |
# Write a program which will find all such numbers which are divisible by 7 but are not a multiple of 5,
# between 2000 and 3200 (both included).
# The numbers obtained should be printed in a comma-separated sequence on a single line.
# Hints:
# Consider use range(#begin, #end) method
length = []
for i in range(2000, 3200):
if ( i % 7 ==0 ) and (i % 5 !=00):
length.append(str(i))
# print(','.join(length))
# Question:
# Write a program which can compute the factorial of a given numbers.
# The results should be printed in a comma-separated sequence on a single line.
# Suppose the following input is supplied to the program:
# 8
# Then, the output should be:
# 40320
def fact(x):
if x == 0:
return 1;
return x * fact(x - 1)
# x=int(raw_input())
# print fact(x)
# Question:
# 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}
# Hints:
# In case of input data being supplied to the question, it should be assumed to be a console input.
# Consider use dict()
for i in range(2000, 3200):
if ( i % 7 ==0 ) and (i % 5 !=00):
length.append(str(i))
|
# Colored Triangles
# A coloured triangle is created from a row of colours, each of which is red, green or blue.
# Successive rows, each containing one fewer colour than the last, are generated by considering
# the two touching colours in the previous row. If these colours are identical, the same colour
# is used in the new row. If they are different, the missing colour is used in the new row.
# This is continued until the final row, with only a single colour, is generated.
# The different possibilities are:
# Colour here: G G B G R G B R
# Becomes colour: G R B G
#With a bigger example:
# R R G B R G B B
# R B R G B R B
# G G B R G G
# G R G B G
# B B R R
# B G R
# R B
# G
# You will be given the first row of the triangle as a string and its your job to return the final
# colour which would appear in the bottom row as a string. In the case of the example above, you
# would the given RRGBRGBB you should return G.
# * The input string will only contain the uppercase letters R, G, B and there will be at least one
# letter so you do not have to test for invalid input.
# * If you are only given one colour as the input, return that colour.
import unittest
class Triangle:
COLOR_TRANSLATION = {
'BG': 'R', 'GB': 'R',
'RG': 'B', 'GR': 'B',
'BR': 'G', 'RB': 'G',
}
def __init__(self, bottom_row):
self.triangle = self.build_triangle(bottom_row)
def build_triangle(self, bottom_row):
base_size = current_base = len(bottom_row)
triangle = [bottom_row]
for i in range(0, base_size-1):
next_row = ''
for j in range(1, current_base):
parents = triangle[i][j-1:j+1]
next_row += parents[0] if parents[0] == parents[1] else self.COLOR_TRANSLATION[parents]
triangle.append(next_row)
current_base -= 1
return triangle
def point_color(self):
return self.triangle[-1][0]
def triangle(bottom_row):
return Triangle(bottom_row).point_color()
class MyTest(unittest.TestCase):
def test_1(self):
self.assertEqual(triangle('GB'), 'R')
def test_2(self):
self.assertEqual(triangle('RRR'), 'R')
def test_3(self):
self.assertEqual(triangle('RGBG'), 'B')
def test_4(self):
self.assertEqual(triangle('RBRGBRB'), 'G')
def test_5(self):
self.assertEqual(triangle('RBRGBRBGGRRRBGBBBGG'), 'G')
def test_6(self):
self.assertEqual(triangle('B'), 'B')
unittest.main()
|
import matplotlib.pyplot as plt
# set the size of the graph image
plt.rcParams["figure.figsize"] = (19, 11)
def plot(p_type: str, x_axis: list, points: list, title: str, x_label: str, y_label: str, y_min_lim=0, y_max_lim=0,
color='blue', marker='D',
width=0.30):
# if y_min_lim and y_max_lim are not provided then calculate them on the basis of the min and max values in
# points variable
if y_min_lim == 0 and y_max_lim == 0:
y_min_lim = int(round(min(points) - 1))
y_max_lim = int(round(max(points) + 1))
plt.title(title)
plt.xlabel(x_label, fontsize=3)
plt.ylabel(y_label)
if p_type == 'plot':
plt.plot(x_axis, points, marker=marker, color=color)
elif p_type == 'stem':
plt.stem(x_axis, points, use_line_collection=True)
elif p_type == 'bar':
plt.bar(x_axis, points, width=width, color=color)
# rotate the labels on x-axis
plt.xticks(rotation=90)
# set the minimum and maximum value of y-axis
axes = plt.gca()
axes.set_ylim([y_min_lim, y_max_lim])
# Save the graph
plt.savefig(f'graphs/{title}.png', bbox_inches='tight')
# NOTE: If we don't place plt.show() after plt.savefig() then it will save all the graphs in one image
plt.show()
|
##############################################
## Name: Creating two stacks using an array ##
## Owner: Darshit Pandya ##
## Purpose: Data Structures Practice ##
##############################################
class TwoStacks():
def __init__(self, n):
self.n = n
self.top1 = -1
self.top2 = self.n
self.array_ = [None] * self.n
def push_1(self, element):
if self.top1 < self.top2 - 1:
self.top1 = self.top1 + 1
self.array_[self.top1] = element
else:
print("Stack Overflow")
exit(1)
def push_2(self, element):
if self.top1 < self.top2 - 1:
self.top2 = self.top2 - 1
self.array_[self.top2] = element
else:
print("Stack Overflow")
exit(1)
def pop_1(self):
## returns the top of the stack of the first stack
if self.top1 > -1:
popped_value = self.array_[self.top1]
self.array_[self.top1] = None
self.top1 = self.top1 - 1
return popped_value
else:
print("Stack empty")
exit(1)
def pop_2(self):
## returns the top of the stack for the second stack
if self.top2 < self.n:
popped_value = self.array_[self.top2]
self.array_[self.top2] = None
self.top2 = self.top2 + 1
return popped_value
else:
print("Stack Empty")
exit(1)
if __name__ == "__main__":
twostacks = TwoStacks(5)
twostacks.push_1(10)
twostacks.push_1(11)
twostacks.push_2(12)
print("Pop from the first stack: ", twostacks.pop_1())
print("Pop from the second stack: ", twostacks.pop_2())
## Let's verify stack empty scenario
twostacks.pop_2()
|
################################################
## Name: Implementation of Binary Search Tree ##
## Owner: Darshit Pandya ##
## Purpose: Data Structure Practice ##
################################################
class Node:
def __init__(self, value):
self.left = None
self.right = None
self.value = value
class BSTree(Node):
def __init__(self):
self.root = None
def creation_(self, list_values):
"""
Create a Binary Search Tree using the given values
Arguments:
list_values: List of values to create the binary search tree
"""
|
"""
For Class #3 of an informal mini-course at NYU Stern, Fall 2014.
Topics: pandas data management
Repository of materials (including this file):
* https://github.com/DaveBackus/Data_Bootcamp
Prepared by Dave Backus, Sarah Beckett-Hile, and Glenn Okun
Created with Python 3.4
"""
import pandas as pd
"""
Examples of DataFrames
"""
# 538's income by college major
url1 = 'https://raw.githubusercontent.com/fivethirtyeight/'
url2 = 'data/master/college-majors/recent-grads.csv'
url = url1 + url2
df538 = pd.read_csv(url)
#%%
# check to see what we have
df538.head() # list first five observations
df538.tail() # last five
#%%
# look at column names (.tolist() isn't necessary but easier to read)
df538.columns
df538.columns.tolist()
df538.index.tolist()
#%%
# Fama-French equity return data
import pandas.io.data as web
ff = web.DataReader('F-F_Research_Data_Factors', 'famafrench')[0]
ff.columns = ['xsm', 'smb', 'hml', 'rf']
#%%
# constructing a DataFrame from scratch
codes = ['USA', 'FRA', 'JPN', 'CHN', 'IND', 'BRA', 'MEX']
countries = ['United States', 'France', 'Japan', 'China', 'India',
'Brazil', 'Mexico']
# Wikipedia, 2013 USD
gdppc = [53.1, 36.9, 36.3, 11.9, 5.4, 15.0, 16.5] # thousands
gdp = [16.8, 2.5, 4.7, 16.1, 6.8, 3.0, 2.1] # trillions
df = pd.DataFrame([gdp, gdppc, countries]).T
#df.columns = ['GDP (trillions of USD)', 'GDP per capita (thousands of USD)',
# 'Country Code']
df.columns = ['gdp', 'gdppc', 'country']
df.index = codes
#%%
# Spencer's version
# Warning: uses a dictionary, skip if you don't know what that is
data = {"GDP (trillions of USD)": gdp,
"GDP per capita (thousands of USD)": gdppc,
"Country": countries}
dfspencer = pd.DataFrame(data, index=codes)
#%%
# Exercise
x = [1, 2, 5, 7, 10]
y = [10, 7, 5, 2, 1]
days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday']
"""
Selecting variables and observations
"""
# check
print(df)
some = df[0:3]
print(some)
keep_obs = [0, 1] #['USA', 'BRA', 'JPN']
keep_var = ['gdp', 'country']
other = df[keep_obs]
print(other)
print(df[0:3])
#%%
"""
Constructing new variables
"""
df.pop = df.gdp/df.gdppc
#%%
df['pop'] = df['gdp']/df['gdppc']
print(df) |
"""
Sarah's Chipotle code
"""
import pandas as pd
#import numpy as np
#import re
# first, define a pathway to tell python where this data can be found
path = 'https://raw.githubusercontent.com/TheUpshot/chipotle/master/orders.tsv'
# now import the data with pandas' read_table function
# read_table turns the data into a pandas DataFrame. Assign the dataframe the name df
df = pd.read_table(path)
# to take a quick look at the first few rows of the data, use the method .head()
# .head(10) returns the first 10 rows. If you don't specify a number, the default is 5
df.head(10)
# This data isn't well formatted for analysis for a few reasons:
#
# - The item price has a $ symbol, so python will treat it like a string
# - and we can't do math with strings
#
#
# - The choice description isn't standardized
# - everything is all clumped together
# - so you can't do much to learn about the popularity of each item or its correlation with the main order
#
#
# - Sometimes the same choice_description isn't consistently written out
# - for example, row 4 has "Tomatillo-Red Chili Salsa (Hot)"
# - but row 7 has "Tomatillo Red Chili Salsa"
# - these are the same menu item, but Python won't recognize that
# So now we have 3 main goals:
# 1. change the item_price so that we can do math with it
# 2. separate the data in choice_description into different columns
# 3. standardize the names of the different items so they can be grouped more easily
# start by trying to sum up the vales in quanity:
df.quantity.sum()
# see? that was easy!
# now try to do the same with item_price
df.item_price.sum()
# that's a mess. it's because pandas saw the $ symbol and imported the data in the column as strings instead of numbers
# another way to diagnose this problem would be to check the datatype of one of the cells in the column
#type(df['item_price'][0])
df.dtypes
# to fix the price, we'll start by using the pandas method .replace()
# More on replace: http://pandas.pydata.org/pandas-docs/version/0.17.0/generated/pandas.DataFrame.replace.html
# replace() is read as follows: look at column item_price, find the $, and replace it with nothing
df = df.replace(to_replace = {'item_price': {'\$': ''}}, regex=True)
# we used regex=True, otherwise Pandas would have looked for cells where $ was the only thing present
# problem is, $ is a symbol that has other operations in regular expression
# so we put a backslash in front of $ to tell regex "just treat $ as a normal character, not as an operator"
# this is a quirk of regex. If you want to learn more: https://docs.python.org/2/library/re.html
# now take a look
df.head()
# but we're still having problems with item_price
df.item_price.sum()
# this will create a new column 'price' that will turn the values in item_price into "floats"
df['price'] = df.item_price.astype('float')
# now this works!
df.price.sum()
# finally, let's just get rid of the old item_price column
del df['item_price']
# great! this is our new dataset with a nicely formatted price column
df.head()
# ## And now for something completely different...
# Now that we have the price column whipped into shape, let's take a closer look at the choice_description column:
df[['choice_description']].head(10)
# this is useless if we wanted to analyize the frequency of each of these sides
# first, let's get rid of the brackets using the same method we used to get rid of the $ symbol above
list_of_things_to_replace = ['\[', '\]'] # again, we'll need backslashes in front of the brackets to tell regex to treat them as normal characters
thing_we_want_to_replace_it_with = '' #t wo quotes with nothing in them means we'll just replace the brackets with nothing
df = df.replace(to_replace = list_of_things_to_replace , value = thing_we_want_to_replace_it_with, regex = True) #regex means it'll look for brackets anywhere, otherwise it would look for cells whose only value was [ or ]
df.head()
# Next, let's make a unique list of all the possible sides that appear in choice_description
choice_list = [] # start with an empty list
for i in range(len(df)): # basically for every row in the df
if type(df['choice_description'][i]) == float: # if it's a number ignore it, this helps us with those NaN values
pass
else:
order_list = df['choice_description'][i].split(", ") # use those commas as your deliminator
for item in order_list: # now you have a little list of each item in choice_description in each row
choice_list.append(item) # add that list to the master list
choice_df = pd.DataFrame(data=choice_list, columns=['Choices']) # turn this list into a little dataframe
# Now we can do some analysis. We'll start by counting how many times each side appears and ordering by most popular. We'll create a table that only takes the top 10 sides:
most_pop_choices = (pd.DataFrame(
choice_df.groupby('Choices')
.size(),
columns=['Count'])
.sort('Count',ascending=False)
.head(10)
.reset_index())
most_pop_choices
least_pop_choices = (pd.DataFrame(
choice_df.groupby('Choices')
.size(),
columns=['Count'])
.sort('Count',ascending=True)
.head(10)
.reset_index())
least_pop_choices
# some of these appear to be the same but with slightly different labels
# let's try to clean that up with some simple search-and-replace
# for instance, there are "vegetarian black beans" and "black beans", which should just be the same thing
# we can use regex for this!
# with method .replace(), you don't actually have to say "to_replace = " and "value = "
# Python will understand the first and second arguments to be these values
fix_beans = choice_df.replace('Vegetarian Black Beans',
'Black Beans', regex=True)
# let's do the same for salsas
# they recorded corn salsa 3 different ways: 'Roasted Chili Corn (Medium)', 'Roasted Chili Corn Salsa', and 'Roasted Chili Corn Salsa (Medium)'
# if we want our analysis to group these together, we can use regex again
# this time we'll use a list in the to_replace arguement
fix_salsas = fix_rice_beans.replace(['Roasted Chili Corn Salsa','Tomatillo Green Chili (Medium)'],
'Roasted Chili Corn Salsa (Medium)')
# further discussion needed about using $, ^, *, ., etc
|
"""
Messing around with World Bank data. We start by reading in the whole WDI
from the online csv. Since the online file is part of a zipped collection,
this turned into an exploration of how to handle zip files -- see Section 1.
Section 2 (coming) does slicing and plotting.
Prepared for the NYU Course "Data Bootcamp."
More at https://github.com/DaveBackus/Data_Bootcamp
References
* http://datacatalog.worldbank.org/
* http://stackoverflow.com/questions/19602931/basic-http-file-downloading-and-saving-to-disk-in-python
* https://docs.python.org/3.4/library/urllib.html
Written by Dave Backus @ NYU, September 2014
Created with Python 3.4
"""
import pandas as pd
import urllib
import zipfile
import os
"""
1. Read data from component of online zip file
"""
# locations of file input and output
url = 'http://databank.worldbank.org/data/download/WDI_csv.zip'
file = os.path.basename(url) # cool tool via SBH
# the idea is to dump data in a different directory, kill with data = ''
data = '' # '../Data/'
#%%
# copy file from url to hard drive (big file, takes a minute or two)
urllib.request.urlretrieve(url, data+file)
#%%
# zipfile contains several files, we want WDI_Data.csv
print(['Is zipfile?', zipfile.is_zipfile(file)])
# key step, give us a file object to work with
zf = zipfile.ZipFile(data+file, 'r')
print('List of zipfile contents (two versions)')
[print(file) for file in zf.namelist()]
zf.printdir()
#%%
# copy data file to hard drive's working directory, then read it
csv = zf.extract('WDI_Data.csv')
df1 = pd.read_csv('WDI_Data.csv')
print(df1.columns)
#%%
# alternative: open and read
csv = zf.open('WDI_Data.csv')
df2 = pd.read_csv(csv)
print(df3.columns)
#%%
# same thing in one line
df3 = pd.read_csv(zf.open('WDI_Data.csv'))
print(df3.columns)
# zf.close() #??
# do we want to close zf? do we care?
# seems to be essential with writes, not so much with reads
# if so, can either close or use the "with" construction Sarah used.
# basic open etc:
# https://docs.python.org/3.4/tutorial/inputoutput.html#reading-and-writing-files
# on with (go to bottom): http://effbot.org/zone/python-with-statement.htm
#%%
# could we further consolidate zip read and extract? seems not.
#zf = zipfile.ZipFile(url, 'r')
|
import pinject
class OuterClass(object):
def __init__(self, inner_class):
self.inner_class = inner_class
class InnerClass(object):
def __init__(self):
self.forty_two = 42
obj_graph = pinject.new_object_graph()
outer_class = obj_graph.provide(OuterClass)
print(outer_class.inner_class.forty_two)
# pinject 自动把inner_class翻译成了InnerClass,然后实例化了一个给outerClass
# 那么如果要传入不同的InnerClass该怎么操作呢
# 是否可以通过字符串来注入和反射呢 |
from fractions import gcd
# all numbers divisible by these are summed
residues = (3, 5)
# max number to check to (exclusive
max_num = 1000
# returns the result from brute force checking
def brute_force():
# the end sum
result = 0
# loop through every number under max, and manually check
for i in range(0, max_num):
# make sure it gets reset
add_bool = False
# manually check all in residues
for j in residues:
if i % j == 0:
# if it passes even one, mark it
add_bool = True
# if it is divisible by any residue, add it to the result
if add_bool:
result += i
# return the sum
return result
# returns the result using accelerated summation techniques
def fast_solution():
# sums multiples of a up to max (not including)
def mult(a):
# use this for max sum (the -1 is because it is exclusive)
st = (max_num - 1) / a
# standard summation of a linear sequence
return (a * (st * (st+1))) / 2
# s(a)+s(b)-s(lcm(a, b))
# this part counts the multiples of 3, and 5, but then subtracts off the multiples of 3 and 5 (15), so that they are only counted once
return mult(residues[0]) + mult(residues[1]) - mult((residues[0] * residues[1]) / gcd(residues[0], residues[1]))
print "Sum of numbers that are multiples of %s up to %s is %s (brute force)" % (" or ".join(map(str, residues)), max_num, brute_force())
print "Sum of numbers that are multiples of %s up to %s is %s (fast solution)" % (" or ".join(map(str, residues)), max_num, fast_solution())
|
# -*- coding: utf-8 -*-
from collections import namedtuple
import menu
jogadorReg = namedtuple("jogadorReg", "cod, cod_equipa, nome, golosm, goloss, cartõesa, cartõesv")
listaJogadores = []
def encontrar_posicao(codigo):
pos = -1
for i in range (len(listaJogadores)):
if listaJogadores[i].id == codigo:
pos = i
break
return pos
def inserir_jogador():
cod = input("Qual o codigo do jogador? ")
pos = encontrar_posicao(cod)
if pos >= 0:
print "Código já existe"
return
#ler dados
nome = raw_input("Qual o nome? ")
codequipa = input("Qual o codigo do jogador? ")
registo = jogadorReg(cod, codequipa, nome, 0, 0, 0, 0)
listaJogadores.append(registo)
def pesquisar_jogador():
cod = input("Qual o codigo do jogador a pesquisar? ")
pos = encontrar_posicao(cod)
if pos == -1:
print "Não existe jogador com esse código"
return
print "Código: ", listaJogadores[pos].id
print "Nome: ", listaJogadores[pos].nome
def listar_jogadores():
for i in range (len(listaJogadores)):
print "Código: ", listaJogadores[i].id
print "Nome: ", listaJogadores[i].nome
def eliminar_jogador():
cod = input ("Código do jogador a eliminar --> ")
pos = encontrar_posicao(cod)
if pos == -1:
print "Não existe jogador com esse código"
return
# TODO: Confirmar eliminação
listaJogadores.pop(pos)
def alterar_jogador():
cod = input ("Código do jogador a alterar --> ")
pos = encontrar_posicao(cod)
if pos == -1:
print "Não existe jogador com esse código"
return
# só altera o nome
novojogador = raw_input("Qual o nome? ")
listaJogadores[pos] = listaJogadores[pos]._replace(nome=novojogador)
def gerir():
terminar = False
while not terminar:
op = menu.jogadores()
if op == '1':
inserir_jogador()
elif op =='2':
listar_jogadores()
elif op == '3':
pesquisar_jogador()
elif op == '4':
alterar_jogador()
elif op == '5':
eliminar_jogador()
elif op == '0':
terminar = True
if __name__ == "__main__":
print "Este programa não deve ser executado diretamente"
|
#!/usr/bin/env python3
def test_0():
print("Hello, World!")
def test_1(n: int) -> None:
def _is_even(n: int) -> bool:
if n % 2 == 0:
return True
return False
if _is_even(n):
if (n >= 2 and n <= 5) or (n > 20):
print("Not Weird")
return
print("Weird")
def test_2(a: int, b: int) -> None:
print(a+b)
print(a-b)
print(a*b)
def test_3(a: int, b: int) -> None:
print(a//b)
print(a/b)
def test_4(n: int) -> None:
for i in range(n):
print(i**2)
def is_leap(year):
if year % 4 == 0:
if year % 100 == 0:
if year % 400 == 0:
return True
return False
return True
return False
def print_one_to_n(n: int):
for i in range(1,n+1):
print(i, end='')
print('\n')
if __name__ == "__main__":
from sys import argv
try:
func_args = ", ".join(argv[2:])
except IndexError:
func_args = None
func_to_run = "test_{:d}({:s})".format(int(argv[1]), func_args)
eval(func_to_run)
|
import eulerlib
import itertools
def compute(number_of_digits: int = 3) -> int:
"""
A palindromic number reads the same both ways. The largest palindrome made from the product of
two 2-digit numbers is 9009 = 91 × 99.
Find the largest palindrome made from the product of two 3-digit numbers.
Notes:
This is super slow and doesn't skip all the products that have already been computed
in reverse (i.e. won't skip xy if yx has been computed), but gives the right answer
Args:
digits (int, optional): number of digits in product numbers. Defaults to 3.
Returns:
int: largest palindromic product
"""
largest_palindrome = -1
digits = eulerlib.n_digit_numbers(number_of_digits)
for i, j in itertools.product(digits, repeat=2):
k = i * j
if eulerlib.is_palindromic(k):
if k > largest_palindrome:
largest_palindrome = k
return largest_palindrome if largest_palindrome != -1 else None
|
def swap_case(s):
s = list(s)
for i, char in enumerate(s):
if char.isupper():
s[i] = char.lower()
if char.islower():
s[i] = char.upper()
return "".join(s)
def split_and_join(line):
return "-".join(line.split(" "))
def print_full_name(a, b):
print('Hello {} {}! You just delved into python.'.format(a, b))
def mutate_string(string, position, character):
string = list(string)
string[position] = character
return "".join(string)
def count_substring(string, sub_string):
count = 0
substr_len = len(sub_string)
for i in range(0, len(string)):
if string[i:i + substr_len] == sub_string:
count += 1
return count
def validate_string(s):
print(any([char.isalnum() for char in s]))
print(any([char.isalpha() for char in s]))
print(any([char.isdigit() for char in s]))
print(any([char.islower() for char in s]))
print(any([char.isupper() for char in s]))
def capitalize(string):
s = string.split(" ")
for i, word in enumerate(s):
s[i] = word.capitalize()
return " ".join(s)
|
import math
def compute(n: int = 20) -> int:
"""
So I cheated and saw that this was a well-known combinatorial problem. For an n x n grid,
the answer is 2n choose n.
Args:
n (int, optional): n by n grid. Defaults to 20.
"""
return math.factorial(2 * n) // (math.factorial(n) * math.factorial(n)) |
import sqlite3
con=sqlite3.connect('uservisit.db')
cur=con.cursor()
print("Database Created Successfully")
cur.execute("DROP TABLE if EXISTS admin")
cur.execute('''CREATE TABLE admin
(admin_id INT PRIMARY KEY NOT NULL,
admin_name TEXT NOT NULL,
admin_uname TEXT NOT NULL,
admin_password TEXT,
admin_email TEXT);''')
print("Table admin Created Successfully")
cur.execute("DROP TABLE if EXISTS user")
cur.execute('''CREATE TABLE user
(user_id INTEGER PRIMARY KEY AUTOINCREMENT,
user_flname TEXT NOT NULL,
user_email TEXT NOT NULL,
user_mobile TEXT NOT NULL,
user_address TEXT NOT NULL);''')
print("Table user Created Successfully")
cur.execute("DROP TABLE if EXISTS Notes")
cur.execute('''CREATE TABLE Notes
(note_id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id INTEGER NOT NULL,
note TEXT NOT NULL);''')
print("Table Notes Created Successfully")
# insert data to admin table
admin_sql="INSERT INTO admin(admin_name,admin_id,admin_uname,admin_password,admin_email) VALUES(?,?,?,?,?)"
cur.execute(admin_sql,('Sharath Raj',1,'admin','admin','[email protected]'))
cur.execute(admin_sql,('Jijo Joseph',2,'admin2','admin@2','[email protected]'))
con.commit()
username='admin123'
password='Admin@123'
cur.execute("SELECT * FROM admin WHERE admin_uname=? AND admin_password=?",(username,password))
for x in cur:
print(x)
con.close()
|
import random
import sqlite3
import datetime
from os import system, name
import time
conn = sqlite3.connect('banking_system.sqlite')
class Customer:
def __init__(self, customer_id = None):
# Constructor:
if customer_id != None:
self.__retrieve_customer_data(customer_id)
elif customer_id == None:
self.get_user_info()
db_customer_flag = self.__dbload_customer_info()
if db_customer_flag:
self.flag = True
def open_account(self, account_type):
self.ledger = []
self.account_type = account_type
self.account_number = self.__generate_account_num()
self.open_date = datetime.date.today()
self.balance = 0.0
db_account_flag = self.__dbload_account_info(account_type)
if not db_account_flag: # Flag will be False if account was not created because account exists
return False
else:
welcome_message(self.first_name, self.account_type, self.account_number)
def __generate_account_num(self):
return random.randrange(1000000, 9999999)
def get_user_info(self):
self.first_name = input("First name: ")
self.middle_name = input("Middle name: ")
self.last_name = input("Last name: ")
self.ssn = input("Social Security Number: ")
self.address = input("Address - please include city/state/zip: ")
self.phone_num = input("Phone number: ")
self.email_address = input("Email address: ")
self.cus_open_date = datetime.date.today()
self.user_name = input("Select a username: ")
while True:
self.password = input("Enter a password: ")
clear()
password_test = input("Enter the password again: ")
if self.password == password_test: break
else: print("The passwords do not match! Please try again.")
def deposit_funds(self, amount):
print()
def withdraw_funds(self, amount):
print()
def update_user_info(self):
print()
def authentication(self):
print()
def get_balance(self, amount, account_type):
current_balance = 0.0
for item in self.ledger.items():
current_balance += item['amount']
return current_balance
def check_funds(self, amount):
if amount >= self.get_balance(amount, self.account_type):
return True
else:
return False
def __dbload_customer_info(self):
# This private method loads the new customer information into the Customer Table in the banking_system.
# database. It links the Customer and Manager Tables by customer_id, loads the user_name and password
# credentials into the Online_Accounts Table, and lastly links the Online_Accounts and Customer Tables
# by the customer_id.
cur = conn.cursor()
cur.execute('''SELECT id FROM Customer WHERE Customer.first_name = ?
AND Customer.ssn = ?''', (self.first_name, self.ssn))
customer_id = cur.fetchone()[0]
if customer_id == self.customer_id:
return True # Return True if customer profile already exists
cur.execute('''INSERT INTO Customer (first_name, middle_name, last_name, ssn,
address, email_address, phone_num, cus_open_date) VALUES (?, ?, ?, ?, ?, ?, ?, ?)
''', (self.first_name, self.middle_name, self.last_name, self.ssn,\
self.address, self.email_address, self.phone_num, self.cus_open_date))
cur.execute('''SELECT id FROM Customer WHERE Customer.first_name = ?
AND Customer.ssn = ?''', (self.first_name, self.ssn))
customer_id = cur.fetchone()[0]
cur.execute('''INSERT OR REPLACE INTO Manager (customer_id)
VALUES (?)''', (customer_id, ))
cur.execute('''INSERT OR REPLACE INTO Online_Accounts (customer_id, user_name, password)
VALUES (?, ?, ?)''', (customer_id, self.user_name, self.password))
conn.commit()
cur.close()
return False # Return flag as False if customer did not exist and load successful
def __dbload_account_info(self, account_type):
# This private method !!!!UFINISHED!!! - Modify this method to be called at any point to update the db...
# Or perhaps another method should take of updating. This one handles creating new records and updating
# the Manager Table keys. At the moment this bank only allows ONE TYPE OF ACCOUNT PER CUSTOMER!
cur = conn.cursor()
# CHECK TO SEE IF AN ACCOUNT ALREADY EXISTS. IF YES THEN RETURN A FLAG.
if account_type.lower() == "checking":
cur.execute('''SELECT Checking.id FROM Checking JOIN Manager JOIN Customer
WHERE Checking.id = Manager.checking_id AND Manager.customer_id = Customer.id
AND Customer.ssn = ?''', (self.ssn, ))
checking_id = cur.fetchone()[0]
if isinstance(checking_id, int):
return False # Return False if cannot proceed because account found
elif account_type.lower() == "savings":
cur.execute('''SELECT Savings.id FROM Savings JOIN Manager JOIN Customer
WHERE Savings.id = Manager.savings_id AND Manager.customer_id = Customer.id
AND Customer.ssn = ?''', (self.ssn,))
savings_id = cur.fetchone()[0]
if isinstance(savings_id, int):
return False # Return False if cannot proceed because account found
# IF YOU HAVE MADE IT THIS FAR THEN AN ACCOUNT DOES NOT EXIST. LET'S LOAD ONE INTO THE DATABASE
cur.execute('''SELECT id FROM Customer WHERE Customer.first_name = ? AND Customer.last_name = ?
AND Customer.ssn == ?''', (self.first_name, self.last_name, self.ssn, ))
customer_id = cur.fetchone()[0]
if account_type.lower() == "checking":
cur.execute('''INSERT OR REPLACE INTO Checking (account_number, balance, ledger, open_date) VALUES
( ?, ?, ?, ?)''', (self.account_number, self.balance, str(self.ledger), self.open_date))
cur.execute('SELECT id FROM Checking WHERE account_number = ? ', (self.account_number, ))
checking_id = cur.fetchone()[0]
cur.execute('''UPDATE Manager SET checking_id = ?
WHERE Manager.customer_id = ?''', (checking_id, customer_id))
elif account_type.lower() == "savings":
cur.execute('''INSERT OR REPLACE INTO Savings (account_number, balance, ledger, open_date) VALUES
( ?, ?, ?, ?)''', (self.account_number, self.balance, str(self.ledger), self.open_date))
cur.execute('SELECT id FROM Savings WHERE account_number = ? ', (self.account_number, ))
savings_id = cur.fetchone()[0]
cur.execute('''UPDATE Manager SET savings_id = ?
WHERE Manager.customer_id= ?''', (savings_id, customer_id))
conn.commit()
cur.close()
return True # Account created = True, new account has been created
def __retrieve_customer_data(self, customer_id):
# This private method retrieves customer data from the Customer Table using the passed in customer_id
cur = conn.cursor()
cur.execute('''SELECT first_name, middle_name, last_name, ssn, address, email_address,
phone_num, cus_open_date FROM Customer WHERE Customer.id = ? ''', (customer_id, ))
customer_info = cur.fetchone()
self.customer_id = customer_id
self.first_name = customer_info[0]
self.middle_name = customer_info[1]
self.last_name = customer_info[2]
self.ssn = customer_info[3]
self.address = customer_info[4]
self.email_address = customer_info[5]
self.phone_num = customer_info[6]
self.cus_open_date = customer_info[7]
cur.close()
def __retrieve_account_data(self, customer_id, account_type):
# This private method retrieves account data from the [account_type] Table using the passed in parameters to
# reference the proper Table and
cur = conn.cursor()
if account_type == 'checking':
cur.execute('''SELECT account_number, balance, ledger FROM Checking JOIN Manager
WHERE Manager.customer_id = ? AND Manager.checking_id = Checking.id''', (customer_id, ))
info = cur.fetchone()
elif account_type == 'savings':
cur.execute('''SELECT account_number, balance, ledger FROM Savings JOIN Manager
WHERE Manager.customer_id = ? AND Manager.savings_id = Savings.id''', (customer_id, ))
info = cur.fetchone()
self.account_number = info[0]
self.balance = info[1]
self.ledger = info[2]
cur.close()
def __del__(self):
print()
##############################################################################
def new_customer_display():
clear()
print(f"Welcome! Let's get you set up with a user profile first.")
customer = Customer() # Instantiate
return customer
def existing_customer_menu(customer):
clear()
print(f"How may we help you today, {customer.first_name}?")
print("1. Open a new account")
print("2. Deposit funds")
print("3. Withdraw funds")
print("4. Transfer funds")
print("5. Check balance")
print("6. Sign Out")
response = input("\nPlease make a selection: ")
return response
def welcome_message(first_name, account_type, account_number):
clear()
print(f"Welcome {first_name}! Please wait while we create your account.")
time.sleep(5)
print(f"\nCongratulations, {first_name}! Your account has been created.")
print(f"Your new {account_type} account number is: {account_number}")
time.sleep(10)
def clear():
if name == 'nt':
_ = system('cls')
else:
_ = system('clear')
def log_in():
while True:
clear()
while True:
clear()
username = input("Enter User name: ")
flag = authenticate_username(username)
if flag:
break
else:
print("Username does not exist! Please try again.")
time.sleep(2)
continue
attempts_left = 5
while True:
clear()
if attempts_left < 3:
print(f"You have {attempts_left} attempts left!")
password = input("Enter Password: ")
customer_id = authenticate_pass_fetch(username, password)
if customer_id is False:
attempts_left -= 1
if attempts_left == 0:
print("Too many failed attempts!")
attempts_left = 5
time.sleep(2)
break
else:
print(f"Invalid credentials! Please try again.")
time.sleep(2)
continue
else:
return customer_id
def authenticate_username(username):
cur = conn.cursor()
cur.execute('SELECT customer_id FROM Online_Accounts WHERE user_name = ?', (username, ))
try:
customer_id = cur.fetchone()[0]
except:
customer_id = False
cur.close()
return str(customer_id).isnumeric()
def authenticate_pass_fetch(username, password):
cur = conn.cursor()
cur.execute('SELECT customer_id FROM Online_Accounts WHERE user_name = ? AND password = ?', (username, password))
try:
customer_id = cur.fetchone()[0]
except:
customer_id = False
cur.close()
return customer_id if str(customer_id).isnumeric() else False
def link_online_account():
print()
def create_online_account(username, password):
cur = conn.cursor()
cur.execute('INSERT OR IGNORE INTO Online_Accounts (user_name, password) VALUES (?, ?)', (username, password))
conn.commit()
cur.close()
return True
|
def writeHDF5(path, image):
""" creates a hdf5 file and writes the mask data
Parameters
----------
path : A string that is the path to the hdf5 file that will be written
image : An image object, from which the data will be stored
Returns
-------
"""
print("not implemented yet")
# TODO:
# - check if path is a correct path
# - create file
# - write data from the quadtree in image.mask in chunks to the file
# - maybe implement Error Messages
|
import random
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def shuffleList(self, head):
if not self.head or not self.head.next:
return head
left = slow = fast = head
fast = fast.next
while fast and fast.next:
slow = slow.next
fast = fast.next.next
right = slow.next
slow.next = None
left_sorted = shuffleList(left)
right_sorted = shuffleList(right)
return merge(left_sorted, right_sorted)
def merge(self, l1, l2):
dummy = ListNode(-1)
prev = dummy
flip = random.randint(l1.val, l2.val)
while l1 or l2:
if l1.val == flip:
prev.next = l1
l1 = l1.next
else:
prev_next = l2
l2 = l2.next
prev = prev.next
prev.next = l1 or l2
return dummy.next
|
##https://docs.python.org/3/library/sqlite3.html
import sqlite3
conn = sqlite3.connect('Users.db')
c = conn.cursor()
class User:
username = None
password = None
creditCard = None
address = None
# default constructor
def __init__(self, username, password):
self.username = username
self.password = password
# a method for getting and setting data members
def getUsername(self):
return self.username
def getPassword(self):
return self.password
def getCreditCard(self):
return self.creditCard
def getAddress(self):
return self.address
def setUsername(self, userName):
self.username = username
return 0
def setPassword(self, password):
self.password = password
def setCreditCard(self, creditCard):
self.userCreditCard = creditCard
def setAddress(self, address):
self.address = address
def addUsertoDatabase(self, userName, password, creditCard, address):
userData = (userName, password, creditCard, address) #place holders for variable substitution. reference sqlite api
c.execute("INSERT INTO Users (username, password, credit, address) VALUES (?, ?, ?, ?)", userData)
# Save (commit) the changes
conn.commit()
print("successfully added to database")
conn.close()
return 0
def login():
pass
def logout():
exit()
def verify(self, userName, password):
userData = (userName, password)
##check if data exists
c.execute("SELECT Username, Password FROM Users WHERE Username=? and Password=?", userData)
exists = c.fetchone() ##returns none if no match
#for row in c:
# print(row)
if exists:
return True
else:
return False
|
#
# Greg's Homework for Essex
# 9/15/2020
#
# #################################################################################################
# ## ##
# ## We define the following classes ##
# ## ##
# ## Card: A single playing card defined with a suit and rank. ##
# ## ##
# ## Deck: A collection of (not neccessarily unique) Cards with the following methods: ##
# ## ##
# ## Shuffle: Randomly rearragne the Deck in place. Does not return a value. ##
# ## ##
# ## Deal: Remove and Return the "top" card from the Deck (the first card in the array). ##
# ## ##
# ## False Shuffle: Looks like you're shuffling, but you're not. For cheaters. ##
# ## ##
# #################################################################################################
# ## Note: We could have used unicode characters but that, we feel, would violate the spirit of ##
# ## the coding assignment. ##
# #################################################################################################
import random
# Let's define a standard 52-card deck. Relax, you can override them if you choose.
SUITS = ('Spades','Hearts','Diamonds','Clubs')
RANKS = ('2','3','4','5','6','7','8','9','10','J','Q','K','A')
class DeckError(Exception):
'''Something to throw is we encounter a problem in the Deck'''
pass
class Card:
'''A single card consisting of suit and rank'''
def __init__(self, suit, rank):
self.suit = suit
self.rank = rank
# a nice way to print the card
def __str__(self):
return f'({self.suit}, {self.rank})'
class Deck:
'''A collection of Cards'''
def __init__(self, suits=SUITS, ranks=RANKS):
self.__cards = []
for suit in suits:
for rank in ranks:
self.__cards.append(Card(suit, rank))
def cards_on_table(self, cards_per_row=13):
'''print out the remaining cards'''
print()
print(f'{len(self.__cards)} left in the deck')
for n in range(1, 1+len(self.__cards)):
print(f'{self.__cards[n-1]}, ', end='')
if ((n)%cards_per_row)==0:
print()
def shuffle(self):
'''Shuffle the deck'''
random.shuffle(self.__cards)
def false_shuffle(self):
'''For the unsavory dealer. Don't be this guy.'''
pass
def deal(self):
'''Return a Card form the top of the deck.
Remove it from the deck'''
if self.__cards:
return self.__cards.pop(0)
else:
# no cards in the deck!
raise DeckError('No Cards in Deck')
# In a production routine I would place test code here. I loke "Nose test" but any
# automated test library would suffice. I do not like manual testing!
if __name__ == '__main__':
deck = Deck()
deck.cards_on_table()
deck.shuffle()
print('Shuffling Deck')
deck.cards_on_table()
card = deck.deal()
print(card)
print('Done')
|
a = []
b = []
c = []
for i in range(0,4,1):
a.append(i+1)
b.append(i+5)
c.append(i+9)
list_2 = [a,b,c]
for i in [0,1,2]:
print("list_1(%d): " % i, list_2[i])
print("-----------------------------------------------------------")
print("list_2: ", list_2)
print("-----------------------------------------------------------")
for i in range(0,len(list_2),1):
for j in range(0,len(list_2[0]),1):
print("list_2[%d][%d] :" %(i,j), "%-4d" % list_2[i][j], end="")
print() |
string = []
while (True):
string = input("문자열 입력 : ")
if( string == "exit"):
break;
else:
print("대소문자 변환 결과 =>", end="")
for i in range(0, len(string), 1):
if ('A' <= string[i] <= 'Z'):
print(string[i].lower(), end="")
elif ( 'a' <= string[i] <= 'z'):
print(string[i].upper(), end="")
else:
print(string[i],end="")
print()
|
n = int(input())
add_n = n + n
multiply_n_by_add_n = add_n * n
subtract_n_from_result = multiply_n_by_add_n - n
division = subtract_n_from_result // n
print(division) |
from sys import argv
script, user_name = argv
prompt = '>'
print "Hi, %s, im the %s script"%(user_name,script)
print "do you like me, %s?" % user_name
like = raw_input(prompt)
#prompt means the terminal will show the things you defined for prompt and than u can input the things.
print "hahaha= %s"% like
#%s will show the content you input but %r will show the character with ''
print """
hahah
this is an attempt
hahaha
how
""" |
#exercise 24
print "let's practise something"
print "You \'d need to know \'about escape with \\ that do \n newlines and \t tabs"
poem = """
\t the lovely world
with logic so firmly planted
cannot discern \n the needs of lovelynor comprhend passion form intuition
and requies an explanation
\t\n\t where there is none.
"""
print "---------"
print poem
print "---------"
def secret_formula(started):
jelly_beans = started * 500
jars = jelly_beans /1000
crates = jars /100
return jelly_beans,jars,crates
start_point = 10000
beans,jars,crates = secret_formula(start_point)
print "with a starting point of : %d" %start_point
print "we'd have %s beans, %s jars, %s crates"% (beans, jars, crates)
print "we can also do that this way : "
print "we'd have %d beans, %d jars, %d crates"% secret_formula(100000) |
import cv2
import numpy as np
img = cv2.imread('lena.jpg', -1) #imread(<file name>,1/0/-1) using for read image
print(img)
cv2.imshow('image', img) #imshow is used to show image in the img and first argument is used to visable a name in the show in title bar
key = cv2.waitKey(0) #waitkey is a method is used to hold the image in specfied time and if the argument is 0 it will waiting forthe closing key
if key == 27:
cv2.destroyAllWindows() # it is used to destroy the window
elif key == ord('s'):
cv2.imwrite('lenacop.png', img) #imwrite is used to save the image |
print("Enter a sentence: ")
seq = list(set(input().split()))
seq.sort()
print("Sorted and no duplicate words")
for word in seq:
print(word,end=" ")
|
class Node:
def __init__(self, data=None, head=None):
self.data = data
class LinkedList():
def __init__(self, head=Node):
self.head = None
def insert(self, data):
new_node = Node(data)
new_node.head = self.head
self.head = new_node
def delete(self, data):
cur = self.head
found = False
prev = None
while cur != None and found is False:
if cur.data == data :
found = True
else:
prev = cur
cur = cur.head
if cur is None:
print "Not Found"
elif prev == None:
self.head = cur.head
else:
prev.head = cur.head
def search(self, data):
temp = self.head
found = False
while temp and found is False:
if temp.data == data :
found = True
else:
temp = temp.head
if found:
print "Found", temp.data
else:
print "Not Found"
def print_list(self):
temp = self.head
while temp:
print temp.data,
print "->",
temp = temp.head
print "None"
list = LinkedList()
list.insert(1)
list.insert(2)
list.print_list() |
def max(x,y):
if x>y:
return x
else:
return y
def min(x,y):
if x<y:
return x
else:
return y
x,y = map(int, raw_input().split())
print "%d"%(max(min(x,y),x)) |
def sum(a,b):
result=0
result=a+b
return result
answer=0
answer=sum(3,4)
print("%d"%answer)
|
def Factorial(n):
if n == 0:
return 1
else:
return n * Factorial(n-1)
for i in range(1,6):
print "%d! = %d"%(i,Factorial(i)) |
def print_max(a,b):
if a > b:
print(a, "is max")
elif a == b:
print(a, "is equal to", b)
else:
print(b, "is max")
print_max(3,4)
x=5
y=7
print_max(x,y)
|
print("Input hour minite second : ",end="")
h,m,s=map(int,input().split())
to_mid=0
to_mid+=h*3600
to_mid+=m*60
to_mid+=s
print("now midnight from %d second after"%(to_mid))
|
class Node:
def __init__(self, data=None, next=None):
self.data = data
self.head = next
def print_list(self):
temp = self.head
while temp:
print temp.data,
print "->",
temp = temp.next
print "None"
def insert(self, data):
new_node = Node(data)
new_node.next = self.head
self.head = new_node
def delete(self, data):
print "delete ",data
cur = self.head
found = False
prev = None
while cur != None and found is False:
if cur.data == data:
found = True
else:
prev = cur
cur = cur.next
if cur is None:
print "Not Found"
elif prev == None:
self.head = cur.next
else:
prev.next = cur.next
def search(self, data):
temp = self.head
found = False
while temp and found is False:
if temp.data == data:
found = True
else:
temp = temp.next
if found:
print "found", temp.data
else:
print "Not Found"
list = Node()
list.insert(1)
list.insert(2)
list.insert(3)
list.print_list()
|
ch='a'
while True:
print("Input character(if input=q is exit) : ",end="")
ch=input()
if(ch=='q'):
break
print("loop exit")
|
a=0
b=0
c=0
for i in range(0,3):
if(a==0):
print("Input : ",end="")
a=int(input())
continue
if(b==0):
print("Input : ",end="")
b=int(input())
continue
if(c==0):
print("Input : ",end="")
c=int(input())
continue
if(a>b):
if(a>c):
print("result : %d"%(a))
elif(b>c):
print("result : %d"%(b))
elif(c>a):
print("result : %d"%(c))
if(a==b):
if(a>c):
print("a and b is same result %d"%(a))
else:
print("a and b is same result %d"%(c))
if(b==c):
if(b>a):
print("b and c is same result %d"%(b))
else:
print("b and c is same result %d"%(c))
|
def Recursive(num):
if num <= 0:
return
print "Recursive call! %d"%(num)
Recursive(num-1)
Recursive(3) |
print("Input Two Integer : ",end="")
a,b=map(int,input().split())
print("Sum : %d + %d = %d"%(a,b,a+b))
print("Sub : %d - %d = %d"%(a,b,a-b))
|
# python3.7.11
# algorithm function (takes only ideal scenario into consideration):
def find_pivot(array):
# array must have at least 3 elements:
if len(array) < 3:
return -1
# solution for an array with just 3 elements:
if len(array) == 3:
return {'index': 1, 'value': array[1], 'sum': array[0]}
# Initialization of 2 pointers and 2 sums for each side of the array:
left_idx = 0
left_count = array[left_idx]
right_idx = len(array) - 1
right_count = array[right_idx]
# Loop to iterate len(array) - 3 times (left initialized + right initialized + pivot position)
for i in range(len(array) - 3):
if (right_count + array[right_idx - 1]) > (left_count + array[left_idx + 1]):
left_idx += 1
left_count += array[left_idx]
else:
right_idx -= 1
right_count += array[right_idx]
"""
Return of useful information:
index: the position of the array where the pivot is located
value: the value of the pivot
sum: the total sum of each side of the array
"""
return {'index': left_idx + 1, 'value': array[left_idx + 1], 'sum': left_count}
# main function:
def main():
print(find_pivot([1, 2, 1])) # {'index': 1, 'value': 2, 'sum': 1}
print(find_pivot([1, 2, 6, 3])) # {'index': 2, 'value': 6, 'sum': 3}
print(find_pivot([2, 1, 2, 1, 3, 2])) # {'index': 3, 'value': 1, 'sum': 5}
print(find_pivot([2, 2, 2, 2, 2, 2, 2, 6, 10, 3, 1, 5, 2, 5, 3, 1, 3, 14]))
# {'index': 10, 'value': 1, 'sum': 33}
# Entry point:
if __name__ == '__main__':
main()
|
# -*- coding: utf-8 -*-
"""
Created on 17-03-2019 at 02:59 PM
@author: Vivek
"""
class Employee:
# Constructor
def __init__(self, name, ID, salary):
self.empName = name
self.empID = ID
self.empSalary = salary
# Defines behaviour when called using print() or str()
def __str__(self):
return 'Employee(' + self.empName + ',' + self.empID + ',' + str(self.empSalary) + ')'
# Defines behaviour when called with repr()
def __repr__(self):
return '[' + self.empID + '] - ' + self.empName
# Defines behaviour when called with '+' operator
def __add__(self, secondObject):
return (self.empSalary+secondObject.empSalary)
if __name__ == '__main__':
objAlice = Employee('Alice','EMP001',10000)
print(objAlice)
print(repr(objAlice))
print('')
objBob = Employee('Bob', 'EMP002', 5000)
print(objBob)
print(repr(objBob))
print('\nSum:',objAlice+objBob)
|
T = int(input())
for i in range(T):
n = int(input())
if n%2 == 0:
print("%d is even"%n)
else :
print("%d is odd"%n)
|
while True:
a,b,c = map(int,input().split())
if a+b+c == 0:
break
list=[a,b,c]
if sum(list) <= max(list)*2 :
print('Invalid')
elif a==b==c :
print('Equilateral')
elif a==b or a==c or b==c :
print('Isosceles')
else :
print('Scalene')
|
p=1
while(p==1):
def isPalindrome(s):
return s==s[::-1]
s = input("Enter the string: ")
ans = isPalindrome(s)
if ans:
print("It is a palindrome")
else:
print("Not a palindrome")
flag=0
while(flag == 0):
p = int(input("Enter 1 to continue and 0 to exit : "))
if(p!=1 and p!=0):
print("Invalid entry")
if(p==1 or p==0):
flag=1 |
# Generate the rigid body transformation matrix from rotation matrix and
# translation matrix using homogeneous representation.
#-----------------------------------------------
import numpy as np
def trans(R,p):
# Dimension Check
assert (R.shape == (3,3) and p.shape ==(3,1)), "This function requires 3*3 matrix and a 3*1 matrix as input"
# Det Check
detR = np.linalg.det(R)
assert (detR > 0.999 and detR < 1.001), "The determinant of R should be 1, please check your rotation matrix"
T = np.concatenate((np.concatenate((R, p), axis=1),np.array([[0,0,0,1]])), axis = 0)
return T |
#Take user input, create a Python list, find a value in the list, and if it is present, replace it with 200. Only update the first occurrence of a value
a=float(input("enter first no:"))
b=float(input("enter second no:"))
c=float(input("enter third no:"))
list1=[a,b,c]
print(list1)
d=float(input("enter a value to find and replace with 200:"))
find=list1.index(d)
list1[find]=200
print(list1)
|
"""exorcise 2 26/2/20 mean counter"""
number = []
keep_asking = True
while keep_asking == True:
num = int(input("Enter a number :"))
if (num) == -1 :
keep_asking = False
else:
number.append (num)
for i in range(len(number)):
print(number[i])
print("the sum of those numbers are",sum (number))
|
"""19/2/2020 trademe code"""
item = input("what would u like to sell?: ")
reserve_price = int(input("what would you like the item to go for?: "))
highest_price = 0
highest_name = "Jesus Jimminy Christmas"
reserve_met = 0
auction_run = True
while auction_run == True :
name = input("please enter your name: ")
price = int(input("please enter your bid: "))
if highest_price >= reserve_price and reserve_met == 0 :
print("reserve has been met")
reserve_met = 1
elif price > highest_price :
highest_price = price
highest_name = name
print("The highest bid so far is {} at {}".format(highest_name,highest_price))
else:
print("That is not high enough.")
print("The highest bid so far is {} at {}".format(highest_name,highest_price))
|
# Learning Python's numpy library via the official documentation and Justin Johnson's Tutorial http://cs231n.github.io/python-numpy-tutorial/
import numpy as np
matrix1 = np.eye(3)
matrix2 = np.array([[2,0,0], [0,2,0],[0,0,2]], dtype=np.float64)
# adding matrices - the two produce the same thing
print(matrix2 + matrix1)
print(np.add(matrix1, matrix2))
|
import turtle,math,time
n=200
count=0
for a in range ((n+2)/3,(n-1)/2+1):
for b in range (n+2)/3,(n-1)/2+1):
for c in range (n+2)/3,(n-1)/2+1):
if b+c>a:
count=count+1
#print (a,b,c)
print (count)
#3 sides
#a=5
#b=4
#c=3
#calcuate the degrees
abDegree=math.degrees(math.acos((a**2 + b**2 - c**2) / (2 * a * b)))
bcDegree=math.degrees(math.acos((b**2 + c**2 - a**2) / (2 * b * c)))
acDegree=math.degrees(math.acos((a**2 + c**2 - b**2) / (2 * a * c)))
print (abDegree,bcDegree,acDegree)
# 调用turtle中的Pen函数创建画布
t = turtle.Pen()
t.down()
# Draw triangle
t.forward(a*50)
t.right(180-abDegree)
t.forward(b*50)
t.right(180-bcDegree)
t.forward(c*50)
|
import sys
# Print all the arguments
print ("Arguments list:{}", str(sys.argv))
#Print only 2nd argument. Catch exception if there is no second argument
try:
print (sys.argv[2])
except IndexError:
print ("Second argument not found")
else:
print ("Done")
|
# Define a variable (add) that represents a statement that can take arguments (n, m).
# This variable is linked to the statement n + m using the lambda keyword which represents a lambda function
add = lambda n, m: n + m
subtract = lambda n, m: n - m
# Call the lambda function using the variable name as if that is a function and pass the arguments to it
print(add (5, 3))
print(subtract(5, 3)) |
# -*- coding: utf-8 -*-
"""
Created on Sun Dec 8 12:54:34 2019
@author: Abhishek
"""
n1=int(input("number1"))
if(n1%6==0):
print("window")
elif(n1%6==1):
print("window")
elif(n1%6==2):
print("middle")
elif(n1%6==5):
print("middle")
elif(n1%6==3):
print("aisle")
elif(n1%6==4):
print("aisle")
print(n1+6)
|
import urllib.request
import zipfile
import requests
def download_geotiff(directory, file_name):
"""
This function downloads the GeoTiff file according to file_name.
The file name should be defined in Topodata.py
Ex:
coordinates = [-00.00, -00.00, -00.00, -00.00]
file_name = Topodata.file_names_topodata(coordinates)
directory = '../folder'
Download.download_geotiff(file_name, directory)
:param file_name: String
Name of the file that must be downloaded.
It is according to the data model of Topodata.
Ex: 22S48_ZN
latitude + hemisphere + longitude +
+ '_' or '5' + type of data
:param directory: folder that must be used to save the
downloaded file.
"""
# In Brazil, geomorphometric data is on the INPE website (topodata)
url = "http://www.dsr.inpe.br/topodata/data/geotiff/" + file_name
with urllib.request.urlopen(url) as dl_file:
with open(directory + file_name, 'wb') as out_file:
out_file.write(dl_file.read())
with zipfile.ZipFile(directory + file_name, 'r') as zip_ref:
zip_ref.extractall(directory)
def download_osm(coordinates_osm, file_name):
"""
:param coordinates_osm Sting
bbox=left,bottom,right,top
left: minLon
bottom: minLat
right: maxLon
top: maxLat
:param file_name: String
Name of the file that must be downloaded.
Ex: 'map.osm' or 'map'
"""
name_len = len(file_name)
file_extension = file_name[name_len-4] + file_name[name_len-3] + file_name[name_len-2] + file_name[name_len-1]
print("Downloading: ", coordinates_osm)
url = "http://overpass.openstreetmap.ru/cgi/xapi_meta?*[bbox={}]".format(coordinates_osm)
r = requests.get(url, allow_redirects=True)
if file_extension == '.osm':
with open(file_name, 'w') as fd:
fd.write(r.text)
else:
with open(file_name + '.osm', 'w') as fd:
fd.write(r.text)
# print("Downloaded File:", file_name, "\nCoordinates", coordinates_osm)
if __name__ == "__main__":
coordinates_osm = str(-47.246313) + "," + str(-23.0612161) + "," + str(-47.239999) + "," + str(-23.0609999)
# name_file = "map.osm"
# directory = '../geography/'
#download_osm(coordinates_osm, directory + name_file)
name_file = "01S495ZN"
directory = '../data/maps/'
download_geotiff(directory, name_file) |
semesters = ['Fall', 'Spring']
# Add values
semesters.append('Summer')
semesters.append('Spring')
print(semesters) # ['Fall', 'Spring', 'Summer', 'Spring']
# Remove values
semesters.remove('Spring')
print(semesters) # ['Fall', 'Summer', 'Spring']
# Access any value using it's index
first_item_in_list = semesters[0]
print(first_item_in_list) # Fall |
# Python program implementing single-byte XOR cipher
# English frequency of letters
english_freq = [
8.167, 1.492, 2.782, 4.253, 12.702, 2.228, 2.015, 6.094, 6.966, # A-I
0.153, 0.772, 4.025, 2.406, 6.749, 7.507, 1.929, 0.095, 5.987, # J-R
6.327, 9.056, 2.758, 0.978, 2.360, 0.150, 1.974, 0.074 # S-Z
]
def xor_encrypt(plaintext: str, key: int) -> str:
""" Encrypt a plaintext into a hex-encoded ciphertext.
Args:
plaintext (str): The plaintext to encrypt
key (int): The single-byte key
Returns:
str: The hex-encoded ciphertext
"""
return bytes(ord(c) ^ key for c in plaintext).hex()
def xor_decrypt(ciphertext: str, key: int) -> str:
""" Decrypt a hex-encoded ciphertext into plaintext.
Args:
ciphertext (str): The hex-encoded ciphertext
key (int): The single-byte key
Returns:
str: The plaintext
"""
return ''.join(chr(b ^ key) for b in bytes.fromhex(ciphertext))
def count_character_frequency(plaintext: str) -> list:
""" Count character frequency in a plaintext.
Args:
plaintext (str): The plaintext
Returns:
list: The frequency of each character
"""
occ = [0] * 26
for c in plaintext.lower():
if c >= 'a' and c <= 'z':
occ[ord(c) - ord('a')] = occ[ord(c) - ord('a')] + 1
return [o * 100 / len(plaintext) for o in occ]
def score_character_frequency(plaintext: str) -> float:
""" Score a plaintext based on character frequency.
Args:
plaintext (str): The plaintext
Returns:
float: The score
"""
plaintext_freq = count_character_frequency(plaintext)
score = 0
for observed, expected in zip(plaintext_freq, english_freq):
score = score + (observed - expected) ** 2
return score
def brute_force_xor_decrypt(ciphertext: str) -> tuple:
""" Brute force the decryption of a hex-encoded ciphertext into plaintext.
Args:
ciphertext (str): The hex-encoded ciphertext
Returns:
tuple(int, str): The key and the plaintext
"""
key, plaintext = None, None
score = float('Inf')
for k in range(256):
t = xor_decrypt(ciphertext, k)
s = score_character_frequency(t)
if s < score:
key, plaintext, score = k, t, s
return (key, plaintext)
def main():
""" Driver program """
# Hex-encoded ciphertext
ciphertext = "03246a2938333a3e252d382b3a2233666a3e222f6a25242f673e23272f6a3a2b2e6a62051e1a636a23396a2b246a2f242938333a3e2325246a3e2f292224233b3f2f6a3e222b3e6a292b2424253e6a282f6a29382b29212f2e666a283f3e6a382f3b3f23382f396a3e222f6a3f392f6a252c6a2b6a25242f673e23272f6a3a382f6739222b382f2e6a212f336a3e222f6a392b272f6a3923302f6a2b39666a25386a2625242d2f386a3e222b24666a3e222f6a272f39392b2d2f6a282f23242d6a392f243e646a03246a3e2223396a3e2f292224233b3f2f666a2b6a3a262b23243e2f323e6a23396a3a2b23382f2e6a3d233e226a2b6a382b242e25276a392f29382f3e6a212f336a622b2639256a382f2c2f38382f2e6a3e256a2b396a2b6a25242f673e23272f6a3a2b2e6364"
# Brute force decryption
key, plaintext = brute_force_xor_decrypt(ciphertext)
print('Key: {}'.format(key))
print('Plaintext:\n{}'.format(plaintext))
if __name__=='__main__':
main()
|
# Author : moranzcw
# Date : 2016-04-13
# This script is used to generate a list of links from leetcode.com
import os
import re
from urllib import request
from bs4 import BeautifulSoup
response = request.urlopen('https://leetcode.com/problemset/algorithms/')
html_content = response.read()
soup = BeautifulSoup(html_content, "html.parser")
problem_tag_list = soup.find_all('tr')
for each in problem_tag_list:
problem_num_tag = each.find('td',text = re.compile("^\d+$"))
if problem_num_tag:
problem_num = problem_num_tag.get_text()
else:
continue
problem_tag = each.find('a',href = True)
if problem_tag:
problem_title = problem_tag.get_text()
problem_link = "https://leetcode.com/" + problem_tag['href']
else:
continue
print("| " + problem_num + " | [" + problem_title + "](" + problem_link + ") |")
|
#1. Você tem uma lista de número: [6,7,4,7,8,4,2,5,7,'hum', 'dois']. A ideia do exercício é tirar a média de todos os valores contidos na lista, porém para fazer o cálculo precisa remover as strings.
print("Bem-vindo")
#Exercicio 1
total = 0
index = 0
x = [6,7,4,7,8,4,2,5,7,'hum', 'dois']
for valor in x:
if type(valor) == int:
index = index + 1
total = total + valor
else:
continue
print(total/index)
|
"""Homework file for my students to have fun with some algorithms! """
def find_greatest_number(incoming_list: list):
"""
Required parameter, incoming_list, should be a list.
Find the largest number in the list.
"""
return max(incoming_list)
def find_least_number(incoming_list: list):
"""
Required parameter, incoming_list, should be a list.
Find the smallest/least number in the list.
"""
return min(incoming_list)
def add_list_numbers(incoming_list: list):
"""
Required parameter, incoming_list, should be a list.
Add all the values together and return it.
"""
return sum(incoming_list)
def longest_value_key(incoming_dict: dict):
"""
Required parameter, incoming_dict, should be a dict.
Find the KEY that has a value with the highest length, use the len() function
"""
longest_value = max(incoming_dict.values(), key=len)
for key, value in incoming_dict.items():
if longest_value == value:
longest_key = key
print(longest_key)
|
'''
Written by Cham K.
June 16th 2015
'''
from sequence_manipulation import nucleotide_count
def nucleotide_composition(sequence, base):
''' (str, str) -> (float)
Returns the amount (percentage rounded to 2 decimal places) of a specified nitrogenous base (A, T, C, or G) in a DNA sequence.
Can process upper-case and lower-case sequence input with or without whitespace characters.
>>>nucleotide_composition('G A T A C C', 'A')
33.33
>>>nucleotide_composition('gaataaccgatac', 'T')
15.38
'''
module = nucleotide_count
A = module.nucleotide_count(sequence, 'A')
T = module.nucleotide_count(sequence, 'T')
C = module.nucleotide_count(sequence, 'C')
G = module.nucleotide_count(sequence, 'G')
total_bases = A + T + C + G
if base == 'A':
return float("%.2f" % ((A/total_bases)*100))
if base == 'T':
return float("%.2f" % ((T/total_bases)*100))
if base == 'C':
return float("%.2f" % ((C/total_bases)*100))
if base == 'G':
return float("%.2f" % ((G/total_bases)*100))
else:
return "ERROR: Null or invalid input recieved for base argument. Base value can be 'A', 'T', 'C', or 'G'."
def total_nucleotide_composition(sequence):
''' (str, str) -> (dict)
Returns a dictionary containing percent composition values (rounded to 2 decimal places) of all bases (A, T, C, and G) in a DNA sequence.
Can process upper-case and lower-case sequence input with or without whitespace characters.
>>>total_nucleotide_composition('G A T A C C')
{'G': 16.67, 'C': 33.33, 'T': 16.67, 'A': 33.33}
>>>total_nucleotide_composition('gaataaccgatac')
{'A':46.15, 'T':15.38, 'C':15.38, 'G':15.38}
'''
return {'A':nucleotide_composition(sequence, 'A'), 'T':nucleotide_composition(sequence, 'T'), 'C':nucleotide_composition(sequence, 'C'), 'G':nucleotide_composition(sequence, 'G')}
|
"""
The approach here is to keep another array and iterate over the given input array. at each iteration
store the element value -1 indexed place as 1 in the new formed array. finally iterate over the new formed
array and if there is no 1 found in the new formed array then the element is not there in the main array.
Leetcode - running
Time complexity O(N)
Space O(N)
"""
def findDisappearedNumbers(self, nums):
res=[]
find=[0]*len(nums)
for i in range(len(nums)):
find[nums[i]-1]=1
for i in range(len(find)):
if not find[i]:
res.append(i+1)
return res |
# coding: utf-8
##Caesar暗号を生成/解読するスクリプト用のアルファベットリストの場合は冗長##
#alphabetList = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"]
##ASCIIコードを使用してアルファベットを生成する方法がスマート
#小文字が97から123までのxrange 大文字が65から91までのxrange
#alphabetTable = [chr(i) for i in range(ord('A'), ord('Z')+1)]
#alphabetTable = [chr(i) for i in xrange(97,123)]
alphabetTable = [chr(i) for i in xrange(65,91)]
print alphabetTable
|
# ask the user for a filename from which it will take its input
# open the file with that filename and reads an integer at the beginning of the file that is the number of lines that follow
# open a file called output.txt
# reads in the strings of the input, one at a time, and writes to the output file either "accept" or "reject"
# depending on whether the program is in error state at the end of each string
# closes both files
class file():
def read_letters(self, file):
self.state = 1
num = file.readline().strip()
num_of_lines = int(num)
print num_of_lines
#While there are still lines to be read, read each letter in each line and
#correlate it to a state.
while num_of_lines != 0:
nextline = file.readline().strip()
print nextline
for x in nextline:
if self.state == 1:
if x.isalpha():
self.state = 3
elif x.isdigit():
self.state = 2
else:
error()
elif self.state == 2:
if x.isalpha():
self.state = 2
elif x.isdigit():
self.state = 2
else:
error()
elif self.state == 3:
if x.isalpha() or x.isdigit():
self.state = 3
else:
error()
num_of_lines = num_of_lines - 1
#If all the lines have been read, open a file and write the final
#accept or reject state to the file.
if num_of_lines == 0:
if self.state == 3:
print "Accept"
out = open("output.txt", "w")
out.write("Accept")
elif self.state == 2 or self.state == 1:
print "Reject"
out = open("output.txt", "w")
out.write("Reject")
else:
print "Final State Error"
def error():
print "Error, program will exit until the programmer gets her life together."
def main():
#works when providing a file, not when obtaining file name from user though
#FIX THIS
#file = raw_input("Please enter the filename:")
#if file == "input.txt" or file == "anotherinput.txt":
# name = open(file, "r")
# file().read_letters(name)
#else:
# print "oops, try again."
##################################
# I struggled to implement the input section, which logically seems right,
# but I'm struggling with syntax. I will try to fix, however, the state
# logic is correct, and can be tested by commenting and uncommmenting
# each of these 3 individual files provided below.
##################################
#name = open("input.txt", "r") #Accept
#name = open("anotherinput.txt", "r") #Accept
name = open("lastinput.txt", "r") #Reject
file().read_letters(name)
main() |
from stack_that import stack_that
import sys
class cave_runner(object):
#do I want to make a dictionary...???
def __init__(self):
self.traversed = stack_that()
self.choices = []
self.hat = []
self.size_x = 0
self.size_y = 0
self.row = 0
self.col = 0
self.found = 0
self.new_pos = []
#This stackoverflow helped me accomplish my for loop, before I was having
#issues where iterating through a for loop could possibly delete information.
#http://stackoverflow.com/questions/3277503/python-read-file-line-by-line-into-array
# wenda = raw_input("Please enter the name of the text file you wish to use:")
with open('fourbysix.txt', "r") as waldos:
for i in waldos:
self.hat.append(i.strip())
print self.hat
# def set_locale(self):
# new_pos = [self.row, self.col]
# self.traversed.push([new_pos])
# print self.traversed.top()
def check_locale(self,x,y):
maze = self.hat
#Base case
x = self.row
y = self.col
# if self.col > self.size_y or self.row > self.size_x:
# print("size error")
if maze[x][y] == "T":
self.my_precious()
elif maze[x][y] == "W":
print("stuck on a wall?")
elif maze[x][y] == 'M':
maze[x][y] = 'V'
if self.check_locale(self.row+1, self.col) == '.': #North
maze[x][y] = 'V'
elif self.check_locale(self.row, self.col+1) == '.': #East
maze[x][y] = 'V'
elif self.check_locale(self.row-1, self.col) == '.': #South
maze[x][y] = 'V'
elif self.check_locale(self.row, self.col-1) == '.': #West
maze[x][y] = 'V'
elif maze[x][y] == '.':
maze[x][y] = 'V'
if self.check_locale(self.row+1, self.col) == '.': #North
maze[x][y] = 'V'
elif self.check_locale(self.row, self.col+1) == '.': #East
maze[x][y] = 'V'
elif self.check_locale(self.row-1, self.col) == '.': #South
maze[x][y] = 'V'
elif self.check_locale(self.row, self.col-1) == '.': #West
maze[x][y] = 'V'
else:
print('beg for mercy')
else:
self.found = 1
for i in self.hat[0:]:
get_out = open('solved.txt', 'a')
get_out.write(i+"/n")
get_out.close()
print ("fin")
# r = self.row+1
# c = self.col
# if self.hat[r][c] == '.':
# self.hat[r][c].write('O')
# self.step_N()
# elif self.hat[r][c] == 'T':
# self.hat[r][c].write('C')
# self.my_precious()
# else:
# r = self.row
# c = self.col+1
# if self.hat[r][c] == '.':
# self.hat[r][c].write('O')
# self.step_N()
# elif self.hat[r][c] == 'T':
# self.hat[r][c].write('C')
# self.my_precious()
# else:
# r = self.row-1
# c = self.col
# if self.hat[r][c] == '.':
# self.hat[r][c].write('O')
# self.step_N()
# elif self.hat[r][c] == 'T':
# self.hat[r][c].write('C')
# self.my_precious()
# else:
# r = self.row
# c = self.col-1
# if self.hat[r][c] == '.':
# self.hat[r][c].write('O')
# self.step_N()
# elif self.hat[r][c] == 'T':
# self.hat[r][c].write('C')
# self.my_precious()
# else:
# print('tucansam!')
# self.last_choice()
# E = self.row, self.col+1
# S = self.row-1, self.col
# W = self.row, self.col-1
# print("N:" + N)
# print("E:" + E)
# print("S:" + S)
# print("W:" + W)
# if N == ".":
# print(".")
# self.step_N()
# if E == "T":
# self.my_precious()
# elif E == ".":
# print(".")
# self.step_E()
# elif E == "T":
# self.my_precious()
# elif S == ".":
# print(".")
# self.step_S()
# elif S == "T":
# self.my_precious()
# elif W == ".":
# print(".")
# self.step_W()
# elif W == "T":
# self.my_precious()
# else:
# self.last_choice()
# sys.exit
def last_choice(self):
new_pos = []
new_pos.append(self.traversed.pop())
self.row = new_pos[0:]
self.col = new_pos[:1]
def find_entrance(self):
for r in range(len(self.hat)):
# print(r)
for c in range(len(self.hat[r])):
# print (c)
if self.hat[r][c] == 'M':
self.row = r
self.col = c
self.choices.append([r,c])
print self.choices
# def step_N(self):
# r = self.row+1
# c = self.col
# self.choices.append([r,c])
# def step_E(self):
# new_pos = self.row, self.col+1
# self[new_pos] = "M"
# def step_S(self):
# new_pos = self.row-1, self.col
# self[new_pos] = "M"
# def step_W(self):
# new_pos = self.col-1, self.col
# self[new_pos] = "M"
def my_precious(self):
new_pos = self.row, self.col
self[new_pos] = "C"
print("My Precious")
# def the_visitor(self):
# #set what you've already visited to something else so you can tell.
# #maybe a V?
# #get self, set self to V
# position = self.row, self.col
# self.traversed.append([position])
# self[position] = "V"
# print self[position]
|
#------------------------------------------------------------------------------#
# Name: Rebeccah Hunter
# File: BinarySearchTree.py
# Purpose: CSC 236 Example of creating and using binary search trees in Python.
#
# Shows how to use a tree to store information, and in particular how to
# search through a binary search tree. This program both creates a binary
# search tree given an array, searches the tree given a target value, and
# deletes the tree before the program ends.
#
#------------------------------------------------------------------------------#
import sys
from Node import Node
class BinaryTree():
"""
A class created with a method to create a binary tree, and another to search
the binary tree after it's created.
"""
def __init__(self):
self.node = Node()
def populate_from_array(self, current_node, given_array, arraySize):
"""
Takes a current node, an array, and the array size and creates a binary tree.
This section of code was my single biggest issue in creating this program.
"""
#--------------------------------------------------------------------------#
#-------------This section of code is originally from A16------------------#
#--------------------------------------------------------------------------#
if current_node == None:
return ("")
if current_node.left != None:
print('error' and current_node.left)
if current_node.right != None:
print("error" and current_node.right)
if arraySize == 1:
return arraySize
new_node = Node()
new_node.set_value(current_node.left)
new_node.set_count(current_node.left)
left_array = []
for i in range(arraySize/2):
left_array.append(given_array[i])
print(str(given_array[i]))
self.populate_from_array(current_node.left, left_array, arraySize)
del left_array[:]
right_size = arraySize/2 + 1
#print right_size
if right_size == 0:
return arraySize
newer_node = Node()
newer_node.set_value(current_node.right)
new_node.set_count(current_node.left)
right_array = []
for i in range(right_size):
right_array.append(given_array[(right_size/2)+i])
print(str(right_array[i]))
self.populate_from_array(current_node.right, right_array, arraySize)
del right_array[:]
left_size = arraySize/2 - 1
#print left_size
if left_size == 0:
return arraySize
return current_node
def binary_searchT(self, itemSought, current_node):
"""
A brief search through a binary tree.
"""
if itemSought < current_node:
if current_node.left is None:
return None, None
return current_node.left
elif itemSought > current_node:
if current_node.right is None:
return None, None
return current_node.right
else:
return current_node
|
################################################################################
# Purpose: to create a fun and rewarding virtual pet for a programmer to interact with.
# Perfect for the person who is allergic to everything and can't have real pets...
# Author: Rebeccah Hunter
# Acknowledgments: Berea College Computer Science Department and Dr. Mario Nakazawa
################################################################################
from BasicPet import BasicPet
from petSurprise import petSurprise
def begin(Seymour):
'''This function is the starting section of the virtual pet game.
It should utilise the user's input to move on the the next part of game play.
'''
user_input = raw_input("Hello, would you like to care for a virtual pet? \nPlease type y or n to take on this non-existant pet named Seymour")
user_input = user_input.lower()
if user_input == "y":
print ("Great! You must care for Seymour in 3 ways. 1 is to give your pet sustenance.\n2 is to do activity and boost metabolism.3 is to love your pet.\nYou may enter n to leave:")
elif user_input == "n":
print ("you cold hearted, neglectful individual. How could you abandon \nthis tiny fake virtual robot-pet? You're a monster!")
Seymour.dragonAttack()
else:
print ("I'm so sorry, something went wrong. Perhaps your pet was eaten\
by a dragon, or perhaps you were..")
def care():
'''A function to determines the user's care choice for their pet.
'''
caring = raw_input("Please enter 1, 2, or 3 to care for your pet.")
return caring
def continueCare(Audrey, Seymour):
'''A function to determine whether the gameplay continues or not.
'''
yes_check = raw_input("would you like to continue to care for your pet?\nEnter y or n: ")
check = yes_check.lower()
return check
def main():
'''Audrey is an instance of BasicPet and Seymour the instance of a dragon attack.
'''
Seymour = petSurprise()
Audrey = BasicPet()
begin(Seymour)
checked = continueCare(Audrey, Seymour)
while checked == "y":
caring = care()
if caring == "1":
Audrey.feedMe()
Audrey.checkPet()
elif caring == "2":
Audrey.walkMe()
Audrey.checkPet()
elif caring == "3":
Audrey.loveMe()
Audrey.checkPet()
elif caring == "n":
Audrey.neglectMe()
Audrey.checkPet()
if Audrey.neglect == 0:
Seymour.dragonAttack()
else:
print "Feed Me!"
checked = continueCare(Audrey, Seymour)
if checked == "n":
Seymour.dragonAttack()
else:
checked = continueCare(Audrey, Seymour)
main() |
"""
Author: Max Martinez Ruts
Date: October 2019
Description:
Creation of AVL data structure with search, insertion and deletion implementations
"""
class AVL:
def __init__(self):
self.root = None
"""
Description:
Check for unbalances comparing left and right subtrees recursively by following a bottom-up path on the tree
Complexity
O(lg n) Since each iteration has O(1) and n of iterations is O(levels) = O(lg n)
"""
def balance(self, root):
x = root
lh = self.get_k(root.left)
rh = self.get_k(root.right)
print('checking balance on', root.value, lh, rh)
if abs(lh - rh) > 1:
if lh > rh:
llh = self.get_k(root.left.left)
lrh = self.get_k(root.left.right)
if llh >= lrh:
y = root.left
self.r_left_left(x, y)
else:
z = root.left
y = root.left.right
self.r_left_right(x, y, z)
else:
rlh = self.get_k(root.right.left)
rrh = self.get_k(root.right.right)
if rlh > rrh:
z = root.right
y = root.right.left
self.r_right_left(x, y, z)
else:
y = root.right
self.r_right_right(x, y)
if root.parent == None:
return
else:
self.balance(root.parent)
# Helper to get k in case node does not exist
def get_k(self, node):
if node == None:
return 0
else:
return node.k
"""
Description:
Add child and update pointer of parents
"""
def add_child(self, parent, child, side):
if parent != None:
print('Adding ', child.value, ' to ', parent.value)
if side == 'left':
parent.left = child
else:
parent.right = child
child.parent = parent
print('node', parent.value, 'has new child', child.value, 'on', side)
self.update_ks_up(child)
"""
Description:
Update ks following a bottom-up approach
Complexity: O(lg n)
Since O(levels) = O(lg n)
"""
def update_ks_up(self, root):
# Iterative method, could also be recursive
while root != None:
root.k = max(self.get_k(root.left), self.get_k(root.right)) + 1
# Update root of tree
if root.parent == None:
self.root = root
print('root is ', root.value)
root = root.parent
"""
Description:
Insert a new node to the tree
Complexity: O(lg n)
Since it first has to go down to a leaf O(lg n) and then balance the tree, also O(lg n). The search is done recursively by following a bottom-up approach
"""
def insert(self, root, value):
try:
print('inserting ', value, 'to', root.value)
except:
print('inserting ', value, 'to', 'empty')
# If tree is empty
if root == None:
child = self.Node(value)
self.add_child(None, child, None)
self.balance(child)
return child
# If root is leave
elif root.left == None and root.right == None:
child = self.Node(value)
if value < root.value:
self.add_child(root, child, 'left')
else:
self.add_child(root, child, 'right')
self.balance(child)
return child
# If value is on left
elif value < root.value:
# If left child exists -> search on left child
if root.left != None:
self.insert(root.left, value)
# Otherwise generate new left child
else:
child = self.Node(value)
self.add_child(root, child, 'left')
self.balance(child)
return child
# If value is on right
else:
print('go right')
# If right child exists -> search on right child
if root.right != None:
self.insert(root.right, value)
# Otherwise generate new right child
else:
child = self.Node(value)
self.add_child(root, child, 'right')
self.balance(child)
return child
"""
Description:
Remove node given a value by searching the node containing the value, removing by updating pointers and finally balancing
Complexity: O(lg n)
Since search is O(lg n), updating pointers is O(1) and balancing is O(lg n)
"""
def remove(self, value):
node = self.search(self.root, value)
# Case 1: Node is leaf
if node.left == None and node.right == None:
print('case 1', node.value)
if node.parent != None:
if node.parent.left == node:
node.parent.left = None
if node.parent.right == node:
node.parent.right = None
self.update_ks_up(node.parent)
self.balance(node.parent)
del node
# Case 2: Node has left child only
elif node.left != None and node.right == None:
if node.parent != None:
if node.parent.left == node:
node.parent.left = node.left
if node.parent.right == node:
node.parent.right = node.left
node.left.parent = node.parent
self.update_ks_up(node.left)
self.balance(node.left)
del node
# Case 3: Node has right child only
elif node.left == None and node.right != None:
if node.parent != None:
if node.parent.left == node:
node.parent.left = node.right
if node.parent.right == node:
node.parent.right = node.right
node.right.parent = node.parent
self.update_ks_up(node.right)
self.balance(node.right)
del node
# Case 4: Node has two children
elif node.left != None and node.right != None:
s = self.successor(node)
print('successor', s.value)
sp = self.search(self.root, s.parent.value)
print(sp)
if node.parent != None:
if node.parent.left == node:
node.parent.left = s
if node.parent.right == node:
node.parent.right = s
s.parent = node.parent
s.right = node.right
s.left = node.left
if sp != None:
if sp.left == s:
sp.left = None
if sp.right == s:
sp.right = None
node.right.parent = s
self.update_ks_up(sp)
self.balance(sp)
del node
return
"""
Description:
Find successor of a node
Complexity: O(lg n)
Since O(levels) = O(lg n)
"""
def successor(self, node):
node = node.right
while node.left != None:
node = node.left
return node
"""
Description:
Search for a node given its value, return None if any node contains this value
Complexity: O(lg n)
Since O(levels) = O(lg n)
"""
def search(self, root, value):
if root == None:
return None
if root.value == value:
return root
else:
if value < root.value:
return self.search(root.left, value)
else:
return self.search(root.right, value)
def r_left_right(self, x, y, z):
print('-----------------------------', 'left_right')
"""
R R
| |
x y
/ \ / \
z A ---> z x
/ \ / \ / \
D y D C B A
/ \
C B
Executed if A -> {k-1), D -> (k-1) and B or C-> (k-1)
"""
R = x.parent
A = x.right
B = y.right
C = y.left
D = z.left
x.right = A
x.left = B
z.right = C
z.left = D
y.right = x
y.left = z
x.parent = y
z.parent = y
y.parent = R
if R != None:
if R.left == x:
R.left = y
if R.right == x:
R.right = y
self.update_ks_up(x)
self.update_ks_up(z)
return
def r_left_left(self, x, y):
print('-----------------------------', 'left_left')
"""
R R
| |
x y
/ \ / \
y A ---> C x
/ \ / \
B C B A
Executed if A -> {k-1), B -> (k+1) and C -> (k or k+1)
"""
A = x.right
B = y.left
C = y.right
R = x.parent
y.right = x
x.left = B
x.parent = y
y.parent = R
if R != None:
if R.left == x:
R.left = y
if R.right == x:
R.right = y
self.update_ks_up(x)
return
def r_right_left(self, x, y, z):
print('-----------------------------', 'right_left')
"""
R R
| |
x y
/ \ / \
A z ---> x z
/ \ / \ / \
y D A B C D
/ \
B C
Executed if A -> {k-1), D -> (k-1) and B or C-> (k-1)
"""
R = x.parent
A = x.left
B = y.left
C = y.right
D = z.right
x.left = A
x.right = B
z.left = C
z.right = D
y.left = x
y.right = z
x.parent = y
z.parent = y
y.parent = R
if R != None:
if R.left == x:
R.left = y
if R.right == x:
R.right = y
self.update_ks_up(x)
self.update_ks_up(z)
return
def r_right_right(self, x, y):
print('-----------------------------', 'right_right')
"""
R R
| |
x y
/ \ / \
A y ---> x C
/ \ / \
B C A B
Executed if A -> {k-1), C -> (k+1) and B -> (k or k+1)
"""
A = x.left
B = y.left
C = y.right
R = x.parent
y.left = x
x.right = B
x.parent = y
y.parent = R
if R != None:
if R.left == x:
R.left = y
if R.right == x:
R.right = y
self.update_ks_up(x)
return
class Node:
def __init__(self, value):
self.value = value
self.left = None
self.right = None
self.parent = None
self.k = 0
# Test cases
avl = AVL()
n5 = avl.insert(avl.root, 5)
n6 = avl.insert(avl.root, 6)
n7 = avl.insert(avl.root, 7)
avl.insert(avl.root, 1)
avl.insert(avl.root, 9)
avl.insert(avl.root, 2)
avl.insert(avl.root, 20)
avl.insert(avl.root, 72)
avl.insert(avl.root, 3)
avl.insert(avl.root, 44)
avl.insert(avl.root, 4)
print(avl.search(avl.root, 5).value)
avl.remove(6)
avl.remove(4)
print(avl.search(avl.root, 44))
|
"""
Author: Max Martinez Ruts
Date: October 2019
Description:
Skip List:
Data structure consisting in a group of double linked lists stacked above one other with the properties that
lists stacked in upper levels skip certain elements found in lower lists of lower levels.
Furthermore, if an element is found in list l, it will also be found in all other lists beneath l.
This data structure allows faster search than linked lists, since further elements in the lowest level list become
available by navigation thorough lists in upper levels.
An example of a Skip list would be:
l3 -> 5 ----------------- 9
| |
l2 -> 5 ------- 7 ------- 9
| | |
l1 -> 5 -- 6 -- 7 -- 8 -- 9
Where nodes can from different layers can be accessed using pointers that link nodes having same values in distinct layers
Using the given Skip list, search(8) would first go from l1 -> 5 to l2 -> 5 to l2 -> 7 to l1 -> 7 to l1 -> 8
Summary of complexity
Search: O(lg n)
"""
import random
class Node:
def __init__(self, value, left, right, up, down):
# Define neighbour pointers
self.up = up
self.left = left
self.right = right
self.down = down
self.value = value
# If down is empty, lv = 0, otherwise lv = down lode lv + 1
self.lv = 0
if self.down != None:
self.lv = self.down.lv + 1
layer[self.lv].append(self.value)
"""
Insert a node in the lowest lv by searching node s and inserting on the right on s on lv 0
Recursively inserting a node lv+1 with p = 1/2.
Complexity: O(lg n) w.h.p (with high probability)
Claim: only c lg n levels exist in skip list w.h.p where c is a constant
Proof: P(failure) = P(not <= c lg n levels)
= P(> c lg n levels)
= P(some element gets promoted greater than c lg n times)
<= n * P(element x gets promoted greater than c lg n times)
= n * (1/2)^(c lg n) = n/n^c = 1/n^(c-1) = 1/n^a with a = c - 1
Example: with n = 10 and c = 10
P(failure) = 1/10^9 = 0.000000001, meaning than only 0.000000001 times levels > c lg n
"""
def insert(value):
# Create node to be inserted in lv 0
n = Node(value, None, None, None, None)
# Search the left neighbour of n
s = search(pt, value, n.lv)
# Temp variable
r = s.right
# Update pointers
if s.right != None:
s.right.left = n
s.right = n
n.left = s
n.right = r
# Repeating process one lv above with probability of 1/2
rd = random.randint(0, 1)
while rd == 1:
rd = random.randint(0, 1)
# Temp variable of node of previous lv
temp = n
# Create node to be inserted in new lv
n = Node(value, None, None, None, n)
# Up of previous n is new n
temp.up = n
# Search the left neighbour of n
s = search(pt, value, n.lv)
# Temp variable
r = s.right
# Update pointers
if s.right != None:
s.right.left = n
s.right = n
n.left = s
n.right = r
return
"""
Idea:
Recursively search by accessing right nodes in the uppermost compatible node of the current note:
1. Reach the uppermost node of the current examined node
2. Try to go right. If right does not exist or overshoot, go down
If down reached a lower level than admitted, solution was reached, since level is minimum and right would overshoot
Complexity: O(lg n)
Proof: Backward intuition
Staring with the found node, to reach
"""
def search(root, value, lv):
node = root
print(root.value, root.lv)
# Go to the uppermost node
while node.up != None:
node = node.up
# Try to go right, if right does not exist or overshooting, go down and try again
while node.right == None or node.right.value > value:
if node.down != None and node.down.lv >= lv:
node = node.down
# If lowest lv encountered
else:
return node
# Recursively search starting from new node
return search(node.right, value, lv)
def delete():
return
layer = {0: [], 1: [], 2: [], 3: [], 4: [], 5: [], 6: [], 7: [], 8: [], 9: [], 10: []}
pt = Node(5, None, None, None, None)
for i in range(6, 100):
print('----', i, '----')
insert(i)
print('-------------------')
n = search(pt, 60, 0)
print(n.value, n.lv)
for l in layer:
print(layer[l]) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.