text
stringlengths 37
1.41M
|
---|
from primes import is_prime
x = True
y = False
z = 0
if z:
print("x is false")
if x and y or (z and y):
print("hello")
i = 0
l = [x for x in range(10000) if is_prime(x)]
s = "Hello"
print(s[::-1])
def fib(n):
if n <= 0:
return 0
if n == 1 :
return 1
if n == 2:
return 1
return fib(n - 1) + fib(n - 2)
print(fib(8-9))
|
def fib(n):
a, b = 1, 1
if n <= 0:
return 0
if n == 1 or n == 2:
return 1
for i in range(n - 2):
temp = b
b = a+b
a = temp
return b
|
import string
def ispanagram(str,alphabet=string.ascii_lowercase):
alphaset=set(alphabet)
return alphaset<=set(str.lower())
ans=ispanagram('the quick brown fox jumps over the lazy dog')
print(ans)
#ANOTHER METHOD
def panagram(str):
alphabet=['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']
for x in str:
if x.lower() in alphabet:
y=alphabet.index(x)
alphabet.pop(y)
if alphabet==[]:
return True
ans=panagram('the quick brown fox jumps over the lazy dog')
print(ans) |
import re
# string = '*'
# match = re.search('*CONUTS', 'COCONUTS')
# print(match)
txt = "*"
# x = re.search("a*", txt)
# match = re.search('COCONUTS', '*CONUTS')
match = re.search('CA', 'CAT')
print(match)
x = re.split('(\W*)', '*A*B**CD')
string = "*A*B**CD"
a = string.split('*')
print(a)
# *CONUTS
# *COCONUTS
# *OCONUTS
# *CONUTS
# string = '*'
# split_string = re.split('(\W*)', string)
# print(split_string)
# a = 'ABC'
# b = 'AB'
# print(b in a) |
# Write a class to hold player information, e.g. what room they are in currently.
from item import Item
class Player:
def __init__(self, name, current_room, inventory=[]):
self.name = name
self.current_room = current_room
self.inventory = inventory
# List player's inventory
def print_inventory(self):
if len(self.inventory) == 0:
print("\nThe player's inventory is empty.")
else:
print("\nHere is the player's inventory:")
for i, item in enumerate(self.inventory):
print(f' {i+1}: {item}')
# Used when player takes an item
def on_take(self, take_item):
print(f'You have picked up {take_item}.')
# User when player drops an item
def on_drop(self, drop_item):
print(f'You have dropped {drop_item}.')
# User takes an item in the room
def take(self, take_item):
room_items_names = [item.name for item in self.current_room.items]
if take_item not in room_items_names:
print(f'\nERROR: {take_item} is not located in the room.')
else:
for item in self.current_room.items:
if take_item == item.name:
self.inventory.append(item)
self.current_room.items.remove(item)
self.on_take(take_item)
break
# User drops an item in the room
def drop(self, drop_item):
inventory_items_names = [item.name for item in self.inventory]
if drop_item not in inventory_items_names:
print(f'\nERROR: {drop_item} is not located in players inventory.')
else:
for item in self.inventory:
if drop_item == item.name:
self.inventory.remove(item)
self.current_room.items.append(item)
self.on_drop(drop_item)
break
|
from collections import Counter
import math
def load_data():
with open("inputs/day_3_input.txt") as f:
return [item.strip() for item in f.readlines()]
def get_column_multiplier(row_size, column_size, row_step_size, column_step_size):
steps_to_bottom = math.ceil(row_size / row_step_size)
minimum_columns = steps_to_bottom * column_step_size
column_multiplier = math.ceil(minimum_columns / column_size)
return column_multiplier
def get_expanded_data(data, column_multiplier):
return [row * column_multiplier for row in data]
def get_path_values(data, row_step_size, column_step_size):
row_position = 0
column_position = 0
path_values = []
while row_position < len(data):
path_values += data[row_position][column_position]
row_position += row_step_size
column_position += column_step_size
return path_values
def main(column_step_size, row_step_size):
# Expand the data to fit the required path
print(f"Step Size is {row_step_size} rows x {column_step_size} columns")
original_data = load_data()
print(
f"Original Data is {len(original_data)} rows x {len(original_data[0])} columns"
)
column_multiplier = get_column_multiplier(
row_size=len(original_data),
column_size=len(original_data[0]),
row_step_size=row_step_size,
column_step_size=column_step_size,
)
print(f"Column Multiplier is {column_multiplier}")
data = get_expanded_data(data=original_data, column_multiplier=column_multiplier)
print(f"Expanded data is {len(data)} rows x {len(data[0])} columns")
# Walk the path and count the trees
path_values = get_path_values(
data=data, row_step_size=row_step_size, column_step_size=column_step_size
)
print(f"Path is {len(path_values)} long")
tree_count = Counter(path_values)["#"]
print(f"{tree_count} trees in path\n")
return tree_count
if __name__ == "__main__":
# Quick check for the most complicated functions.
assert get_column_multiplier(100, 10, 1, 3) == 30
assert get_column_multiplier(100, 7, 1, 3) == 43
assert get_column_multiplier(323, 31, 1, 3) == 32
assert get_column_multiplier(323, 31, 1, 5) == 53
assert get_column_multiplier(323, 31, 2, 1) == 6
assert main(3, 1) == 207
print("All Checks Complete\n")
output_list = [
main(column_step_size=1, row_step_size=1),
main(column_step_size=3, row_step_size=1),
main(column_step_size=5, row_step_size=1),
main(column_step_size=7, row_step_size=1),
main(column_step_size=1, row_step_size=2),
]
print(f"Output list is: {output_list}")
print(f"Product is {math.prod(output_list)}")
|
from typing import Dict, List
import math
def load_data() -> List[str]:
with open("inputs/day_5_input.txt", "r") as f:
return [item.strip() for item in f.readlines()]
def binary_partition(instruction: str, bottom: int, top: int) -> Dict[str, int]:
if instruction in ["F", "L"]:
return {"top": top - math.ceil((top - bottom) / 2), "bottom": bottom}
elif instruction in ["B", "R"]:
return {"top": top, "bottom": bottom + math.ceil((top - bottom) / 2)}
else:
assert False
def parse_seat_instructions(instructions: str, size: int) -> Dict[str, int]:
position = {"bottom": 0, "top": size - 1}
for instruction in instructions:
position = binary_partition(instruction, **position)
return position
def get_seat_id(instructions: str) -> int:
row = parse_seat_instructions(instructions[:8], 128)["top"]
column = parse_seat_instructions(instructions[7:], 8)["top"]
return row * 8 + column
def main() -> None:
data = load_data()
seats = [get_seat_id(item) for item in data]
print(f"Largest Seat ID: {max(seats)}")
print(f"Empty Seats: {set(range(0, 128 * 8)) - set(seats)}")
if __name__ == "__main__":
main()
|
import numpy as np
import matplotlib.pyplot as plt
def plotLineGraph(stat,iterations):
x = np.arange(iterations)
plt.plot(x,stat[:,0])
plt.plot(x,stat[:,1])
plt.plot(x,stat[:,2])
plt.legend([str(stat[-1,0])+' Games Won By Bot 1', str(stat[-1,1])+' Games Won By Bot 2', str(stat[-1,2])+' Games Draw'], loc='upper left')
plt.suptitle('Training of Bot 1 (playing with bot 2)')
plt.title('Training after '+str(iterations)+' iterations')
plt.savefig("TrainingHistory.png") # save as png
plt.show() |
def print_name(x):
name=input("your name:")
print(name*x) |
import speech_recognition as sr
r = sr.Recognizer() # Works as a recognizer to recognize our audio
with sr.Microphone(device_index = None) as source: # Initializing our source to sr.Microphone()
print('Speak Anything : ')
r.adjust_for_ambient_noise(source, duration = 5) # Using the ambient noise suppression/adjustment
audio = r.listen(source) # Telling it to listen to source and storing it in audio
try:
text = r.recognize_google(audio) # Converts audio into text
print('You said : {}'.format(text)) # Prints what you said
except:
print('Sorry could not recognize your voice') |
# # # def test(x,y): #define function
# # # print(x,y)
# # # test(10,20) #calling function
# # # def users(name,age):
# # # get_name=f'your name is {name}'
# # # get_age=f'age {age}'
# # # return [get_name, get_age]
# # # data = users('ram', 20)
# # # print(data[0])
# # # print(data[1])
# # # #lambda, endless, inner fxn
# # def students(name, roll=None):
# # print(name)
# # if not roll == None:
# # print(roll)
# # # students('ram',20)
# def take_value():
# x = int(input('enter principle'))
# y = int(input('Enter time'))
# z = int(input('Enter rate'))
# return [x,y,z]
# def calculate():
# data = take_value()
# p = data[0]
# t = data[1]
# r = data[2]
# return p*t*r/100
# def display():
# print(calculate())
# display()
# # x = 1
# # evn_num = 0
# # odd_num = 0
# # while x<=50
# # if x % 2 == 0
# nested function:
# def users():
# def names(name):
# return f'your name is {name}'
# return names
# data = users()
# print(data('ram'))
# x = 10
# def test():
# global x
# x = x + 20
# print(x)
# test()
#lambda function
# data = lambda x,y: x + y
# print(data(10, 20))
# def users(x):
# return lambda y: x + y
# a = users(10)
# print(a(20))
# def users()
#dunder method in documentation string
#function decorator study
#python.org
#annotation
#function decorator
# def get_doc(anyfunction):
# def inner():
# return f'{anyfunction.__doc__}'
# return inner
# @get_doc
# def test():
# """ this is test function"""
# pass
# @get_doc
# def users():
# """ hello users function """
# function decorator
# def zero_check(anyfunction):
# def inner(x,y):
# if y == 0:
# return f'y is zero'
# return anyfunction(x,y)
# return inner
# def add(x,y):
# if y == 0:
# print('y is zero')
# return x+y
# print(add(10,10))
# custom module, fxn wrap and multiple decorator study
# read documentation at python.org
# from functools import wraps
# def test(anyfunction):
# @wraps(anyfunction)
# def inner():
# """ Hello inner function """
# return "test"
# return inner
# @test
# def get():
# """ Hello get function """
# return "success"
# print(get.__doc__)
#online compiler linux study
import calculator
print(calculator.add(20,10))
print(calculator.sub(40,30))
#git ignore, OS module, system module study |
import sys
digit_string = sys.argv[1]
count = 0
for i in range(0, len(digit_string)):
count += int(digit_string[i])
print(count)
# tutors' solution
# import sys
# print(sum([int(x) for x in sys.argv[1]]))
|
# 학생 5명의 수학 점수를 입력 후 평균 값이 80점 이상이라면 PASS, 아니라면 Try Again을 입력하기
total = 0
studentList = {}
print("첫 번쨰 학생의 점수를 입력하세요")
studentList[0] = int(input())
print("두 번쨰 학생의 점수를 입력하세요")
studentList[2] = int(input())
print("세 번쨰 학생의 점수를 입력하세요")
studentList[3] = int(input())
print("네 번쨰 학생의 점수를 입력하세요")
studentList[4] = int(input())
print("다섯 번쨰 학생의 점수를 입력하세요")
studentList[5] = int(input())
for score in studentList.values() :
total += score
print("total.. : ",total)
print("평균 점수.. : ",total/len(studentList))
if total >= 80:
print("PASS")
else :
print("Try Again")
|
# 형변환
# 변수를 문자와 정수로 초기화
var1 = '123'
var2 = 123
# 문자와 정수를 사용해서 덧셈 연산을 시도하면 예외가 발생한다
# print(var1+var2)
# 문자(열)를 정수로 변경
# 문자(열)를 정수로 변환하면 정수의 덧셈 연산이 가능하다.
print(int(var1)+var2)
# 정수를 문자(열)로 변경
# 정수를 문자(열)로 변환하면 문자의 덧셈 연산이 가능하다.
print(var1+str(var2))
# 'hello'는 정수로 형변환될수없다.
# print(int('hello')) |
#Find all occurences of a single lowercase letter inbetween 3 uppercase letters
import re
pattern = re.compile('[a-z]+[A-Z]{3}[a-z]{1}[A-Z]{3}[a-z]+')
junkfile = open("ch3_junk.txt", "r")
junk = junkfile.read()
junkfile.close()
result = pattern.finditer(junk)
if result:
for match in result:
print match.group()
#Answer: linkedlist.php
|
#!/usr/bin/env python
# -*- coding: utf8 -*-
import re
FILE = r'examples.txt'
utfCheck = re.compile('[^\d]')
f = open(FILE, 'r')
msg = f.read().strip()
msgList = list(msg)
words = []
tmp = []
cnt = 0
for i in range(len(msgList)):
if utfCheck.search(msgList[i]):
tmp.append(msgList[i])
cnt += 1
if cnt == 3:
word = ''.join(tmp)
words.append(word)
tmp = []
cnt = 0
else:
words.append(msgList[i])
for word in words:
print word,
|
# Enter your code here. Read input from STDIN. Print output to STDOUT
t=int(input())
while t>0:
t -=1
ss=input()
x=""
y=""
for i in range(len(ss)):
if(i%2==0):
x += ss[i]
else:
y += ss[i]
print(x, y, end=" ")
print()
|
# General implementation for Knuth Morris Pratt Pattern Searching algorithm.
# This algorithm is used to find a pattern or substring in an array/string
def kmp(s):
"""
Given a concatenated string s with unique identifier, return a table
F such that F[i] is the longest proper prefix of s[0..i] as well as
a suffix of s[0..i]
"""
n = len(s)
if n == 0:
return []
F = [0] * n
for i in range(1, n):
# Set k to the length of the longest proper prefix that is also
# a suffix of s[0..i-1].
k = F[i - 1]
# Attempt to shorten the prefix as little as possible such that the
# prefix and suffix can both be extended by the same character
while k > 0 and s[k] != s[i]:
# The property s[0..k-1] == s[i-k..i-1] holds because s[0..k-1]
# is the longest proper prefix that is equal to the suffix of
# s[0..i-1]. We further break this problem down by looking at the
# s[0..k-1]. One proper prefix of s[0..k-1] is s[0..k-2]. Because
# s[0..k-1] == s[i-k..i-1], s[0..k-2] can also act as the proper
# prefix for s[i].
k = F[k-1]
if s[k] == s[i]:
k += 1
F[i] = k
return F
def substr(s, substr, seperator='#'):
"""
Checks if SUBSTR is a substring of S.
"""
m = len(substr)
s = substr + seperator + s
F = kmp(s)
return any([i == m for i in F]) |
class Solution(object):
def minDistance(self, word1, word2):
m, n = len(word1), len(word2)
# initialize dp matrix
dp = [[0 for i in range(n + 1)] for j in range(m + 1)]
# Build up dp bottom up
for i in range(m + 1):
for j in range(n + 1):
# if first string is empty then only operation would be
# to insert every character.
if i == 0:
dp[i][j] = j
# same if second string is empty.
elif j == 0:
dp[i][j] = i
# we dont have to do anything if the two characters are the
# same.
elif word1[i-1] == word2[j-1]:
dp[i][j] = dp[i-1][j-1]
# if the last characters are different, then consider whether
# to insert, replace, or replace.
else:
dp[i][j] = 1 + min(dp[i][j-1], dp[i-1][j], dp[i-1][j-1])
# return minimum edit distance.
return dp[m][n]
def test():
print("Testing algorithm...")
s = Solution()
# assert 3 == s.minDistance("saturday", "sunday")
# assert 0 == s.minDistance("hello", "hello")
assert 1 == s.minDistance("a", "b")
print("All tests pass!")
if __name__ == '__main__':
test() |
import time
import pandas as pd
import numpy as np
CITY_DATA = { 'chicago': 'chicago.csv',
'new york city': 'new_york_city.csv',
'washington': 'washington.csv' }
def get_filters():
"""
Asks user to specify a city, month, and day to analyze.
Returns:
(str) city - name of the city to analyze
(str) month - name of the month to filter by, or "all" to apply no month filter
(str) day - name of the day of week to filter by, or "all" to apply no day filter
"""
print('Hello! Let\'s explore some US bikeshare data!')
# get user input for city (chicago, new york city, washington)
while True:
city = input("Enter city.. options: [Chicago, New York City, Washington]\n").upper().strip()
if city in ['CHICAGO', 'NEW YORK CITY', 'WASHINGTON']:
break
# get user input for month (all, january, february, ... , june)
while True:
month = input("Enter month.. options [All, January, February, March, April, May, June]\n").upper().strip()
if month in ['ALL', 'JANUARY', 'FEBRUARY', 'MARCH', 'APRIL', 'MAY', 'JUNE']:
break
# get user input for day of week (all, monday, tuesday, ... sunday)
while True:
day = input("Enter day of week.. options [All, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday]\n").upper().strip()
if day in ['ALL', 'MONDAY', 'TUESDAY', 'WEDNESDAY', 'THURSDAY', 'FRIDAY', 'SATURDAY', 'SUNDAY']:
break
print('-'*40)
return city, month, day
def load_data(city, month, day):
"""
Loads data for the specified city and filters by month and day if applicable.
Args:
(str) city - name of the city to analyze
(str) month - name of the month to filter by, or "all" to apply no month filter
(str) day - name of the day of week to filter by, or "all" to apply no day filter
Returns:
df - Pandas DataFrame containing city data filtered by month and day
"""
# load data file into a dataframe
df = pd.read_csv(CITY_DATA[city])
# convert the Start Time column to datetime
df['Start Time'] = pd.to_datetime(df['Start Time'])
# extract month and day of week from Start Time to create new columns
df['month'] = df['Start Time'].dt.month
df['day_of_week'] = df['Start Time'].dt.weekday_name
# filter by month if applicable
if month != 'all':
# use the index of the months list to get the corresponding int
months = ['january', 'february', 'march', 'april', 'may', 'june']
month = months.index(month) + 1
# filter by month to create the new dataframe
df = df[df['month'] == month]
# filter by day of week if applicable
if day != 'all':
# filter by day of week to create the new dataframe
df = df[df['day_of_week'] == day.title()]
return df
def time_stats(df):
"""Displays statistics on the most frequent times of travel."""
print('\nCalculating The Most Frequent Times of Travel...\n')
start_time = time.time()
# display the most common month
print("Most Common Month: ", str(df['month'].mode()[0]))
# display the most common day of week
print("Most Common day of week is: ", str(df['day_of_week'].mode()[0]))
# display the most common start hour
print("Most common start hour is: ", str(df['Start Time'].dt.hour.mode()[0]))
print("\nThis took %s seconds." % (time.time() - start_time))
print('-'*40)
def station_stats(df):
"""Displays statistics on the most popular stations and trip."""
print('\nCalculating The Most Popular Stations and Trip...\n')
start_time = time.time()
# print(df.info())
# display most commonly used start station
print('Most Commonly Used Start Station')
print(df['Start Station'].mode()[0])
# display most commonly used end station
print('\nMost Commonly Used End Station')
print(df['End Station'].mode()[0])
# display most frequent combination of start station and end station trip
print('\nMost frequent combination of start station and end station trip')
df1 = '[Start]: ' + df['Start Station'] + ' [Stop]: ' + df['End Station']
print(df1.mode()[0])
print("\nThis took %s seconds." % (time.time() - start_time))
print('-'*40)
def trip_duration_stats(df):
"""Displays statistics on the total and average trip duration."""
print('\nCalculating Trip Duration...\n')
start_time = time.time()
# display total travel time
print('\nTotal travel time in days, hours, min and seconds', sep='\n')
print(pd.to_timedelta(str(df['Trip Duration'].sum()) + 's'))
# display mean travel time
print('\nMean travel time in days, hours, min and seconds')
print(pd.to_timedelta(str(df['Trip Duration'].mean()) + 's'))
print("\nThis took %s seconds." % (time.time() - start_time))
print('-'*40)
def user_stats(df):
"""Displays statistics on bikeshare users."""
print('\nCalculating User Stats...\n')
start_time = time.time()
# Display counts of user types
print("\nCounts of user types")
print(df.groupby(['User Type']).size().to_string())
# Display counts of gender
print("\nCounts of gender")
if 'Gender' in df.columns:
print(df.groupby(['Gender']).size().to_string())
else:
print('Gender stats cannot be calculated because \'Gender\' does not appear in the dataframe')
# Display earliest, most recent, and most common year of birth
print("\nEarliest, most recent, and most common year of birth")
if 'Birth Year' in df.columns:
print("Earliest year: ", df["Birth Year"].min(), end="\n\n")
print("Most recent year: ", df["Birth Year"].max(), end="\n\n")
print("Common year: ", df["Birth Year"].mode()[0], end="\n\n")
else:
print('Birth Year stats cannot be calculated because \'Birth Year\' does not appear in the dataframe')
print("\nThis took %s seconds." % (time.time() - start_time))
print('-'*40)
def display_data(df):
"""
This function displays the content of the dataframe depending on users choice
Args:
(dataframe) df - Pandas dataframe containing data
Returns:
null
"""
view_data = input("Would you like to view rows of individual trip data? Enter yes or no?\n").upper().strip()
start_loc = 0
num_rows = 0
while (view_data == "yes"):
while True:
rows = input("Enter number of rows you want to view\n").strip()
if rows.isdigit():
num_rows = int(rows)
break
else:
print(num_rows, ": is no valid. Enter valid integer!!", end='\n\n')
stop_loc = start_loc + num_rows
df_len = len(df)
print("\n","-"*40,"Displaying rows: ", start_loc, " to: ", df_len if stop_loc > len(df) else stop_loc , "-"*40, end='\n\n')
print(df.iloc[start_loc:start_loc + num_rows].to_string())
start_loc += num_rows
view_display = input("\nDo you wish to continue viewing the next set of data?: Enter yes or no \n").lower()
view_data = view_display
if start_loc > df_len and view_data == 'yes':
print("\nYou have already viewed all data, exiting.....\n")
break
def main():
while True:
city, month, day = get_filters()
print(city, month, day)
df = load_data(city, month, day)
time_stats(df)
station_stats(df)
trip_duration_stats(df)
user_stats(df)
display_data(df)
restart = input('\nWould you like to restart? Enter yes or no., \n')
if restart.lower() != 'yes':
break
if __name__ == "__main__":
main()
|
import time
import random
import timeit
def sequential_search (a_list, item):
start_time = time.time()
pos = 0
found = False
while pos < len(a_list) and not found:
if a_list[pos] == item:
found = True
else:
pos = pos+1
return found, (time.time() - start_time)
def ordered_sequential_search(a_list, item):
start_time = time.time()
pos = 0
found = False
stop = False
while pos < len(a_list) and not found and not stop:
if a_list[pos] == item:
found = True
else:
if a_list[pos] > item:
stop = True
else:
pos = pos+1
return found, (time.time() - start_time)
def binary_search_iterative(a_list, item):
start_time = time.time()
first = 0
last = len(a_list) - 1
found = False
while first <= last and not found:
midpoint = (first + last) // 2
if a_list[midpoint] == item:
found = True
else:
if item < a_list[midpoint]:
last = midpoint - 1
else:
first = midpoint + 1
return found, (time.time() - start_time)
def binary_search_recursive(a_list, item):
start_time = time.time()
if len(a_list) == 0:
return False, start_time
else:
midpoint = len(a_list) // 2
if a_list[midpoint] == item:
return True, (time.time() - start_time)
else:
if item < a_list[midpoint]:
return binary_search_recursive(a_list[:midpoint], item), (time.time() - start_time)
else:
return binary_search_recursive(a_list[midpoint + 1:], item), (time.time() - start_time)
if __name__ == "__main__":
list1 = []
list2 = []
list3 = []
list4 = []
list5 = []
list6 = []
list7 = []
list8 = []
list9 = []
list10 = []
list11 = []
list12 = []
list13 = []
list14 = []
list15 = []
list16 = []
list17 = []
list18 = []
list19 = []
list20 = []
list21 = []
list22 = []
list23 = []
list24 = []
list25 = []
list26 = []
list27 = []
list28 = []
list29 = []
list30 = []
list31 = []
list32 = []
list33 = []
list34 = []
list35 = []
list36 = []
list37 = []
list38 = []
list39 = []
list40 = []
list41 = []
list42 = []
list43 = []
list44 = []
list45 = []
list46 = []
list47 = []
list48 = []
list49 = []
list50 = []
list51 = []
list52 = []
list53 = []
list54 = []
list55 = []
list56 = []
list57 = []
list58 = []
list59 = []
list60 = []
list61 = []
list62 = []
list63 = []
list64 = []
list65 = []
list66 = []
list67 = []
list68 = []
list69 = []
list70 = []
list71 = []
list72 = []
list73 = []
list74 = []
list75 = []
list76 = []
list77 = []
list78 = []
list79 = []
list80 = []
list81 = []
list82 = []
list83 = []
list84 = []
list85 = []
list86 = []
list87 = []
list88 = []
list89 = []
list90 = []
list91 = []
list92 = []
list93 = []
list94 = []
list95 = []
list96 = []
list97 = []
list98 = []
list99 = []
list100 = []
list1 = random.sample(xrange(500), 500)
list2 = random.sample(xrange(500), 500)
list3 = random.sample(xrange(500), 500)
list4 = random.sample(xrange(500), 500)
list5 = random.sample(xrange(500), 500)
list6 = random.sample(xrange(500), 500)
list7 = random.sample(xrange(500), 500)
list8 = random.sample(xrange(500), 500)
list9 = random.sample(xrange(500), 500)
list10 = random.sample(xrange(500), 500)
list11 = random.sample(xrange(500), 500)
list12 = random.sample(xrange(500), 500)
list13 = random.sample(xrange(500), 500)
list14 = random.sample(xrange(500), 500)
list15 = random.sample(xrange(500), 500)
list16 = random.sample(xrange(500), 500)
list17 = random.sample(xrange(500), 500)
list18 = random.sample(xrange(500), 500)
list19 = random.sample(xrange(500), 500)
list20 = random.sample(xrange(500), 500)
list21 = random.sample(xrange(500), 500)
list22 = random.sample(xrange(500), 500)
list23 = random.sample(xrange(500), 500)
list24 = random.sample(xrange(500), 500)
list25 = random.sample(xrange(500), 500)
list26 = random.sample(xrange(500), 500)
list27 = random.sample(xrange(500), 500)
list28 = random.sample(xrange(500), 500)
list29 = random.sample(xrange(500), 500)
list30 = random.sample(xrange(500), 500)
list31 = random.sample(xrange(500), 500)
list32 = random.sample(xrange(500), 500)
list33 = random.sample(xrange(500), 500)
list34 = random.sample(xrange(1000), 1000)
list35 = random.sample(xrange(1000), 1000)
list36 = random.sample(xrange(1000), 1000)
list37 = random.sample(xrange(1000), 1000)
list38 = random.sample(xrange(1000), 1000)
list39 = random.sample(xrange(1000), 1000)
list40 = random.sample(xrange(1000), 1000)
list41 = random.sample(xrange(1000), 1000)
list42 = random.sample(xrange(1000), 1000)
list43 = random.sample(xrange(1000), 1000)
list44 = random.sample(xrange(1000), 1000)
list45 = random.sample(xrange(1000), 1000)
list46 = random.sample(xrange(1000), 1000)
list47 = random.sample(xrange(1000), 1000)
list48 = random.sample(xrange(1000), 1000)
list49 = random.sample(xrange(1000), 1000)
list50 = random.sample(xrange(1000), 1000)
list51 = random.sample(xrange(1000), 1000)
list52 = random.sample(xrange(1000), 1000)
list53 = random.sample(xrange(1000), 1000)
list54 = random.sample(xrange(1000), 1000)
list55 = random.sample(xrange(1000), 1000)
list56 = random.sample(xrange(1000), 1000)
list57 = random.sample(xrange(1000), 1000)
list58 = random.sample(xrange(1000), 1000)
list59 = random.sample(xrange(1000), 1000)
list60 = random.sample(xrange(1000), 1000)
list61 = random.sample(xrange(1000), 1000)
list62 = random.sample(xrange(1000), 1000)
list63 = random.sample(xrange(1000), 1000)
list64 = random.sample(xrange(1000), 1000)
list65 = random.sample(xrange(1000), 1000)
list66 = random.sample(xrange(1000), 1000)
list67 = random.sample(xrange(1000), 1000)
list68 = random.sample(xrange(10000), 10000)
list69 = random.sample(xrange(10000), 10000)
list70 = random.sample(xrange(10000), 10000)
list71 = random.sample(xrange(10000), 10000)
list72 = random.sample(xrange(10000), 10000)
list73 = random.sample(xrange(10000), 10000)
list74 = random.sample(xrange(10000), 10000)
list75 = random.sample(xrange(10000), 10000)
list76 = random.sample(xrange(10000), 10000)
list77 = random.sample(xrange(10000), 10000)
list78 = random.sample(xrange(10000), 10000)
list79 = random.sample(xrange(10000), 10000)
list80 = random.sample(xrange(10000), 10000)
list81 = random.sample(xrange(10000), 10000)
list82 = random.sample(xrange(10000), 10000)
list83 = random.sample(xrange(10000), 10000)
list84 = random.sample(xrange(10000), 10000)
list85 = random.sample(xrange(10000), 10000)
list86 = random.sample(xrange(10000), 10000)
list87 = random.sample(xrange(10000), 10000)
list88 = random.sample(xrange(10000), 10000)
list89 = random.sample(xrange(10000), 10000)
list90 = random.sample(xrange(10000), 10000)
list91 = random.sample(xrange(10000), 10000)
list92 = random.sample(xrange(10000), 10000)
list93 = random.sample(xrange(10000), 10000)
list94 = random.sample(xrange(10000), 10000)
list95 = random.sample(xrange(10000), 10000)
list96 = random.sample(xrange(10000), 10000)
list97 = random.sample(xrange(10000), 10000)
list98 = random.sample(xrange(10000), 10000)
list99 = random.sample(xrange(10000), 10000)
list100 = random.sample(xrange(10000), 10000)
print "Sequential Search took %10.7f seconds to run on average" % (sum(((sequential_search(sorted(list1), -1))[1], (sequential_search(sorted(list2), -1))[1], (sequential_search(sorted(list3), -1))[1], (sequential_search(sorted(list4), -1))[1],
(sequential_search(sorted(list5), -1))[1], (sequential_search(sorted(list6), -1))[1], (sequential_search(sorted(list7), -1))[1],
(sequential_search(sorted(list8), -1))[1], (sequential_search(sorted(list9), -1))[1], (sequential_search(sorted(list10), -1))[1], (sequential_search(sorted(list11), -1))[1],
(sequential_search(sorted(list12), -1))[1],
(sequential_search(sorted(list13), -1))[1], (sequential_search(sorted(list14), -1))[1],(sequential_search(sorted(list15), -1))[1],
(sequential_search(sorted(list16), -1))[1], (sequential_search(sorted(list17), -1))[1],
(sequential_search(sorted(list18), -1))[1], (sequential_search(sorted(list19), -1))[1], (sequential_search(sorted(list20), -1))[1],
(sequential_search(sorted(list21), -1))[1], (sequential_search(sorted(list22), -1))[1], (sequential_search(sorted(list23), -1))[1],
(sequential_search(sorted(list24), -1))[1], (sequential_search(sorted(list25), -1))[1], (sequential_search(sorted(list26), -1))[1],
(sequential_search(sorted(list27), -1))[1], (sequential_search(sorted(list28), -1))[1], (sequential_search(sorted(list29), -1))[1],
(sequential_search(sorted(list30), -1))[1], (sequential_search(sorted(list31), -1))[1], (sequential_search(sorted(list32), -1))[1],
(sequential_search(sorted(list33), -1))[1], (sequential_search(sorted(list34), -1))[1], (sequential_search(sorted(list35), -1))[1],
(sequential_search(sorted(list36), -1))[1], (sequential_search(sorted(list37), -1))[1], (sequential_search(sorted(list38), -1))[1],
(sequential_search(sorted(list39), -1))[1], (sequential_search(sorted(list40), -1))[1], (sequential_search(sorted(list41), -1))[1],
(sequential_search(sorted(list42), -1))[1], (sequential_search(sorted(list43), -1))[1], (sequential_search(sorted(list44), -1))[1],
(sequential_search(sorted(list45), -1))[1], (sequential_search(sorted(list46), -1))[1], (sequential_search(sorted(list47), -1))[1],
(sequential_search(sorted(list48), -1))[1], (sequential_search(sorted(list49), -1))[1], (sequential_search(sorted(list50), -1))[1],
(sequential_search(sorted(list51), -1))[1], (sequential_search(sorted(list52), -1))[1], (sequential_search(sorted(list53), -1))[1],
(sequential_search(sorted(list54), -1))[1], (sequential_search(sorted(list55), -1))[1], (sequential_search(sorted(list56), -1))[1],
(sequential_search(sorted(list57), -1))[1], (sequential_search(sorted(list58), -1))[1], (sequential_search(sorted(list59), -1))[1],
(sequential_search(sorted(list60), -1))[1], (sequential_search(sorted(list61), -1))[1], (sequential_search(sorted(list62), -1))[1],
(sequential_search(sorted(list63), -1))[1], (sequential_search(sorted(list64), -1))[1], (sequential_search(sorted(list65), -1))[1],
(sequential_search(sorted(list66), -1))[1], (sequential_search(sorted(list67), -1))[1], (sequential_search(sorted(list68), -1))[1],
(sequential_search(sorted(list69), -1))[1], (sequential_search(sorted(list70), -1))[1], (sequential_search(sorted(list71), -1))[1],
(sequential_search(sorted(list72), -1))[1], (sequential_search(sorted(list73), -1))[1], (sequential_search(sorted(list74), -1))[1],
(sequential_search(sorted(list75), -1))[1], (sequential_search(sorted(list76), -1))[1], (sequential_search(sorted(list77), -1))[1],
(sequential_search(sorted(list78), -1))[1], (sequential_search(sorted(list79), -1))[1], (sequential_search(sorted(list80), -1))[1],
(sequential_search(sorted(list81), -1))[1], (sequential_search(sorted(list82), -1))[1], (sequential_search(sorted(list83), -1))[1],
(sequential_search(sorted(list84), -1))[1], (sequential_search(sorted(list85), -1))[1], (sequential_search(sorted(list86), -1))[1],
(sequential_search(sorted(list87), -1))[1], (sequential_search(sorted(list88), -1))[1], (sequential_search(sorted(list89), -1))[1],
(sequential_search(sorted(list90), -1))[1], (sequential_search(sorted(list91), -1))[1], (sequential_search(sorted(list92), -1))[1],
(sequential_search(sorted(list93), -1))[1], (sequential_search(sorted(list94), -1))[1], (sequential_search(sorted(list95), -1))[1],
(sequential_search(sorted(list96), -1))[1], (sequential_search(sorted(list97), -1))[1], (sequential_search(sorted(list98), -1))[1],
(sequential_search(sorted(list99), -1))[1], (sequential_search(sorted(list100), -1))[1]))/100)
print "Ordered Sequential Search took %10.7f seconds to run on average" % (sum(((ordered_sequential_search(sorted(list1), -1))[1], (ordered_sequential_search(sorted(list2), -1))[1], (ordered_sequential_search(sorted(list3), -1))[1], (ordered_sequential_search(sorted(list4), -1))[1],
(ordered_sequential_search(sorted(list5), -1))[1],
(ordered_sequential_search(sorted(list6), -1))[1], (ordered_sequential_search(sorted(list7), -1))[1],
(ordered_sequential_search(sorted(list8), -1))[1], (ordered_sequential_search(sorted(list9), -1))[1],
(ordered_sequential_search(sorted(list10), -1))[1], (ordered_sequential_search(sorted(list11), -1))[1],(ordered_sequential_search(sorted(list12), -1))[1],
(ordered_sequential_search(sorted(list13), -1))[1], (ordered_sequential_search(sorted(list14), -1))[1],(ordered_sequential_search(sorted(list15), -1))[1],
(ordered_sequential_search(sorted(list16), -1))[1], (ordered_sequential_search(sorted(list17), -1))[1],
(ordered_sequential_search(sorted(list18), -1))[1], (ordered_sequential_search(sorted(list19), -1))[1], (ordered_sequential_search(sorted(list20), -1))[1],
(ordered_sequential_search(sorted(list21), -1))[1], (ordered_sequential_search(sorted(list22), -1))[1], (ordered_sequential_search(sorted(list23), -1))[1],
(ordered_sequential_search(sorted(list24), -1))[1], (ordered_sequential_search(sorted(list25), -1))[1], (ordered_sequential_search(sorted(list26), -1))[1],
(ordered_sequential_search(sorted(list27), -1))[1], (ordered_sequential_search(sorted(list28), -1))[1], (ordered_sequential_search(sorted(list29), -1))[1],
(ordered_sequential_search(sorted(list30), -1))[1], (ordered_sequential_search(sorted(list31), -1))[1], (ordered_sequential_search(sorted(list32), -1))[1],
(ordered_sequential_search(sorted(list33), -1))[1], (ordered_sequential_search(sorted(list34), -1))[1], (ordered_sequential_search(sorted(list35), -1))[1],
(ordered_sequential_search(sorted(list36), -1))[1], (ordered_sequential_search(sorted(list37), -1))[1], (ordered_sequential_search(sorted(list38), -1))[1],
(ordered_sequential_search(sorted(list39), -1))[1], (ordered_sequential_search(sorted(list40), -1))[1], (ordered_sequential_search(sorted(list41), -1))[1],
(ordered_sequential_search(sorted(list42), -1))[1], (ordered_sequential_search(sorted(list43), -1))[1], (ordered_sequential_search(sorted(list44), -1))[1],
(ordered_sequential_search(sorted(list45), -1))[1], (ordered_sequential_search(sorted(list46), -1))[1], (ordered_sequential_search(sorted(list47), -1))[1],
(ordered_sequential_search(sorted(list48), -1))[1], (ordered_sequential_search(sorted(list49), -1))[1], (ordered_sequential_search(sorted(list50), -1))[1],
(ordered_sequential_search(sorted(list51), -1))[1], (ordered_sequential_search(sorted(list52), -1))[1], (ordered_sequential_search(sorted(list53), -1))[1],
(ordered_sequential_search(sorted(list54), -1))[1], (ordered_sequential_search(sorted(list55), -1))[1], (ordered_sequential_search(sorted(list56), -1))[1],
(ordered_sequential_search(sorted(list57), -1))[1], (ordered_sequential_search(sorted(list58), -1))[1], (ordered_sequential_search(sorted(list59), -1))[1],
(ordered_sequential_search(sorted(list60), -1))[1], (ordered_sequential_search(sorted(list61), -1))[1], (ordered_sequential_search(sorted(list62), -1))[1],
(ordered_sequential_search(sorted(list63), -1))[1], (ordered_sequential_search(sorted(list64), -1))[1], (ordered_sequential_search(sorted(list65), -1))[1],
(ordered_sequential_search(sorted(list66), -1))[1], (ordered_sequential_search(sorted(list67), -1))[1], (ordered_sequential_search(sorted(list68), -1))[1],
(ordered_sequential_search(sorted(list69), -1))[1], (ordered_sequential_search(sorted(list70), -1))[1], (ordered_sequential_search(sorted(list71), -1))[1],
(ordered_sequential_search(sorted(list72), -1))[1], (ordered_sequential_search(sorted(list73), -1))[1], (ordered_sequential_search(sorted(list74), -1))[1],
(ordered_sequential_search(sorted(list75), -1))[1], (ordered_sequential_search(sorted(list76), -1))[1], (ordered_sequential_search(sorted(list77), -1))[1],
(ordered_sequential_search(sorted(list78), -1))[1], (ordered_sequential_search(sorted(list79), -1))[1], (ordered_sequential_search(sorted(list80), -1))[1],
(ordered_sequential_search(sorted(list81), -1))[1], (ordered_sequential_search(sorted(list82), -1))[1], (ordered_sequential_search(sorted(list83), -1))[1],
(ordered_sequential_search(sorted(list84), -1))[1], (ordered_sequential_search(sorted(list85), -1))[1], (ordered_sequential_search(sorted(list86), -1))[1],
(ordered_sequential_search(sorted(list87), -1))[1], (ordered_sequential_search(sorted(list88), -1))[1], (ordered_sequential_search(sorted(list89), -1))[1],
(ordered_sequential_search(sorted(list90), -1))[1], (ordered_sequential_search(sorted(list91), -1))[1], (ordered_sequential_search(sorted(list92), -1))[1],
(ordered_sequential_search(sorted(list93), -1))[1], (ordered_sequential_search(sorted(list94), -1))[1], (ordered_sequential_search(sorted(list95), -1))[1],
(ordered_sequential_search(sorted(list96), -1))[1], (ordered_sequential_search(sorted(list97), -1))[1], (ordered_sequential_search(sorted(list98), -1))[1],
(ordered_sequential_search(sorted(list99), -1))[1], (ordered_sequential_search(sorted(list100), -1))[1]))/100)
print "Binary Search Iterative took %10.7f seconds to run on average" % (sum(((binary_search_iterative(sorted(list1), -1))[1], (binary_search_iterative(sorted(list2), -1))[1], (binary_search_iterative(sorted(list3), -1))[1], (binary_search_iterative(sorted(list4), -1))[1],
(binary_search_iterative(sorted(list5), -1))[1],
(binary_search_iterative(sorted(list6), -1))[1], (binary_search_iterative(sorted(list7), -1))[1],
(binary_search_iterative(sorted(list8), -1))[1], (binary_search_iterative(sorted(list9), -1))[1],
(binary_search_iterative(sorted(list10), -1))[1], (binary_search_iterative(sorted(list11), -1))[1],(binary_search_iterative(sorted(list12), -1))[1],
(binary_search_iterative(sorted(list13), -1))[1], (binary_search_iterative(sorted(list14), -1))[1],(binary_search_iterative(sorted(list15), -1))[1],
(binary_search_iterative(sorted(list16), -1))[1], (binary_search_iterative(sorted(list17), -1))[1],
(binary_search_iterative(sorted(list18), -1))[1], (binary_search_iterative(sorted(list19), -1))[1], (binary_search_iterative(sorted(list20), -1))[1],
(binary_search_iterative(sorted(list21), -1))[1], (binary_search_iterative(sorted(list22), -1))[1], (binary_search_iterative(sorted(list23), -1))[1],
(binary_search_iterative(sorted(list24), -1))[1], (binary_search_iterative(sorted(list25), -1))[1], (binary_search_iterative(sorted(list26), -1))[1],
(binary_search_iterative(sorted(list27), -1))[1], (binary_search_iterative(sorted(list28), -1))[1], (binary_search_iterative(sorted(list29), -1))[1],
(binary_search_iterative(sorted(list30), -1))[1], (binary_search_iterative(sorted(list31), -1))[1], (binary_search_iterative(sorted(list32), -1))[1],
(binary_search_iterative(sorted(list33), -1))[1], (binary_search_iterative(sorted(list34), -1))[1], (binary_search_iterative(sorted(list35), -1))[1],
(binary_search_iterative(sorted(list36), -1))[1], (binary_search_iterative(sorted(list37), -1))[1], (binary_search_iterative(sorted(list38), -1))[1],
(binary_search_iterative(sorted(list39), -1))[1], (binary_search_iterative(sorted(list40), -1))[1], (binary_search_iterative(sorted(list41), -1))[1],
(binary_search_iterative(sorted(list42), -1))[1], (binary_search_iterative(sorted(list43), -1))[1], (binary_search_iterative(sorted(list44), -1))[1],
(binary_search_iterative(sorted(list45), -1))[1], (binary_search_iterative(sorted(list46), -1))[1], (binary_search_iterative(sorted(list47), -1))[1],
(binary_search_iterative(sorted(list48), -1))[1], (binary_search_iterative(sorted(list49), -1))[1], (binary_search_iterative(sorted(list50), -1))[1],
(binary_search_iterative(sorted(list51), -1))[1], (binary_search_iterative(sorted(list52), -1))[1], (binary_search_iterative(sorted(list53), -1))[1],
(binary_search_iterative(sorted(list54), -1))[1], (binary_search_iterative(sorted(list55), -1))[1], (binary_search_iterative(sorted(list56), -1))[1],
(binary_search_iterative(sorted(list57), -1))[1], (binary_search_iterative(sorted(list58), -1))[1], (binary_search_iterative(sorted(list59), -1))[1],
(binary_search_iterative(sorted(list60), -1))[1], (binary_search_iterative(sorted(list61), -1))[1], (binary_search_iterative(sorted(list62), -1))[1],
(binary_search_iterative(sorted(list63), -1))[1], (binary_search_iterative(sorted(list64), -1))[1], (binary_search_iterative(sorted(list65), -1))[1],
(binary_search_iterative(sorted(list66), -1))[1], (binary_search_iterative(sorted(list67), -1))[1], (binary_search_iterative(sorted(list68), -1))[1],
(binary_search_iterative(sorted(list69), -1))[1], (binary_search_iterative(sorted(list70), -1))[1], (binary_search_iterative(sorted(list71), -1))[1],
(binary_search_iterative(sorted(list72), -1))[1], (binary_search_iterative(sorted(list73), -1))[1], (binary_search_iterative(sorted(list74), -1))[1],
(binary_search_iterative(sorted(list75), -1))[1], (binary_search_iterative(sorted(list76), -1))[1], (binary_search_iterative(sorted(list77), -1))[1],
(binary_search_iterative(sorted(list78), -1))[1], (binary_search_iterative(sorted(list79), -1))[1], (binary_search_iterative(sorted(list80), -1))[1],
(binary_search_iterative(sorted(list81), -1))[1], (binary_search_iterative(sorted(list82), -1))[1], (binary_search_iterative(sorted(list83), -1))[1],
(binary_search_iterative(sorted(list84), -1))[1], (binary_search_iterative(sorted(list85), -1))[1], (binary_search_iterative(sorted(list86), -1))[1],
(binary_search_iterative(sorted(list87), -1))[1], (binary_search_iterative(sorted(list88), -1))[1], (binary_search_iterative(sorted(list89), -1))[1],
(binary_search_iterative(sorted(list90), -1))[1], (binary_search_iterative(sorted(list91), -1))[1], (binary_search_iterative(sorted(list92), -1))[1],
(binary_search_iterative(sorted(list93), -1))[1], (binary_search_iterative(sorted(list94), -1))[1], (binary_search_iterative(sorted(list95), -1))[1],
(binary_search_iterative(sorted(list96), -1))[1], (binary_search_iterative(sorted(list97), -1))[1], (binary_search_iterative(sorted(list98), -1))[1],
(binary_search_iterative(sorted(list99), -1))[1], (binary_search_iterative(sorted(list100), -1))[1]))/100)
print "Binary Search Recursive took %10.7f seconds to run on average" % (sum(((binary_search_recursive(sorted(list1), -1))[1], (binary_search_recursive(sorted(list2), -1))[1], (binary_search_recursive(sorted(list3), -1))[1],
(binary_search_recursive(sorted(list4), -1))[1],
(binary_search_recursive(sorted(list5), -1))[1],
(binary_search_recursive(sorted(list6), -1))[1], (binary_search_recursive(sorted(list7), -1))[1],
(binary_search_recursive(sorted(list8), -1))[1], (binary_search_recursive(sorted(list9), -1))[1],
(binary_search_recursive(sorted(list10), -1))[1], (binary_search_recursive(sorted(list11), -1))[1],(binary_search_recursive(sorted(list12), -1))[1],
(binary_search_recursive(sorted(list13), -1))[1], (binary_search_recursive(sorted(list14), -1))[1],(binary_search_recursive(sorted(list15), -1))[1],
(binary_search_recursive(sorted(list16), -1))[1], (binary_search_recursive(sorted(list17), -1))[1],
(binary_search_recursive(sorted(list18), -1))[1], (binary_search_recursive(sorted(list19), -1))[1], (binary_search_recursive(sorted(list20), -1))[1],
(binary_search_recursive(sorted(list21), -1))[1], (binary_search_recursive(sorted(list22), -1))[1], (binary_search_recursive(sorted(list23), -1))[1],
(binary_search_recursive(sorted(list24), -1))[1], (binary_search_recursive(sorted(list25), -1))[1], (binary_search_recursive(sorted(list26), -1))[1],
(binary_search_recursive(sorted(list27), -1))[1], (binary_search_recursive(sorted(list28), -1))[1], (binary_search_recursive(sorted(list29), -1))[1],
(binary_search_recursive(sorted(list30), -1))[1], (binary_search_recursive(sorted(list31), -1))[1], (binary_search_recursive(sorted(list32), -1))[1],
(binary_search_recursive(sorted(list33), -1))[1], (binary_search_recursive(sorted(list34), -1))[1], (binary_search_recursive(sorted(list35), -1))[1],
(binary_search_recursive(sorted(list36), -1))[1], (binary_search_recursive(sorted(list37), -1))[1], (binary_search_recursive(sorted(list38), -1))[1],
(binary_search_recursive(sorted(list39), -1))[1], (binary_search_recursive(sorted(list40), -1))[1], (binary_search_recursive(sorted(list41), -1))[1],
(binary_search_recursive(sorted(list42), -1))[1], (binary_search_recursive(sorted(list43), -1))[1], (binary_search_recursive(sorted(list44), -1))[1],
(binary_search_recursive(sorted(list45), -1))[1], (binary_search_recursive(sorted(list46), -1))[1], (binary_search_recursive(sorted(list47), -1))[1],
(binary_search_recursive(sorted(list48), -1))[1], (binary_search_recursive(sorted(list49), -1))[1], (binary_search_recursive(sorted(list50), -1))[1],
(binary_search_recursive(sorted(list51), -1))[1], (binary_search_recursive(sorted(list52), -1))[1], (binary_search_recursive(sorted(list53), -1))[1],
(binary_search_recursive(sorted(list54), -1))[1], (binary_search_recursive(sorted(list55), -1))[1], (binary_search_recursive(sorted(list56), -1))[1],
(binary_search_recursive(sorted(list57), -1))[1], (binary_search_recursive(sorted(list58), -1))[1], (binary_search_recursive(sorted(list59), -1))[1],
(binary_search_recursive(sorted(list60), -1))[1], (binary_search_recursive(sorted(list61), -1))[1], (binary_search_recursive(sorted(list62), -1))[1],
(binary_search_recursive(sorted(list63), -1))[1], (binary_search_recursive(sorted(list64), -1))[1], (binary_search_recursive(sorted(list65), -1))[1],
(binary_search_recursive(sorted(list66), -1))[1], (binary_search_recursive(sorted(list67), -1))[1], (binary_search_recursive(sorted(list68), -1))[1],
(binary_search_recursive(sorted(list69), -1))[1], (binary_search_recursive(sorted(list70), -1))[1], (binary_search_recursive(sorted(list71), -1))[1],
(binary_search_recursive(sorted(list72), -1))[1], (binary_search_recursive(sorted(list73), -1))[1], (binary_search_recursive(sorted(list74), -1))[1],
(binary_search_recursive(sorted(list75), -1))[1], (binary_search_recursive(sorted(list76), -1))[1], (binary_search_recursive(sorted(list77), -1))[1],
(binary_search_recursive(sorted(list78), -1))[1], (binary_search_recursive(sorted(list79), -1))[1], (binary_search_recursive(sorted(list80), -1))[1],
(binary_search_recursive(sorted(list81), -1))[1], (binary_search_recursive(sorted(list82), -1))[1], (binary_search_recursive(sorted(list83), -1))[1],
(binary_search_recursive(sorted(list84), -1))[1], (binary_search_recursive(sorted(list85), -1))[1], (binary_search_recursive(sorted(list86), -1))[1],
(binary_search_recursive(sorted(list87), -1))[1], (binary_search_recursive(sorted(list88), -1))[1], (binary_search_recursive(sorted(list89), -1))[1],
(binary_search_recursive(sorted(list90), -1))[1], (binary_search_recursive(sorted(list91), -1))[1], (binary_search_recursive(sorted(list92), -1))[1],
(binary_search_recursive(sorted(list93), -1))[1], (binary_search_recursive(sorted(list94), -1))[1], (binary_search_recursive(sorted(list95), -1))[1],
(binary_search_recursive(sorted(list96), -1))[1], (binary_search_recursive(sorted(list97), -1))[1], (binary_search_recursive(sorted(list98), -1))[1],
(binary_search_recursive(sorted(list99), -1))[1], (binary_search_recursive(sorted(list100), -1))[1]))/100)
|
"""
The Partition Table encoding method is used for a segment that appears in the URI as a pair
of variable-length numeric fields separated by a dot (“.”) character, and in the binary
encoding as a 3-bit “partition” field followed by two variable length binary integers.
The number of characters in the two URI fields always totals to a constant number of
characters, and the number of bits in the binary encoding likewise totals to a constant
number of bits. The Partition Table encoding method makes use of a “partition table.”
The specific partition table to use is specified in the coding table for a given EPC scheme.
"""
from .integer import encode_int, decode_int
def encode_partition(parition_value, c, c_length, d, d_length, c_digits=None, d_digits=None):
"""
The input to the encoding method is the URI portion indicated in the “URI portion” row of
the encoding table. This consists of two strings of digits separated by a dot (“.”) character.
For the purpose of this encoding procedure, the digit strings to the left and right of the dot
are denoted C and D, respectively.
"""
if not isinstance(c, int):
try:
c = int(c)
except ValueError:
raise AttributeError('c must be an integer')
if not isinstance(d, int):
try:
d = int(d)
except ValueError:
raise AttributeError('d must be an integer')
if c.bit_length() > c_length:
raise AttributeError('c must have a bit length less than c_length (%d)' % c_length)
if d.bit_length() > d_length:
raise AttributeError('d must have a bit length less than d_length (%d)' % d_length)
# If no digits are available, set the value to 0 per the EPC standard.
if c_digits == 0:
c = 0
if d_digits == 0:
d = 0
return '{partition:03b}{c}{d}'.format(
partition=parition_value, c=encode_int(c, c_length), d=encode_int(d, d_length)
)
def decode_partition(bin_string, c_length, d_length, start_pos=0):
"""
The input to the decoding method is the bit string identified in the “bit position” row of
the coding table. Logically, this bit string is divided into three substrings, consisting
of a 3-bit “partition” value, followed by two substrings of variable length.
"""
c_end = start_pos + c_length
d_end = c_end + d_length
c = decode_int(bin_string[start_pos:c_end])
d = decode_int(bin_string[c_end:d_end])
return c, d
|
#Purpose: function to make question into tags
#Joe Burg
import string
def parse_question(question):
get_tags = question.strip().split()
parsed_question = []
for tag in get_tags:
clean_tag = tag.translate(string.maketrans("",""),string.punctuation)
parsed_question.append(clean_tag)
#if there is a number in the question make a string with the previous
# word since it may be a class title
numbers = []
for i in range(len(parsed_question)):
if parsed_question[i][0] in '0123456789':
numbers.append(i)
for i in numbers:
new_tag = parsed_question[i-1]+' '+parsed_question[i]
parsed_question.append(new_tag)
#if there is a capital word in a sentance, make a string with the
# previous word
capital_words = []
for i in range(len(parsed_question)):
if parsed_question[i][0] in 'ABCDEFGHIJKLMNOPQRSTUVWXYZ':
capital_words.append(i)
for i in capital_words: #may need to add code for more than 2 words
if i>0:
if parsed_question[i-1][0] in 'ABCDEFGHIJKLMNOPQRSTUVWXYZ':
new_tag = parsed_question[i-1]+' '+parsed_question[i]
parsed_question.append(new_tag)
return parsed_question
|
#Purpose: check question's tags against users list to see who it's relevant to
#Joe Burg
from parse_question import parse_question
from import_data import import_data
###################################################################
question = raw_input('What is your question: ')
#import the user IDs
user_IDs = []
with open('user_IDs.txt') as inputfile:
for line in inputfile:
user_IDs.append(line.strip())
#using the user IDs, use the import_data function to access each
# user's tag file and organize all the user's data into a dictionary
# with the user's ID as the key and their data as [[classes],[tags]]
user_classes_and_tags_dictionary = import_data(user_IDs)
###################################################################
#check if the question's tags are in the user's data
parsed_question = parse_question(question)
for user in user_IDs:
class_guage=0
tag_guage=0
user_classes = user_classes_and_tags_dictionary[user][0]
user_tags = user_classes_and_tags_dictionary[user][1]
for tag in parsed_question:
if tag in user_classes:
class_guage = class_guage + 1
if tag in user_tags:
tag_guage = tag_guage + 1
if class_guage > 0:
print 'This question is relevant to '+user+"\'s classes."
in_class = True
else:
in_class = False
if tag_guage > 0:
print 'This question is relevant to '+user+"\'s tags."
in_tags = True
else:
in_tags = False
print ''
print 'All done!'
|
#Purpose: parse a wiki page for tags
#Joe Burg
import re
############################################################################
def digit_check(word):
for i in range(len(word)):
if word[i] in '0123456789':
return False
else:
return True
############################################################################
filename = raw_input('Provide the filename: ')
filtered_words = re.findall(r'\w+', open('common_word_filter_1000.txt').read().lower())
scraped_words = re.findall(r'\w+', open(filename).read().lower())
print scraped_words[:100]
tags = []
for word in scraped_words:
if word not in filtered_words:
if word.isdigit()==False: #remove numbers
if digit_check(word)==True:
if word[-2:] != 'ly': #remove adverbs
if word not in tags: #remove repeats
tags.append(word)
print ''
print len(tags)
print ''
print tags[:100]
###############################################################################
##dataFile = open('tags_with_'+str(cutoff)+'_filter.txt', 'w'x)
##for eachitem in tags:
## dataFile.write("".join(eachitem)+'\n')
##
##dataFile.close()
##
##print "All done!"
|
#Purpose: parse a wiki page for tag; filter common words
#Joe Burg
import re
############################################################################
number = input('What number file is this? ')
all_words = []
for i in range(100):
print 'Scanning page '+str(i)
if i<10:
filename = 'wiki_0'+str(i)
else:
filename = 'wiki_'+str(i)
words = re.findall(r'\w+', open(filename).read().lower())
all_words.append(words)
#############################################################################
dataFile = open('all_words_'+str(number)+'.txt', 'w')
for eachitem in all_words:
dataFile.write(" ".join(eachitem)+'\n')
dataFile.close()
print "All done!"
|
"""
An Doan
Lopez Gerardo
CECS 575 - Assignment 1
September 17, 2021
"""
# Node class
class Node:
def __init__(self, data_value = 0):
self.data = data_value
self.left_child = None
self.right_child = None
# accessor funtions for Node class
def get_data(self):
return self.data
def get_left_child(self):
return self.left_child
def get_right_child(self):
return self.right_child
# mutator functions for Node class
def set_data(self, value):
self.data = value
def set_left_child(self, new_node):
self.left_child = new_node
def set_right_child(self, new_node):
self.right_child = new_node
# method to swap data inside two nodes
def swap_node_values(self, new_node):
swap_value = self.data
self.data = new_node.get_data()
new_node.set_data(swap_value)
|
class Stack:
def __init__(self):
self.len = 0
self.list = []
def push(self, num):
self.list.append(num)
self.len += 1
def pop(self):
if self.size() == 0:
return -1
pop_result = self.list[self.len - 1]
del self.list[self.len - 1]
self.len -= 1
return pop_result
def size(self):
return self.len
def empty(self):
return 1 if self.len == 0 else 0
def top(self):
return self.list[-1] if self.size() != 0 else -1
num = int(input())
stack = Stack()
while(num > 0):
num -= 1
input_split = input().split()
op = input_split[0]
if op == "push":
stack.push(input_split[1])
elif op == "pop":
print(stack.pop())
elif op == "size":
print(stack.size())
elif op == "empty":
print(stack.empty())
elif op == "top":
print(stack.top())
else:
print("unacceptable op")
print("end")
|
# S3C2 Laurel Kuang
def Events():
print("A:PressStartButton B:EnterPin C:ActivateSensor")
def PressStartButton(state):
if state==SystemInactive:
state=SystemActive
print(state)
return state
def EnterPin(state, timer):
if state==SystemActive:
state=SystemInactive
elif state==AlertMode:
state=SystemInactive
timer=0
elif state==AlarmBellRinging:
state=SystemInactive
print(state)
return state
return timer
def ActivateSensor(state):
if state==SystemActive:
state=AlertMode
print(state)
return state
def 2MinutesPass():
for i in range(240):
print(end="")
def Timer(state, timer):
if state==AlertMode:
timer=timer+1
return timer
def Bell(state, timer):
if state==AlertMode and timer==2:
state=AlarmBellRinging
print(state)
timer=0
state=SystemInactive
Events()
Event=input("Enter the event please.")
if Event=="A":
state=PressStartButton(state)
elif Event=="B":
state,timer=EnterPin(state, timer)
elif Event=="C":
state=ActivateSensor(state)
2MinutesPass()
timer=Timer(state, timer)
state=Bell(state, timer)
|
# S3C2 Laurel Kuang
def BubbleSort(List):
while len(List)>0:
for i in range(len(List)-1):
if List[i]>List[i+1]:
List[i],List[i+1]=List[i+1],List[i]
len(List)=len(List)-1
return List
|
import json
# Python script showing use of json package
def get_string():
# Creating and initializing variables
file = "myScript.py"
name = "Osebi Adams"
Id = "HNG-04874"
email = "[email protected]"
language = "Python"
status = "Pass"
output = ("Hello World, this is %s with HNGi7 ID %s using %s for stage 2 task. %s" % (
name, Id, language, email))
# Key: value mapping in a dict and appending it to a list
data = {'myData': []}
data['myData'].append({
"file": file,
"output": output,
"name": name,
"id": Id,
"email": email,
"language": language,
"status": status
})
# Conversion to JSON done by dumps() function
data = json.dumps(data, indent=4)
# Parse myData
data = json.loads(data)
for i in data['myData']:
output = (i['output'])
print(output)
return output
# print(get_string())
get_string() |
temp = eval(input('Enter a temperature in Celsius: '))
fr = 9/5*temp +32
print("test input",fr)
print("test if")
if fr > 10:
print('fr>10',fr)
elif fr < 10:
print('fr<10',fr)
|
import time
import os
prime_numbers = [2]
number_to_check = 3
not_prime = False
start_time_again = True
number_of_prime = 0
primes_a_second = 0
print("Prime --> 1")
print("Prime --> 2")
while True:
#os.system("clear")
if start_time_again == True:
start = time.time()
start_time_again = False
for prime in prime_numbers:
if number_to_check != prime:
if number_to_check % prime == 0:
not_prime = True
break
if not_prime == False:
number_of_prime += 1
primes_a_second +=1
prime_numbers.append(number_to_check)
print("Prime #",number_of_prime," --> ",number_to_check, sep='')
not_prime = False
number_to_check += 2
if start >= 1:
start_time_again = True
#print(primes_a_second)
primes_a_second = 0
|
#!/usr/bin/env python
test_string = [ "foo", "bar", "baz", "quux" ]
#print("\t".join( test_string))
def print_sep( a_string, sep = "\t" ):
print( sep.join( a_string ) )
print_sep( test_string )
print_sep( test_string, " - " ) |
from sys import argv
#list container
lista = ["Red", "Black", "White", "Gray", "Green" ]
##List Comp.
lista2 = [i for i in range(1, 101) if i%2==0 ]
listaEvenOdd = [ [i for i in range(1, 101) if i%2==0 ], [i for i in range(1, 101) if i%2!=0 ] ]
print(listaEvenOdd)
if __name__ == "__main__":
print( f'programName: {argv[0]}\n' )
print( lista, len( lista ) ) #Size of a list
## Manual
# print( lista[0] )
# print( lista[1] )
# print( lista[2] )
##...
##...
##Auto
index = 0
while( index < len( lista ) ):
print( f'index:{index}, value: {lista[index]} ' )
index = index + 1
print("--------------------")
for index in range(0, len( lista) ):
print( f'index:{index}, value: {lista[index]} ') |
#Image Processing Module
#Task1:Access Pixels
#28/09/2020
#Laura Whelan
######### import the necessary packages: #########
import cv2
import numpy as np
from matplotlib import pyplot as plt
from matplotlib import image as image
import easygui
######### Task #########
#1.Read in any image (this is done as direct input)
I=cv2.imread('landscape.jpg')
#2.Convert this image to YUV
YUV = cv2.cvtColor(I, cv2.COLOR_BGR2YUV)
#3.Exctract the Y Channel (luminance)
y=YUV[:,:,0]
#4.Convert the original image to grayscale (intensity)
G = cv2.cvtColor(I, cv2.COLOR_BGR2GRAY)
#5.Show the two on the screen using OpenCV's imshow function
cv2.imshow("Luminance", y)
cv2.imshow("Greyscale", G)
cv2.waitKey(0)
#6.Show the two on the screen side by side with the intensity using matplotlibs subplot function
# Showing an image on the screen (MatPlotLib):
plt.figure(1)
plt.subplot(1,2,1)
plt.imshow(y, cmap='gray')
plt.title('Luminance')
plt.xticks([])
plt.yticks([])
plt.subplot(1,2,2)
plt.imshow(G,cmap='gray')
plt.title('Grayscale')
plt.xticks([])
plt.yticks([])
plt.show()
|
import numpy as np
class Ordered_Vector:
def __init__(self, capacity):
self.capacity = capacity
self.last_position = -1
self.vals = np.empty(self.capacity, dtype=int)
# O(n)
def display(self):
if self.last_position == -1:
print('The vector is empty')
else:
for i in range(self.last_position + 1):
print(i, ' - ', self.vals[i])
# O(n)
#When inserting items in an already ordered vector
#you must take into acount the correct position to include the item.
#
def including(self, val):
if self.last_position == self.capacity - 1:
print('Maximum capacity reached')
return
#In which position to include the new element?
position = 0
for i in range(self.last_position + 1):
position = i
if self.vals[i] > val:
break
if i == self.last_position:
position = i + 1
x = self.last_position
while x>= position:
self.vals[x + 1] = self.vals[x]
x -= 1
self.vals[position] = val
self.last_position += 1
# O(n)
#Linear search
def linsearch (self, val):
for i in range(self.last_position + 1):
if self.vals[i] > val:
return -1
if self.vals[i] == val:
return i
if i == self.last_position:
return -1
# O(log n)
def binsearch (self, val):
lower_limit = 0
upper_limit = self.last_position
while True:
current_position = int((lower_limit + upper_limit) / 2)
# If it was found on the first attempt:
if self.vals[current_position] == val:
return current_position
# If the value was not found:
elif lower_limit > upper_limit:
return -1
# Dividing the limits
else:
# Lower limit
if self.vals[current_position] < val:
lower_limit = current_position + 1
# Upper Limit
else:
upper_limit = current_position - 1
# O(n)
def excluding(self, val):
position = self.searching(val)
if position == -1:
return -1
else:
for i in range(position, self.last_position):
self.vals[i] = self.vals[i + 1]
self.last_position -= 1
vector = Ordered_Vector(10)
vector.display()
print("Including items in the vector")
vector.including(8)
vector.including(9)
vector.including(4)
vector.including(1)
vector.including(5)
vector.including(7)
vector.including(11)
vector.including(13)
vector.including(2)
vector.display()
#Executing binary search:
print("executing binary search")
vector.binsearch(7)
vector.binsearch(5)
vector.binsearch(13)
vector.binsearch(20)
vector.display()
|
def hist(sample):
"""Plots a histogram based on a user specified origin and bandwidth.
Plots a histogram, a jagged density estimator, of a given sample with a user specified
origin and bandwidth, after checking if the sample is valid.
ARGS:
sample: data desired to create a histogram for, entered as a one-dimensional numpy
array
origin: any real number
bandwidth: any number greater than 0
RETURNS:
A histogram plot is returned based on the sample given, the chosen origin and the specified
bandwidth.
"""
import numpy as np
import math
import matplotlib.pyplot as plt
import sys
# Test sample
try:
sample = np.array(sample)
except:
print "That is not a valid sample."
sys.exit()
isArray = True
if len(sample.shape) != 1:
isArray = False
for u in sample:
try:
float(u)
except:
isArray = False
if isArray == False:
print "That is not a valid sample."
sys.exit()
# Choose origin
while True:
o = raw_input("Origin? ")
try:
o = float(o)
break
except:
pass
# Choose bandwidth
while True:
h = raw_input("Bandwidth [>0]? ")
try:
h = float(h)
if h > 0:
break
except:
pass
# Identify x-axis range
j_max = int(math.ceil((max(sample)-o)/h))
j_min = int(math.ceil((min(sample)-o)/h))
bins = np.arange(j_min,j_max)*h+o
# Define histogram density estimate and create plot
y_values = np.zeros(len(bins)-1)
for i in range(0,len(y_values)):
for x in sample:
if bins[i] <= x:
if x < bins[i+1]:
y_values[i] += 1
y_values[i] = y_values[i]/float(len(sample)*h)
plt.plot(bins[:-1],y_values)
plt.title("Histogram Density Estimate")
plt.xlabel("X")
plt.ylabel("Density")
plt.show()
|
import math
import time
def timing_average(func):
def wrapper(x, y):
t0 = time.time()
res = func(x, y)
t1 = time.time()
print("It took {} seconds for {} to calculate the average".format(t1-t0, func.__name__))
return res
return wrapper
def check_positive(func):
def func_wrapper(x, y):
if x<0 or y<0:
raise Exception("Both x and y have to be positive for {} to work".format(func.__name__))
res = func(x,y)
return res
return func_wrapper
@timing_average
@check_positive
def average(x, y):
return (x + y)/2
@timing_average
@check_positive
def geom_average(x, y):
return math.sqrt(x*y)
x = 9
y = 25
print("The average between {} and {} is {}".format(x, y, average(x, y)))
print("The geometrical average between {} and {} is {}".format(x, y, geom_average(x, y))) |
class Tile(object):
"""Class for map Tiles"""
width = 70 # tile width in pixels
def __init__(self, x, y, height, fixed):
super(Tile, self).__init__()
# self.rotate = rotate
self.speed = speed
self.x = x
self.y = y
self.height = height
self.fixed = fixed
def getCollision(self):
"""Summary
Returns:
x: Initial x
y: Initial y
dx: Final x
dy: Final y
"""
return (self.x, self.y, self.x + self.width, self.y + self.height)
|
# -*- coding: utf-8 -*-
__author__ = "karnikamit"
import re
def replace1(match):
return match.group(1)+'_'+match.group(2).lower()
def convert_to_snake_case(var):
return re.sub(r'(.)([A-Z])', replace1, var)
def replace2(match):
return match.group(2).upper()
def cov_back_to_camel_case(var_name):
s2 = re.sub('([_])(.)', replace2, var_name)
return s2
if __name__ == '__main__':
name = 'camelCaseCasesYo'
snake_case = convert_to_snake_case(name)
print 'original: %s' % name
print 'converted: %s' % snake_case
print 'conv back: %s' % cov_back_to_camel_case(snake_case)
|
__author__ = 'karnikamit'
'''
Move spaces in a given string to the front
'''
def move(string):
count = 0
for character in string:
if character == ' ':
count += 1
string = string.replace(" ", "")
spaces = " "*count
# This is done because 'str' object does not support item assignment
temp_str = list(string)
temp_str.insert(0, spaces)
string = ''.join(temp_str)
return string
s = "move these spaces to beginning"
print s
print move(s) |
# -*- coding: utf-8 -*-
__author__ = 'karnikamit'
'''
given an array, find the largest good subset.
A good subset is when the integers in the selected subset, divides every other number.
ie array[i]%array[j] == 0 or array[j]%array[i] == 0
'''
size_of_array = input("Size of array")
array = []
for i in xrange(size_of_array):
array.append(input("array element"))
def mod(a, b):
if a > b:
return a % b
else:
return b % a
def get_sub_lists(alist):
sub_sets = []
for i in xrange(len(alist)):
pivot_value = alist[i]
temp_array = alist[i+1:]
sub_list = get_sub_set(pivot_value, temp_array)
if sub_list:
sub_sets.append((sub_list, len(sub_list)))
return sub_sets
def get_sub_set(pivot, a_list):
if not a_list:
return []
sub_list = [pivot]
for i in a_list:
if mod(i, pivot) == 0:
sub_list.append(i)
else:
return -1
return sub_list
if __name__ == '__main__':
sub_lists = get_sub_lists([4, 8, 2, 3]) # array of tupples==[([], len([])),...]
if sub_lists:
print len(sorted(sub_lists, key=lambda x: x[1]).pop()[0])
print None
|
# -*- coding: utf-8 -*-
__author__ = 'karnikamit'
cases = int(raw_input())
for _ in xrange(cases):
ip_string = raw_input()
if ip_string == ip_string[::-1]:
print 'YES {}'.format('EVEN' if len(ip_string) % 2 == 0 else 'ODD')
else:
print 'NO'
|
__author__ = 'karnikamit'
def merge(x, y):
"""
:param x: sorted list
:param y: sorted list
:return: merge both sorted list to one new list
"""
result = []
i = 0
j = 0
while True:
if i >= len(x): # If xs list is finished,
result.extend(y[j:]) # Add remaining items from y
return result
if j >= len(y):
result.extend(x[i:])
return result
# Both lists still have items, copy smaller item to result.
if x[i] <= y[j]:
result.append(x[i])
i += 1
else:
result.append(y[j])
j += 1
if __name__ == '__main__':
a = range(10)
b = range(20, 30)
print merge(a, b)
|
# -*- coding: utf-8 -*-
__author__ = 'karnikamit'
'''
https://www.hackerearth.com/practice/data-structures/hash-tables/basics-of-hash-tables/practice-problems/algorithm/pair-sums/
'''
N, K = map(int, raw_input().split(' '))
array = map(int, raw_input().split(' '))
assert len(array) == N
def pair_sum(array, k):
"""
:param array: array of integers
:param k: sum required
:return: pair of integers
"""
for pivot in array:
p_index = array.index(pivot)
for elem in array[p_index:]:
if pivot + elem == k:
return 'Yes'
else:
return 'No'
print pair_sum(array, K)
|
# -*- coding: utf-8 -*-
__author__ = 'karnikamit'
def find_max_sub_array_sum(array, mod_operand):
current, result = array[0], 0
for i in xrange(1, len(array)-1):
current = max(array[i], current+array[i])
mod_sum = current % mod_operand
if mod_sum > result:
result = mod_sum
return result
print find_max_sub_array_sum([3,3,9,9,5], 7)
|
__author__ = 'karnikamit'
a1 = [1, 2, 3, 4, 5]
b1 = ['a', 'b', 'c', 'd', 'e']
def create_dict(a, b):
"""
:param a:
:param b:
:return:this function creates a dictionary from given two lists,
it prepares a dict by considering the length of the lists.
it prepares the dict only to the items present in the 1st list 'a'.
If length of list 'b' is less than the length of list 'a',
then it appends 'None' to 'b' to make its length equal to the length of list 'a'.
"""
d = dict()
if len(a)-len(b) != 0:
for i in range(len(a)-len(b)):
b.append(None)
for j in range(len(a)):
d[a[j]] = b[j]
return d
def dict_create(keys, values):
return dict(zip(keys, values + [None] * (len(keys) - len(values))))
|
__author__ = 'karnikamit'
import sys
from time import sleep
def stack():
work = ['1. Add to Stack', '2. Pop from stack', '3. Print stack', '4. Exit']
stack_list = list()
flag = True
while flag:
for w in work:
print w
q = int(raw_input('What do you want to do? '))
if q == 1:
item = str(raw_input("Add "))
stack_list.append(item)
elif q == 2:
stack_list.pop(stack_list.index(str(raw_input('item to pop- '))))
elif q == 3:
for i in stack_list:
print i
elif q == 4:
# for python 2.7
dot = '...'
for c in dot:
print c,
sys.stdout.flush()
sleep(1)
print 'Bye'
# for python 3.3
# for c in msg:
# sys.stdout.write(c)
# sys.stdout.flush()
# sleep(1)
flag = False
else:
print 'Asshole!'
exit(0)
|
# -*- coding: utf-8 -*-
__author__ = 'karnikamit'
'''
https://www.hackerearth.com/practice/data-structures/hash-tables/basics-of-hash-tables/practice-problems/algorithm/xsquare-and-double-strings-1/
'''
def is_double_string(s):
"""
:param s: special string S consisting of lower case English letters.
:return: Yes if string s can be converted to double string else No
"""
string_list = list(s)
string_length = len(string_list)
if string_length >= 2:
if string_length == 2:
return 'Yes' if string_list[0] == string_list[1] else 'No'
else:
if not len(string_list) % 2:
mid = string_length/2
A = string_list[:mid]
B = string_list[mid:]
if A == B:
return 'Yes'
else:
A = {k: v for k, v in enumerate(A)}
a = A.copy()
B = {k: v for k, v in enumerate(B)}
for key in a:
if A[key] != B[key]:
del A[key]
del B[key]
A = ''.join(A.values())
B = ''.join(B.values())
return 'Yes' if A == B else 'No'
else:
temp = {}
{temp.setdefault(i, []).append(i) for i in string_list}
res = filter(lambda x: len(temp[x]) % 2, temp)
if res:
for i in res:
string_list.remove(i)
new_string = ''.join(string_list)
return is_double_string(new_string)
return 'No'
cases = int(raw_input())
for _ in xrange(cases):
print is_double_string(raw_input())
|
# import os
# list1= ['Google', 'Taobao', 'Runoob', 'Baidu']
# tuple1=tuple(list1)
# print(list1)
# print(tuple1)
# basket = {'apple', 'orange', 'apple', 'pear', 'orange', 'banana'}
# print(type(baske
# !/usr/bin/python3
# -*- coding: UTF-8 -*-
# Filename : test.py
# author by : www.runoob.com
# Python 斐波那契数列实现
# 获取用户输入数据
# nterms = int(input("你需要几项?"))
#
# # 第一和第二项
# n1 = 0
# n2 = 1
# count = 2
#
# # 判断输入的值是否合法
# if nterms <= 0:
# print("请输入一个正整数。")
# elif nterms == 1:
# print("斐波那契数列:")
# print(n1)
# else:
# print("斐波那契数列:")
# print(n1, ",", n2, end=" , ")
# while count < nterms:
# nth = n1 + n2
# print(nth, end=" , ")
# # 更新值
# n1 = n2
# n2 = nth
# count += 1
# url = "xxxxx"
# str000='/home/aqonvs.jpg'
# newname = str000.split('/')
# print (newname[len(newname)-1])
# files = {'file':(newname,open('/home/aqonvs.jpg','rb'),'image/jpg')}
# import urllib.request
# keyworld="渴望飞的鱼"
# key=urllib.request.quote(keyworld)
# url="https://www.baidu.com/s?wd="+key
# print(url)
# req=urllib.request.Request(url)
# data=urllib.request.urlopen(req).read()
# fhandle=open('D:/爬虫/抓取文件/2018110205.html','wb')
# fhandle.write(data)
#python 火车票信息的查询
import requests,re,json
from prettytable import PrettyTable
from colorama import init,Fore
# from content import chezhan_code,chezhan_names
# self.browser = browser
session = requests.session()
# pictor = 'https://kyfw.12306.cn/passport/captcha/captcha-image?login_site=E&module=login&rand=sjrand'
# verify_url = 'http://littlebigluo.qicp.net:47720/' # 验证码识别网址,返回识别结果
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.132 Safari/537.36',
'Referer': 'http://littlebigluo.qicp.net:47720/'
}
url="https://kyfw.12306.cn/otn/resources/js/framework/station_name.js?station_version=1.9110"
response = requests.get(url,verify=False)
#将车站的名字和编码进行提取
chezhan_name = re.findall(r'([\u4e00-\u9fa5]+)\|([A-Z]+)', response.text)
chezhan_code = dict(chezhan_name)
chezhan_names = dict(zip(chezhan_code.values(),chezhan_code.keys()))
class Colored(object):
def yeah(self,s):
return Fore.LIGHTCYAN_EX + s + Fore.RESET
def green(self,s):
return Fore.LIGHTGREEN_EX + s + Fore.RESET
def yellow(self,s):
return Fore.LIGHTYELLOW_EX + s + Fore.RESET
def white(self,s):
return Fore.LIGHTWHITE_EX + s + Fore.RESET
def blue(self,s):
return Fore.LIGHTBLUE_EX + s + Fore.RESET
# txt=requests.get(url).text
# inf=txt[:-2].split("@")[1:]
# stations={}
# for record in inf:
# rlist=record.split("|")
# stations[rlist[2]]={"cn":rlist[1],"qp":rlist[3],"jp":rlist[4]} #把车站编码当作key
# print(stations)
# def getcode(t):
# while True:
# s1=input("%s站:"%t)
# r1=[]
# for id,station in stations.items():
# if s1 in station.values():
# r1.append((id,station))
# if r1:
# break
# print("没有这个车站。")
# print("请重新输入。")
# if len(r1)==1:
# sid=r1[0][0]
# else:
# print("你需要在以下车站里选择:")
# for i in range(len(r1)):
# print(i+1,r1[i][1]["cn"])
# sel=int(input("你的选择是:"))-1
# sid=r1[sel][0]
# return sid
fromstation=chezhan_code[input("请输入起始站点:\n")]
tostation=chezhan_code[input("请输入目的站点:\n")]
chufatime=input("请输入时间(如2019-01-22):\n")
url='https://kyfw.12306.cn/otn/leftTicket/queryA?leftTicketDTO.train_date={}&leftTicketDTO.from_station={}&leftTicketDTO.to_station={}&purpose_codes=ADULT'.format(chufatime,fromstation,tostation)
print(url)
html=requests.get(url,headers=headers).content
ai = json.loads(html)
table = PrettyTable(
[" 车次 ", "出发车站", "到达车站", "出发时间", "到达时间", " 历时 ", "商务座", " 一等座", "二等座", "高级软卧", "软卧", "动卧", "硬卧", "软座", "硬座",
"无座", "其他", "备注"])
result=[]
for i in ai['data']['result']:
name = [
"station_train_code",
"from_station_name",
"to_station_name",
"start_time",
"arrive_time",
"lishi",
"swz_num",
"zy_num",
"ze_num",
"dw_num",
"gr_num",
"rw_num",
"yw_num",
"rz_num",
"yz_num",
"wz_num",
"qt_num",
"note_num"
]
data = {
"station_train_code": '',
"from_station_name": '',
"to_station_name": '',
"start_time": '',
"arrive_time": '',
"lishi": '',
"swz_num": '',
"zy_num": '',
"ze_num": '',
"dw_num": '',
"gr_num": '',
"rw_num": '',
"yw_num": '',
"rz_num": '',
"yz_num": '',
"wz_num": '',
"qt_num": '',
"note_num": ''
}
# 将各项信息提取并赋值
item = i.split('|') # 使用“|”进行分割
data["station_train_code"] = item[3] # 获取车次信息,在3号位置
data["from_station_name"] = item[6] # 始发站信息在6号位置
data["to_station_name"] = item[7] # 终点站信息在7号位置
data["start_time"] = item[8] # 出发时间在8号位置
data["arrive_time"] = item[9] # 抵达时间在9号位置
data["lishi"] = item[10] # 经历时间在10号位置
data["swz_num"] = item[32] or item[25] # 特别注意,商务座在32或25位置
data["zy_num"] = item[31] # 一等座信息在31号位置
data["ze_num"] = item[30] # 二等座信息在30号位置
data["gr_num"] = item[21] # 高级软卧信息在21号位置
data["rw_num"] = item[23] # 软卧信息在23号位置
data["dw_num"] = item[27] # 动卧信息在27号位置
data["yw_num"] = item[28] # 硬卧信息在28号位置
data["rz_num"] = item[24] # 软座信息在24号位置
data["yz_num"] = item[29] # 硬座信息在29号位置
data["wz_num"] = item[26] # 无座信息在26号位置
data["qt_num"] = item[22] # 其他信息在22号位置
data["note_num"] = item[1] # 备注信息在1号位置
color = Colored()
data["note_num"] = color.white(item[1])
# 如果没有信息,那么就用“-”代替
for pos in name:
if data[pos] == "":
data[pos] = "-"
tickets = []
cont = []
cont.append(data)
for x in cont:
tmp = []
for y in name:
if y == "from_station_name":
s = color.green(chezhan_names[data["from_station_name"]])
tmp.append(s)
elif y == "to_station_name":
s = color.yeah(chezhan_names[data["to_station_name"]])
tmp.append(s)
elif y == "start_time":
s = color.green(data["start_time"])
tmp.append(s)
elif y == "arrive_time":
s = color.yeah(data["arrive_time"])
tmp.append(s)
elif y == "station_train_code":
s = color.yellow(data["station_train_code"])
tmp.append(s)
else:
tmp.append(data[y])
tickets.append(tmp)
for ticket in tickets:
table.add_row(ticket)
print(table)
|
#1.1 现有字典 dict={‘a’:24,‘g’:52,‘i’:12,‘k’:33}请按字典中的 value 值进行排序?
dict={'a':'24','g':'52','i':'12','k':'33'}
print(sorted(dict.items(),key=lambda x:x[1]))
#请反转字符串“sStr”
print("sStr"[::-1])
# 将字符串”k:1|k1:2|k2:3|k3:4”,处理成Python字典:{k:1, k1:2, … } # 字 典里的K作为字符串处理
str1 = "k:1|k1:2|k2:3|k3:4"
def srt2dict(str1):
dict={}
for items in str1.split("|"):
k,v=items.split(":")
dict[k]=v
return dict
print(srt2dict(str1))
#请按alist中元素的age由大到小排序
alist=[{'name':'a','age':10},{'name':'b','age':20},{'name':'c','age':30}]
# alist=[{'name':'a','age':10},{'name':'b','age':20},{'name':'c','age':30}]
def sort_by_age(alist):
return sorted(alist,key=lambda x:x["age"],reverse=True)
print(sort_by_age(alist))
#写一个列表生成式,产生一个公差为11的等差数列
print([x*11 for x in range(10)])
#给定两个列表,怎么找出他们相同的元素和不同的元素?
list1 = [1,2,3]
list2 = [3,4,5]
set1 = set(list1)
set2 = set(list2)
print(set1&set2)
print(set1^set2)
#请写出一段Python代码实现删除一个list里面的重复元素?
l1 = ['b','c','d','b','c','a','a']
print(list(set(l1)))
#如果想要保持他们原来的排序:用list类的sort方法:
l1 = ['b','c','d','b','c','a','a']
# print(list(set(l1)))
l2 = list(set(l1))
l2.sort(key=l1.index)
print(l2)
#也可以这样写:
l1 = ['b','c','d','b','c','a','a']
l2 = sorted(set(l1),key=l1.index)
print(l2)
#也可以使用遍历:
l1 = ['b','c','d','b','c','a','a']
l2 = []
for i in l1:
if not i in l2:
l2.append(i)
print(l2)
#新的默认列表只在函数被定义的那一刻创建一次。当extendList被没有指定特定参数list调用时,这组list的值
#随后将被使用。这是因为带有默认参数的表达式在函数被定义的时候被计算,不是在调用的时候被计算。
def extendlist(val, list=[]):
list.append(val)
return list
list1 = extendlist(10)
list2 = extendlist(123, [])
list3 = extendlist('a')
print("list1 = %s" %list1)
print("list2 = %s" %list2)
print("list3 = %s" %list3)
#获取1~100被7整除的偶数?
def A():
L=[]
for i in range(1,100):
if i%7==0:
L.append(i)
return L
print(A())
#快速去除列表中的重复元素
# In [4]: a = [11,22,33,33,44,22,55]
# In [5]: set(a)
# Out[5]: {11, 22, 33, 44, 55}
#交集:共有的部分
a = {71,72,73,74,75}
b = {72,74,75,76,77}
a&b
#{72, 74, 75}
#并集:总共的部分
a = {21,22,23,24,25}
b = {22,24,25,26,27}
a | b
#{21, 22, 23, 24, 25, 26, 27}
#差集:另一个集合中没有的部分
a = {51,52,53,54,55}
b = {52,54,55,56,57}
b - a
#{66, 77}
#对称差集(在a或b中,但不会同时出现在二者中)
a = {91,92,93,94,95}
b = {92,94,95,96,97}
a ^ b
#{11, 33, 66, 77} |
ipk = float(input("Masukkan IPK: "))
if (ipk>3.51 and ipk<4.00):
print("Dengan pujian")
elif (ipk>2.76 and ipk<3.50):
print("Sangat memuaskan")
elif (ipk>2.00 and ipk<2.75):
print("Memuaskan")
1.start
2.input (ipk)
3.if ipk>3.51 and ipk<4.00:
4. output (Dengan pujian)
5.elif ipk>2.76 and ipk<3.50:
6. output(Sangat memuaskan)
7.elif ipk>2.00 and ipk<2.75:
8. output(Memuaskan)
9.end
|
import numpy as np
numeros = np.array([1, 3.5])
print(numeros)
numeros += 3
print(numeros)
|
idades = [15, 87, 32, 65, 56, 32, 49, 37]
#idades = sorted(idades)
#print(sorted(idades, reverse=True))
# print(list(reversed(idades)))
idades.sort()
idades= list(reversed(idades))
print(idades)
|
def cons(x,xs=None):
return(x,xs)
def lista(*xs):
if not xs:
return None
return cons(xs[0],lista(*xs[1:]))
def head(xs):
return xs[0]
def tail(xs):
return xs[1:]
def is_empty(xs):
return xs is None
def last(xs):
if is_empty(tail(xs)):
return cons(head(xs))
return last(tail(xs))
def concat(xs,yx):
if is_empty(xs):
return ys
return cons( head(xs),concat(tail(xs),ys) )
def reverse(xs):
if is_empty(xs):
return xs
return concat( reverse(tail(xs)),cons(head(xs)) )
a=lista(1,2,3,4,5,6)
print lista(a)
def tupla(x,xs):
return xs[x]
def item(n,x):
return x[n]
def neg(n):
if n<0:
return n
return -n
def take(n,xs):#trocar nome
if n==1:
return xs[0]
return (take(n-1,xs),item(0,tupla(n-1,xs)))
print take(2,a)
def drop(n,xs):#trocar nome
print "aa", xs
if n==1:
return xs[0]
return ( xs[0] ,drop(n-1,tupla(-1,xs)) )
print drop(3,reverse(a))
|
def triplets(arr):
n = len(arr)
sum,sum2,count=0,0,0
for i in range(n):
sum = arr[0]
arr.pop(0)
for j in range(n-1):
sum2 = arr[j]+arr[j-1]
if(sum2 == sum):
count +=1
arr.append(sum)
return count
T = int(input())
lst = []
for i in range(T):
x = int(input())
for j in range(x):
lst.append(int(input()))
p = triplets(lst)
if p==0:
print("-1")
else:
print(p)
|
#Să se afişeze cel mai mare număr par dintre doua numere introduse în calculator.
n1=int(input("introduceti nr 1: "))
n2=int(input("introduceti nr 2: "))
if ((n1%2==0)and(n2%2==0)):
if (n1>n2):
print(n1)
else:
print(n2)
if ((n1%2==0)and(n2%2!=0)):
print(n1)
if ((n1%2!=0)and(n2%2==0)):
print(n2)
if ((n1%2!=0)and(n2%2!=0)):
print("nu exista numere pare") |
#Se introduc trei date de forma număr curent elev, punctaj. Afişaţi numărul elevului cu cel mai mare punctaj.
e1=int(input("nr. elev"))
e2=int(input("nr. elev"))
e3=int(input("nr. elev"))
p1=int(input("introduceti punctajul primului elev"))
p2=int(input("introduceti punctajul elevului al doilea"))
p3=int(input("introduceti punctajul elevului al treilea"))
if ((p1>p2)and(p1>p3)):
print("elevul cu nr",e1, "are cel mai mare punctaj")
if ((p2>p1)and(p2>p3)):
print("elevul cu nr",e2, "are cel mai mare punctaj")
if ((p3>p1)and(p3>p2)):
print("elevul cu nr",e3, "are cel mai mare punctaj")
|
# Small exercise 5
numbers = [-2, -1, 0, 1, 2, 3, 4, 5, 6]
for value in numbers:
if value > 0:
print(value)
#Small exercise 6
new_list = []
for value in numbers:
if value > 0:
new_list.append(value)
print(new_list) |
"""
You work on a team whose job is to understand the most sought after toys for the holiday season.
A teammate of yours has built a webcrawler that extracts a list of quotes about toys from different articles.
You need to take these quotes and identify which toys are mentioned most frequently.
Write an algorithm that identifies the top N toys out of a list of quotes and list of toys.
Your algorithm should output the top N toys mentioned most frequently in the quotes.
Input:
The input to the function/method consists of five arguments:
numToys, an integer representing the number of toys
topToys, an integer representing the number of top toys your algorithm needs to return;
toys, a list of strings representing the toys,
numQuotes, an integer representing the number of quotes about toys;
quotes, a list of strings that consists of space-sperated words representing articles about toys
Output:
Return a list of strings of the most popular N toys in order of most to least frequently mentioned
Note:
The comparison of strings is case-insensitive.
If the value of topToys is more than the number of toys,
return the names of only the toys mentioned in the quotes.
If toys are mentioned an equal number of times in quotes, sort alphabetically.
Example:
Input:
numToys = 6
topToys = 2
toys = ["elmo", "elsa", "legos", "drone", "tablet", "warcraft"]
numQuotes = 6
quotes = [
"Elmo is the hottest of the season! Elmo will be on every kid's wishlist!",
"The new Elmo dolls are super high quality",
"Expect the Elsa dolls to be very popular this year, Elsa!",
"Elsa and Elmo are the toys I'll be buying for my kids, Elsa is good",
"For parents of older kids, look into buying them a drone",
"Warcraft is slowly rising in popularity ahead of the holiday season"
];
Output:
["elmo", "elsa"]
Explanation:
elmo - 4
elsa - 4
"elmo" should be placed before "elsa" in the result because "elmo" appears in 3 different quotes and "elsa" appears in 2 different quotes.
"""
import re
def top_n_buzzword(num_toys, top_toys, toys, num_quotes, quotes):
buzzwords = {} # init dictionary
# O(n^2)
for toy in toys: # iterate over toys
buzzwords[toy] = 0
buzzword_count = 0
for quote in quotes: # iterate over quotes list, counting occurrences of tpy names
clean_quote = re.sub('[^A-Za-z0-9]+', ' ', quote).lower()
buzzword_count += clean_quote.split(" ").count(toy)
buzzwords[toy] = buzzword_count
# O(n Log n) python uses Timesort (merge and insertion)
sorted_buzzwords = sorted(buzzwords.items(), key=lambda kv: kv[1], reverse=True)
counter = 1
buzzword_list = []
# O(n)
for (name, count) in sorted_buzzwords:
buzzword_list.append(name)
if counter == top_toys:
break
counter += 1
return buzzword_list
if __name__ == '__main__':
#str = "Elmo is the hottest of the season! Elmo will be on every kid's wishlist!".lower()
#print(str.split(" ").count('elmo'))
toys = ["elmo", "elsa", "legos", "drone", "tablet", "warcraft"]
quotes = [
"Elmo is the hottest of the season! Elmo will be on every kid's wishlist!",
"The new Elmo dolls are super high quality",
"Expect the Elsa dolls to be very popular this year, Elsa!",
"Elsa and Elmo are the toys I'll be buying for my kids, Elsa is good",
"For parents of older kids, look into buying them a drone",
"Warcraft is slowly rising in popularity ahead of the holiday season"
]
print(top_n_buzzword(6, 2, toys, 6, quotes)) |
# Google Question
# Given an array = [2,5,1,2,3,5,1,2,4]:
# It should return 2
# Given an array = [2,1,1,2,3,5,1,2,4]:
# It should return 1
# Given an array = [2,3,4,5]:
# It should return undefined
#function firstRecurringCharacter(input)
#}
# Bonus... What if we had this:
# [2,5,5,2,3,5,1,2,4]
# return 5 because the pairs are before 2,2
def first_recurring_character(arr):
character_map = {}
# create a dict / map checking if it's already in the map. If it is, it's the first recurring
for item in arr:
if item in character_map:
return item
else:
character_map[item] = 1
return None
|
# Different way to traversal a matrix with equal
# LEFT TO RIGHT --->
# Left to Right equals row, than column
def matrix_traversals_left_to_right(matrix):
arr = []
for row in range(len(matrix)):
for column in range(len(matrix[0])):
value = matrix[row][column]
arr.append(value)
return arr
# RIGHT TO LEFT <--
# Right to Left equals, column, than backwards row
def matrix_traversals_right_to_left(matrix):
arr = []
for column in range(len(matrix[0])):
for row in range(len(matrix) - 1, -1, -1):
value = matrix[column][row]
arr.append(value)
return arr
# TOP TO BOTTOM
# Top to Bottom equals, column, than row
def matrix_traversals_top_to_bottom(matrix):
arr = []
for column in range(len(matrix[0])):
for row in range(len(matrix)):
value = matrix[row][column]
arr.append(value)
return arr
# BOTTOM TO TOP
# Bottom to Top equals, column, than backwards row
def matrix_traversals_bottom_to_top(matrix):
arr = []
for column in range(len(matrix[0])):
for row in range(len(matrix) - 1, -1, -1):
value = matrix[row][column]
arr.append(value)
return arr
# DIAGONAL TOP TO BOTTOM
def matrix_traversals_diagonal_top_bottom(matrix):
arr = []
row = 0
column = 0
while row < len(matrix):
value = matrix[row][column]
arr.append(value)
row += 1
column += 1
return arr
# DIAGONAL BOTTOM TO TOP
def matrix_traversals_diagonal_bottom_top(matrix):
arr = []
row = len(matrix) - 1
column = len(matrix[0]) - 1
while row >= 0:
value = matrix[row][column]
arr.append(value)
row -= 1
column -= 1
return arr
# SPIRAL TOP TO BOTTOM
def matrix_traversals_spiral_top_bottom(matrix):
"""
k - starting row index
m - ending row index
l - starting column index
n - ending column index
i - iterator
"""
output_arr = []
start_row_idx = 0
end_row_idx = len(matrix)
start_column_idx = 0
end_column_idx = len(matrix[0])
while start_row_idx < end_row_idx:
while start_column_idx < end_column_idx:
value = matrix[start_row_idx][start_column_idx]
output_arr.append(value)
print("value: ", value)
start_column_idx += 1
start_row_idx += 1
start_row_idx = 1
while start_row_idx < end_row_idx:
value = matrix[start_row_idx][start_column_idx - 1]
output_arr.append(value)
print("value: ", value)
start_row_idx += 1
#print("start_row_idx ", start_row_idx)
#print("end_row_idx ", end_row_idx)
#print("start_column_idx ", start_column_idx)
#print("end_column_idx ", end_column_idx)
return output_arr
# SPIRAL BOTTOM TO TOP
def matrix_traversals_spiral_bottom_to_top(matrix):
return None
# Matrix Indexes
# 00 01 02 03 04
# 10 11 12 13 14
# 20 21 22 23 24
# 30 31 32 33 34
# 40 41 42 43 44
if __name__ == "__main__":
tests = dict()
tests['left_to_right'] = {"paramters": [
[1, 4, 7, 11, 15],
[2, 5, 8, 12, 19],
[3, 6, 9, 16, 22],
[10, 13, 14, 17, 24],
[18, 21, 23, 26, 30]
], "expected": [1, 4, 7, 11, 15, 2, 5, 8, 12, 19, 3, 6, 9, 16, 22, 10, 13, 14, 17, 24, 18, 21, 23, 26, 30]}
tests['right_to_left'] = {"paramters": [
[1, 4, 7, 11, 15],
[2, 5, 8, 12, 19],
[3, 6, 9, 16, 22],
[10, 13, 14, 17, 24],
[18, 21, 23, 26, 30]
], "expected": [15, 11, 7, 4, 1, 19, 12, 8, 5, 2, 22, 16, 9, 6, 3, 24, 17, 14, 13, 10, 30, 26, 23, 21, 18]}
tests['top_to_bottom'] = {"paramters": [
[1, 4, 7, 11, 15],
[2, 5, 8, 12, 19],
[3, 6, 9, 16, 22],
[10, 13, 14, 17, 24],
[18, 21, 23, 26, 30]
], "expected": [1, 2, 3, 10, 18, 4, 5, 6, 13, 21, 7, 8, 9, 14, 23, 11, 12, 16, 17, 26, 15, 19, 22, 24, 30]}
tests['bottom_to_top'] = {"paramters": [
[1, 4, 7, 11, 15],
[2, 5, 8, 12, 19],
[3, 6, 9, 16, 22],
[10, 13, 14, 17, 24],
[18, 21, 23, 26, 30]
], "expected": [18, 10, 3, 2, 1, 21, 13, 6, 5, 4, 23, 14, 9, 8, 7, 26, 17, 16, 12, 11, 30, 24, 22, 19, 15]}
tests['diagonal_top_bottom'] = {"paramters": [
[1, 4, 7, 11, 15],
[2, 5, 8, 12, 19],
[3, 6, 9, 16, 22],
[10, 13, 14, 17, 24],
[18, 21, 23, 26, 30]
], "expected": [1, 5, 9, 17, 30]}
tests['diagonal_bottom_top'] = {"paramters": [
[1, 4, 7, 11, 15],
[2, 5, 8, 12, 19],
[3, 6, 9, 16, 22],
[10, 13, 14, 17, 24],
[18, 21, 23, 26, 30]
], "expected": [30, 17, 9, 5, 1]}
tests['sprial_top_bottom'] = {"paramters": [
[1, 4, 7, 11, 15],
[2, 5, 8, 12, 19],
[3, 6, 9, 16, 22],
[10, 13, 14, 17, 24],
[18, 21, 23, 26, 30]
], "expected": [1, 4, 7, 11, 15, 19, 22, 24, 30, 26, 23, 21, 18, 10, 3, 2, 5, 8, 12, 16, 17, 14, 13, 6, 9]}
# Left to Right
# results1 = matrix_traversals_left_to_right(tests['left_to_right']['paramters'])
# print("Test {0}".format("left_to_right ", tests['left_to_right']['paramters']), tests['left_to_right']['expected'] == results1, results1)
# # Right to Left
# results2 = matrix_traversals_right_to_left(tests['right_to_left']['paramters'])
# print("Test {0}".format("right_to_left ", tests['right_to_left']['paramters']), tests['right_to_left']['expected'] == results2, results2)
# # Top to Bottom
# results3 = matrix_traversals_top_to_bottom(tests['top_to_bottom']['paramters'])
# print("Test {0}".format("top_to_bottom ", tests['top_to_bottom']['paramters']), tests['top_to_bottom']['expected'] == results3, results3)
# # Bottom to Top
# results4 = matrix_traversals_bottom_to_top(tests['bottom_to_top']['paramters'])
# print("Test {0}".format("bottom_to_top ", tests['bottom_to_top']['paramters']), tests['bottom_to_top']['expected'] == results4, results4)
# # Diagonal Top to Bottom
# results5 = matrix_traversals_diagonal_top_bottom(tests['diagonal_top_bottom']['paramters'])
# print("Test {0}".format("diagonal_top_bottom ", tests['diagonal_top_bottom']['paramters']), tests['diagonal_top_bottom']['expected'] == results5, results5)
# # Diagonal Bottom to Top
# results6 = matrix_traversals_diagonal_bottom_top(tests['diagonal_bottom_top']['paramters'])
# print("Test {0}".format("diagonal_bottom_top ", tests['diagonal_bottom_top']['paramters']), tests['diagonal_bottom_top']['expected'] == results6, results6)
results7 = matrix_traversals_spiral_top_bottom(tests['sprial_top_bottom']['paramters'])
print("Test {0}".format("sprial_top_bottom ", tests['sprial_top_bottom']['paramters']), tests['sprial_top_bottom']['expected'] == results7, results7)
|
def is_palindrome(string):
reversed_string = string[::-1]
if string == reversed_string:
return True
return False
if __name__ == '__main__':
results = is_palindrome("abcdcbad")
print(results)
|
# Given two strings s and t , write a function to determine if t is an anagram of s.
def is_valid_anagram(s, t):
if len(s) != len(t):
return False
s_dict = {}
t_dict = {}
for i in range(len(s)):
char = s[i]
if char not in s_dict:
s_dict[char] = 1
else:
s_dict[char] += 1
for i in range(len(t)):
char = t[i]
if char not in t_dict:
t_dict[char] = 1
else:
t_dict[char] += 1
return s_dict == t_dict
if __name__ == '__main__':
s = "anagram"
t = "nagaram"
s1 = 'car'
t1 = 'rat'
r = is_valid_anagram(s1, t1)
print(r)
|
def initialize_union(my_dict, x, y):
if x not in my_dict:
my_dict[x] = x
if y not in my_dict:
my_dict[y] = y
def initialize_size(my_dict, x, y):
if x not in my_dict:
my_dict[x] = 1
if y not in my_dict:
my_dict[y] = 1
def get_root(arr, i):
while arr[i] != i:
i = arr[i]
return i
def find(arr, a, b):
if get_root(arr, a) == get_root(arr, b):
return True
else:
return False
if __name__ == '__main__':
queries = [
[1, 2],
[3, 4],
[1, 3],
[5, 7],
[5, 6],
[7, 4]
]
queries_2 = [
[0, 1],
[1, 2],
[3, 2]
]
queries_3 = [
[1, 2],
[1, 3]
]
queries_4 = [
[1000000000, 23],
[11, 3778],
[7, 47],
[11, 1000000000]
]
queries_5 = [
[6, 4],
[5, 9],
[8, 5],
[4, 1],
[1, 5],
[7, 2],
[4, 2],
[7, 6]
]
"""
2
2
3
3
6
6
8
8
"""
my_queries = queries_5
union_find_dict = {}
size_dict = {}
results = []
my_union = []
largest_group = 0
# report the size of the largest friend circle (the largest group of friends)
for query in my_queries:
initialize_union(union_find_dict, query[0], query[1])
initialize_size(size_dict, query[0], query[1])
root_a = get_root(union_find_dict, query[0])
root_b = get_root(union_find_dict, query[1])
if root_a != root_b:
if size_dict[root_a] > size_dict[root_b]:
union_find_dict[root_b] = root_a
size_dict[root_a] = size_dict[root_a] + size_dict[root_b]
else:
union_find_dict[root_a] = root_b
size_dict[root_b] = size_dict[root_a] + size_dict[root_b]
largest_group = max(largest_group, max(size_dict[root_a], size_dict[root_b]))
results.append(largest_group)
print(results)
|
def spiralMatrixPrint(row, col, arr):
# Defining the boundaries of the matrix.
top = 0
bottom = row-1
left = 0
right = col - 1
# Defining the direction in which the array is to be traversed.
dir = 0
while (top <= bottom and left <=right):
if dir ==0:
for i in range(left,right+1): # moving left->right
print (arr[top][i], end=" ")
# Since we have traversed the whole first
# row, move down to the next row.
top +=1
dir = 1
elif dir ==1:
for i in range(top,bottom+1): # moving top->bottom
print (arr[i][right], end=" ")
# Since we have traversed the whole last
# column, move down to the previous column.
right -=1
dir = 2
elif dir ==2:
for i in range(right,left-1,-1): # moving right->left
print (arr[bottom][i], end=" ")
# Since we have traversed the whole last
# row, move down to the previous row.
bottom -=1
dir = 3
elif dir ==3:
for i in range(bottom,top-1,-1): # moving bottom->top
print (arr[i][left], end=" ")
# Since we have traversed the whole first
# column, move down to the next column.
left +=1
dir = 0
def spiralTraverse(array):
# Write your code here.
top = 0
bottom = len(array) - 1
left = 0
right = len(array[0]) - 1
traverse_direction = 0
output_array = []
while top <= bottom and left <= right:
if traverse_direction == 0: # left to right
for i in range(left, right + 1, 1):
value = array[top][i]
output_array.append(value)
top += 1
traverse_direction += 1
elif traverse_direction == 1: # top to bottom
for i in range(top, bottom+1, 1):
value = array[i][right]
output_array.append(value)
right -= 1
traverse_direction += 1
elif traverse_direction == 2: # right to left
for i in range(right, left - 1, -1):
value = array[bottom][i]
output_array.append(value)
bottom -= 1
traverse_direction += 1
elif traverse_direction == 3: # bottom to top
for i in range(bottom, top - 1, -1):
value = array[i][left]
output_array.append(value)
left += 1
traverse_direction = 0
return output_array
# Driver code
# Change the following array and the corresponding row and
# column arguments to test on some other input
if __name__ == '__main__':
array = [[1,2,3,4],
[12,13,14,5],
[11,16,15,6],
[10,9,8,7]]
spiralMatrixPrint(4, 4, array)
print("\n")
v = spiralTraverse(array)
print(v) |
"""
Write a function that takes in a "special" array and returns its product sum.
A "special" array is a non-empty array that contains either integers or other "special" arrays.
The product sum of a "special" array is the sum of its elements, where "special" arrays inside
it should be summed themselves and then multiplied by their level of depth. For example,
the product sum of [x, y] is x + y; the product sum of [x, [y, z]] is x + 2y + 2z.
Sample input: [5, 2, [7, -1], 3, [6, [-13, 8], 4]]
Sample output: 12 (calculated as: (5 + 2 + 2 * (7 - 1) + 3 + 2 * (6 + 3 * (-13 + 8) + 4)))
Initialize the product sum of the "special" array to 0. Then, iterate through all of the array's elements;
if you come across a number, add it to the product sum; if you come across another "special" array, recursively
call the productSum function on it and add the returned value to the product sum. How will you handle multiplying
the product sums at a given level of depth?
"""
def product_sum(array):
return calulate_product_sum(array, 1)
def calulate_product_sum(source_array, multiplier):
psum = 0
for item in source_array:
if isinstance(item, list):
psum += calulate_product_sum(item, multiplier + 1)
else:
psum += item
return psum * multiplier
pass
if __name__ == '__main__':
array = [5, 2, [7, -1], 3, [6, [-13, 8], 4]]
results = product_sum(array)
print(results) |
"""
Given a 2D grid, each cell is either a zombie or a human.
Zombies can turn adjacent (up/down/left/right) human beings into zombies every day.
Find out how many days does it take to infect all humans?
Input:
matrix, a 2D integer array where a[i][j] = 1 represents a zombie on the cell and a[i][j] = 0 represents a human on the cell.
Output:
Return an integer represent how many days does it take to infect all humans.
Return -1 if no zombie exists.
Example :
Input:
[[0, 1, 1, 0, 1], <-- 0,0 - (0,1) - (0,2) - 0,3 - (0,4)
[0, 1, 0, 1, 0], <-- 1,0 - (1,1) - 1,2 - (1,3) - 1,4
[0, 0, 0, 0, 1], <-- 2,0 - 2,1 - 2,2 - 2,3 - (2,4)
[0, 1, 0, 0, 0]]m<-- 3,0 - (3,1) - 3,2 - 3,3 - 3,4
directions=[[1,0],[-1,0],[0,1],[0,-1]] bottom, top, right, left
Output:
2
Explanation:
At the end of the day 1, the status of the grid:
[[1, 1, 1, 1, 1],
[1, 1, 1, 1, 1],
[0, 1, 0, 1, 1],
[1, 1, 1, 0, 1]]
At the end of the day 2, the status of the grid:
[[1, 1, 1, 1, 1],
[1, 1, 1, 1, 1],
[1, 1, 1, 1, 1],
[1, 1, 1, 1, 1]]
"""
def human_days(matrix):
if len(matrix) == 0:
return 0
days = 0
queue = []
row_length = len(matrix)
column_length = len(matrix[0])
# add zombies to the queue
for row in range(row_length):
for column in range(column_length):
if matrix[row][column] == 1:
queue.append((row, column))
direction_shift = [[1,0],[-1,0],[0,1],[0,-1]] # bottom, top, right, left shift
while True:
sub_queue = []
while len(queue) > 0:
(row, column) = queue.pop()
print("- row, column: {0}, {1}".format(row, column))
for d in direction_shift:
new_row = row + d[0]
new_column = column + d[1]
# Make sure the indexes are within the range of the matrix
# and if the grid item is a human == 0
if new_row < row_length and new_column < column_length and matrix[new_row][new_column] == 0:
matrix[new_row][new_column] = 1
sub_queue.append((new_column, new_column))
print("- ni, nj {0} {1}".format(new_row, new_column))
print()
queue = sub_queue
days += 1
if not queue:
break
return days
if __name__ == '__main__':
matrix = [[0, 1, 1, 0, 1],
[0, 1, 0, 1, 0],
[0, 0, 0, 0, 1],
[0, 1, 0, 0, 0]]
print(human_days(matrix)) |
"""
You're given a <span>Node</span> class that has a <span>name</span> and an
array of optional <span>children</span> nodes. When put together, nodes form a
simple tree-like structure.
Implement the <span>depthFirstSearch</span> method on the
<span>Node</span> class, which takes in an empty array, traverses the tree
using the Depth-first Search approach (specifically navigating the tree from
left to right), stores all of the nodes' names in the input array, and
returns it.
If you're unfamiliar with Depth-first Search, we recommend watching the Conceptual
Overview section of this question's video explanation before starting to code.
Sample Input
graph = A
/ | \
B C D
/ \ / \
E F G H
/ \ \
I J K
Sample Output
["A", "B", "E", "F", "I", "J", "C", "D", "G", "K", "H"]
"""
class Node:
def __init__(self, name):
self.children = []
self.name = name
def add_child(self, name):
self.children.append(Node(name))
return self
def breadith_first_search(self, array):
queue = [self]
while len(queue) > 0:
current = queue.pop()
array.append(current.name)
for child in current.children:
queue.append(child)
return array
|
# Peak Valley Approach
# initial index, peak, valley, max_profit variables
# iterate over prices
# iterate to find peaks and valleys
# while if price[i] >= price[i + 1] increment index by one
# define valley based off the condition
# while if price[i] <= price[i + 1] increment index by one
# define peak based off the condition
# calulate max_profile (peak - valley)
def best_time_to_buy_and_sell_stock_II(prices):
index = 0
max_profit = 0
peak = prices[0]
valley = prices[0]
while index < len(prices) - 1:
while index < len(prices) - 1 and prices[index] >= prices[index + 1]:
index += 1
peak = prices[index]
while index < len(prices) - 1 and prices[index] <= prices[index + 1]:
index += 1
valley = prices[index]
max_profit += abs(peak - valley)
return max_profit
def best_time_to_buy_and_sell_stock_II_2(prices):
max_profit = 0
for i in range(1, len(prices)):
if prices[i] > prices[i - 1]:
max_profit += prices[i] - prices[i - 1]
return max_profit
if __name__ == '__main__':
r1 = best_time_to_buy_and_sell_stock_II_2([7,1,5,3,6,4])
print(r1)
|
class AIBoard:
def __init__(self, board):
self.board = board
def make_move(self):
# assuming this is legal move
if not self.board.is_board_full():
# get all value with dashes.
print()
else:
raise Exception('Can not make move')
# find all tashes
# what is legal move
class Board:
def __init__(self):
self.board = [["-", "-", "-"], ["-", "-", "-"], ["-", "-", "-"]]
def add_token_to_board(self, rows, columns, token):
if (rows >= 0 and rows <= len(self.board)) and (columns >= 0 and columns <= len(self.board[0]) -1):
self.board[rows][columns] = token
else:
print("token is out of bounds")
return self.board
def print_board(self):
for row in self.board:
print('|'.join(row))
def is_board_full(self):
for row in self.board:
if "-" in row:
return False
return True
if __name__ == '__main__':
board = Board()
board.add_token_to_board(0, 0, 'X')
board.add_token_to_board(1, 1, '0')
board.add_token_to_board(1, 2, 'X')
board.print_board()
print(board.is_board_full())
#print(results)
#print()
if __name__ == '__main__':
pass |
"""
You are on a flight and wanna watch two movies during this flight.
You are given int[] movie_duration which includes all the movie durations.
You are also given the duration of the flight which is d in minutes.
Now, you need to pick two movies and the total duration of the two movies is less than or equal to (d - 30min).
Find the pair of movies with the longest total duration. If multiple found, return all pairs.
Input
movie_duration: [90, 85, 75, 60, 120, 150, 125]
d: 250
Output
[90, 125]
90min + 125min = 215 is the maximum number within 220 (250min - 30min)
"""
def movies_on_flight_2(flight_duration, movie_duration):
flight_duration -= 30
movie_duration = sorted(movie_duration)
left_index = 0
right_index = len(movie_duration) - 1
closest_value = 0
while(left_index < right_index):
if movie_duration[left_index] + movie_duration[right_index] <= flight_duration:
if closest_value < (movie_duration[left_index] + movie_duration[right_index]):
closest_value = movie_duration[left_index] + movie_duration[right_index]
x = left_index
y = right_index
left_index += 1
else:
right_index -= 1
return (movie_duration[x], movie_duration[y])
def movies_on_flight(flight_duration, movie_duration):
movies_flight_duration = flight_duration - 30
if movies_flight_duration == movie_duration:
return movie_duration
movie_dict = {}
list_of_final_durations = []
# build a map of all possible sums with a list of their associated indexes {215: (0, 5)}
# Time complexity O(n^2) Not very efficient
for d in range(len(movie_duration)):
for dd in range(len(movie_duration) -1):
sub_sum = movie_duration[d] + movie_duration[dd+1]
if sub_sum in movie_dict:
movie_dict[sub_sum].append((d, dd+1))
else:
movie_dict[sub_sum] = []
movie_dict[sub_sum].append((d, dd+1))
# find matching sum key in dictionary, return a list of associated indexes.
if movies_flight_duration in movie_dict:
indexes = movie_dict[movies_flight_duration]
else:
# Get the closest value to movies_flight_duration and return list of indexes
closest_value = min(movie_dict, key=lambda x:abs(x-movies_flight_duration))
indexes = movie_dict[closest_value]
# create final list (converts index values into actual values.)
# Time complexity O(n)
for index in indexes:
list_of_final_durations.append((movie_duration[index[0]], movie_duration[index[1]]))
# Space complexity O(n)
# Time complexity O(n^2)
return list_of_final_durations
if __name__ == '__main__':
results = movies_on_flight_2(250, [90, 85, 75, 60, 120, 150, 125])
print(results) |
# Quick script to parse nmap (.gnmap) files: IP/Port -> URL
# Normally this gets leveraged as input to another tool like -> whatweb
#
# Example: ~$ python parse_nmap.py nmap_results.gnmap
# https://10.10.146.1
# http://10.10.146.1
# https://10.10.146.67
# http://10.10.146.75:8080
# https://10.10.146.100
# http://10.10.146.100
# https://10.10.146.101:8443
# http://10.10.146.117
#!/usr/bin/env python
import sys
import re
import os
# Check for proper args
if len(sys.argv) < 2:
print "Usage: "+sys.argv[0]+" [nmap_file.gnmap]"
sys.exit(0)
# This will parse for common ports associated with URLs
# You can add in additional as needed by following the same syntax below
with open(sys.argv[1], 'r') as nmap_file:
for line in nmap_file:
if 'open' in line:
if re.search("443/open".format(),line):
print "https://" + line.split()[1]
if '()' not in line:
newline = line.split()[2]
newline = newline.replace("(", "")
newline = newline.replace(")", "")
print "https://" + newline
if re.search("80/open".format(),line):
print "http://" + line.split()[1]
if '()' not in line:
newline = line.split()[2]
newline = newline.replace("(", "")
newline = newline.replace(")", "")
print "http://" + newline
if re.search("8080/open".format(),line):
print "http://" + line.split()[1]+":8080"
if '()' not in line:
newline = line.split()[2]
newline = newline.replace("(", "")
newline = newline.replace(")", "")
print "http://" + newline+":8080"
if re.search("8000/open".format(),line):
print "http://" + line.split()[1]+":8000"
if '()' not in line:
newline = line.split()[2]
newline = newline.replace("(", "")
newline = newline.replace(")", "")
print "http://" + newline+":8000"
if re.search("8443/open".format(),line):
print "https://" + line.split()[1]+":8443"
if '()' not in line:
newline = line.split()[2]
newline = newline.replace("(", "")
newline = newline.replace(")", "")
print "https://" + newline+":8443"
if re.search("8009/open".format(),line):
print "http://" + line.split()[1]+":8009"
if '()' not in line:
newline = line.split()[2]
newline = newline.replace("(", "")
newline = newline.replace(")", "")
print "http://" + newline+":8009"
if re.search("8090/open".format(),line):
print "http://" + line.split()[1]+":8090"
if '()' not in line:
newline = line.split()[2]
newline = newline.replace("(", "")
newline = newline.replace(")", "")
print "http://" + newline+":8090"
if re.search("10000/open".format(),line):
print "http://" + line.split()[1]+":10000"
if '()' not in line:
newline = line.split()[2]
newline = newline.replace("(", "")
newline = newline.replace(")", "")
print "http://" + newline+":10000"
|
from tkinter import *
from time import strftime
window = Tk()
window.geometry("300x75")
window.configure(bg="black")
space = " "
window.title(space+"DIGITAL CLOCK")
def clock():
time = strftime('%H:%M:%S %p')
label = Label(frame, font=('arial', 20, 'bold'), text=time, fg="white", bg="black")
label.place(x=65, y=20)
label.after(1000, clock)
frame = Frame(window, width=300, height=75, highlightbackground="white", highlightcolor="black", highlightthickness=2,
bg="black")
frame.pack()
clock()
window.mainloop()
|
# Implementation of heap from list in Python
class Heap(object):
def __init__(self):
self.list = []
self.last_index = -1
def insert(self, x):
self.last_index += 1
if not self.list:
self.list.append(x)
return
self.list.append(x)
index = self.last_index
parent = int((index-1)/2)
while (self.list[index] > self.list[parent]) and parent >= 0:
temp = self.list[index]
self.list[index] = self.list[parent]
self.list[parent] = temp
index = parent
parent = int((parent-1)/2)
def max(self):
return self.list[0]
def pop(self):
head = self.list[0]
self.list[0] = self.list[self.last_index]
self.list.pop()
print self.list
self.last_index -= 1
index = 0
left_child_index = (index * 2) + 1
right_child_index = (index * 2) + 2
if left_child_index > self.last_index: # 0 or 1 nodes in heap, done
return head
if right_child_index > self.last_index: # no right child
right_child_index = index
while (self.list[index] < self.list[right_child_index]) or \
(self.list[index] < self.list[left_child_index]):
if self.list[left_child_index] > self.list[right_child_index]:
temp = self.list[index]
self.list[index] = self.list[left_child_index]
self.list[left_child_index] = temp
index = left_child_index
left_child_index = (index * 2) + 1
right_child_index = (index * 2) + 2
else:
temp = self.list[index]
self.list[index] = self.list[right_child_index]
self.list[right_child_index] = temp
index = right_child_index
left_child_index = (index * 2) + 1
right_child_index = (index * 2) + 2
if left_child_index > self.last_index:
return head
if right_child_index > self.last_index:
right_child_index = index
if __name__ == "__main__":
h = Heap()
for i in range(20):
h.insert(i)
print h.list
print h.pop()
print h.list
|
import pandas as pd
from nba_api.stats.endpoints import boxscoretraditionalv2, teamgamelog
def get_team_info(game_id, season, season_type):
# Create Box Score Traditional Object and get DataFrame
# print(type(game_id))
traditional = boxscoretraditionalv2.BoxScoreTraditionalV2(game_id=game_id)
teams_df = traditional.team_stats.get_data_frame()
# Determine The Two Teams That Played In The Game #
teams = teams_df['TEAM_ID'].unique()
### Figure Out Which Team Won The Game ###
# Create a game log object and dataframe for the first team in the teams list
game_log = teamgamelog.TeamGameLog(team_id=teams[0], season=season, season_type_all_star=season_type)
game_log_df = game_log.team_game_log.get_data_frame()
# Filter that teams game log to be only the specific game we are evaluating
game_log_df = game_log_df[game_log_df['Game_ID'] == game_id]
# Print basic info about the game for tracking purposes as code is running, game date, two teams playing, if first team won or lost game
print(game_log_df.iloc[0]['GAME_DATE'], " ", game_log_df.iloc[0]['MATCHUP'], " ", game_log_df.iloc[0]['WL'])
# If team[0] won the game, set their id to the winning_team variable, else set team[1]
# If there is an @ the first team is away, else they are home. This is important for the play_by_play dataframe
if game_log_df.iloc[0]['WL'] == 'W' and '@' in game_log_df.iloc[0]['MATCHUP']:
winning_team = teams[0]
losing_team = teams[1]
home_away = 1
elif game_log_df.iloc[0]['WL'] == 'W' and '@' not in game_log_df.iloc[0]['MATCHUP']:
winning_team = teams[0]
losing_team = teams[1]
home_away = 0
elif game_log_df.iloc[0]['WL'] == 'L' and '@' not in game_log_df.iloc[0]['MATCHUP']:
winning_team = teams[1]
losing_team = teams[0]
home_away = 1
else:
winning_team = teams[1]
losing_team = teams[0]
home_away = 0
return losing_team, winning_team, home_away |
import pandas as pd
import pdb
# Blocks Value Structure
block_before_turnover = .5
block_with_rebound = .9
#defense_value = 2.2 # Possession value can be subtracted by this for an alternate way of evaluating. This makes the assumption that blocking something is stopping a field goal that is likely to go in, rather than just the expected value of a field goal
def score_blocks(play_by_play_df, val_contr_inputs_df, current_player, win_loss, team_id, defense_possession_value):
current_player_blocks_score = 0 # Set blocks score to 0
failed_blocks = 0
# Blocks works differently than other events because there is no explicit message type for it
# We need to find strings within the play_by_play_df which contain the word 'block' and the name of the player being evaluated
# Finding those events creates our player_events_df
if win_loss == 1:
team1 = 'WINNINGTEAM'
team2 = 'LOSINGTEAM'
else:
team1 = 'LOSINGTEAM'
team2 = 'WINNINGTEAM'
player_last_name = val_contr_inputs_df['PLAYER_NAME'].where(val_contr_inputs_df['PLAYER_ID'] == current_player).dropna().reset_index().drop(columns='index')
player_last_name = str(player_last_name).split()[-1]
player_events_df = play_by_play_df[(play_by_play_df[team1].str.contains("BLOCK", na=False)) & (play_by_play_df[team1].str.contains(player_last_name, na=False))]
# play_by_play_df and player_events_df have the same indexes
# play_by_play_df includes every play from the game
# player_events_df includes only events the current player being evaluated was involved in
# It is filtered to include events related to the current staistic, in this case blocks
# Moving down play_by_play_df means looking at events which happened after the result being analyzed in the player_events_df
# In regards to blocks, this means looking to see if the losing team scored after the block or if the winning team came up with a stop
for idx, event in player_events_df['EVENTMSGTYPE'].iteritems(): # For every block by this player
shot_made_index = 1 # Called shot_made_index because we are looking to see if the losing team made a shot, which would make the block worthless
while True:
if idx + shot_made_index > len(play_by_play_df.index) - 1: # If we go to an index outside the play_by_play_df, there must be no score after the block
current_player_blocks_score += defense_possession_value # Add score to player's blocks score using the value of a defensive possession
break
elif (play_by_play_df.loc[idx + shot_made_index]['EVENTMSGTYPE'] == 1
and play_by_play_df.loc[idx + shot_made_index][team1] == None): # If we see that the losing team made a shot assign no value to the block and move onto the next block to be evaluated
failed_blocks += 1
break
elif (play_by_play_df.loc[idx + shot_made_index]['EVENTMSGTYPE'] == 4
and play_by_play_df.loc[idx + shot_made_index][team1] != None): # If there is a rebound by the winning team, award value to the block and move onto next block
current_player_blocks_score += defense_possession_value * block_with_rebound
break
elif (play_by_play_df.loc[idx + shot_made_index]['EVENTMSGTYPE'] == 5
and 'steal' in str(play_by_play_df.loc[idx + shot_made_index][team1]).lower()): # If a steal caused a change in possession by the losing team, award the block value based on value structure with turnover
current_player_blocks_score += defense_possession_value * block_before_turnover
break
elif (play_by_play_df.loc[idx + shot_made_index]['EVENTMSGTYPE'] == 5
and play_by_play_df.loc[idx + shot_made_index][team1] == None): # If there was a turnover that was not a steal, award 100% value for block
current_player_blocks_score += defense_possession_value
break
elif (play_by_play_df.loc[idx + shot_made_index]['EVENTMSGTYPE'] == 2
and (play_by_play_df.loc[idx + shot_made_index + 1]['EVENTMSGTYPE'] == 4
and play_by_play_df.loc[idx + shot_made_index + 1][team2] == None)): # If there was a missed shot followed by a rebound by the winning team
if play_by_play_df.loc[idx + shot_made_index + 1]['PLAYER1_ID'] == None: # If the rebound was a team rebound, award the block 100% value
current_player_blocks_score += defense_possession_value
break
else:
current_player_blocks_score += defense_possession_value * block_with_rebound # If the rebound wasn't a team rebound, award the block the percentage value associated with a defensive rebound
break
elif (play_by_play_df.loc[idx + shot_made_index]['EVENTMSGTYPE'] == 3
and play_by_play_df.loc[idx + shot_made_index]['PLAYER1_TEAM_ID'] != team_id): # If there were free throws by the losing team after the block
counter = 0 # Total free throws counter
points_off_board = 0 # Free throw made counter
if 'technial' in str(play_by_play_df.loc[idx + shot_made_index][team2]).lower(): # If free throws caused by technical foul
free_throws = 1
if 'pts' in str(play_by_play_df.loc[idx + shot_made_index + counter][team2]).lower(): # If tehnical free throw is made
points_off_board += 1 # Add points scored on the possession
free_throws -= 1
counter += 1
else: # If technical free throw is missed
free_throws -= 1
counter += 1
elif 'of 1' in str(play_by_play_df.loc[idx + shot_made_index][team2]).lower(): # If there was 1 free throw
free_throws = 1
elif 'of 2' in str(play_by_play_df.loc[idx + shot_made_index][team2]).lower(): # If there were 2 free throws
free_throws = 2
elif 'of 3' in str(play_by_play_df.loc[idx + shot_made_index][team2]).lower(): # If there were 3 free throws
free_throws = 3
else: # Print errors if there are an unknown number of free throws
# print('BLOCK: ', str(play_by_play_df.loc[idx][team2]).lower())
# print('BLOCK: ', str(play_by_play_df.loc[idx + shot_made_index][team2]).lower())
# print('BLOCK: ERROR: UNKNOWN NUMBER OF FREE THROWS', idx)
# #pdb.set_trace()
# print(play_by_play_df.loc[idx - 10 : idx + 10][:])
free_throws = 0
while free_throws > 0: # Continue going down the play_by_play_df if there are still free throw shots to be taken
if play_by_play_df.loc[idx + shot_made_index + counter]['EVENTMSGTYPE'] == 4: # There is a nuance that team rebounds are often included in between free throws. If there is a rebound in the free throw sequence, move to th next index
counter += 1
continue
elif 'miss' not in str(play_by_play_df.loc[idx + shot_made_index + counter][team2]).lower(): # If a free throw is made
points_off_board += 1 # Add to the points scored on the possession
free_throws -= 1 # Decrease amount of free throws left to take
counter += 1 # Increase the index to check (next free throw is the next index)
else: # If the player missed, decrease the free throws left to shoot
free_throws -= 1
counter += 1
if (idx + shot_made_index + counter + 1 > len(play_by_play_df.index) - 1
or play_by_play_df.loc[idx + shot_made_index + counter + 1]['EVENTMSGTYPE'] == 4
and play_by_play_df.loc[idx + shot_made_index + counter][team1] != None): # If there is a defensive rebound after the free throw, give credit to the block based on the amount of free throws made
if points_off_board > defense_possession_value: # Don't penalize player who got the block for free throws, but give them value if the free throw shooter doesn't make enough
failed_blocks += 1
break
else:
current_player_blocks_score += (defense_possession_value - points_off_board) * block_before_turnover
break
else:
if points_off_board > defense_possession_value: # Don't penalize player who got the block for free throws, but give them value if the free throw shooter doesn't make enough
failed_blocks += 1
break
else:
current_player_blocks_score += (defense_possession_value - points_off_board) * block_before_turnover
break
else:
shot_made_index += 1 # Move down play_by_play_df one row
if current_player_blocks_score is None:
return 0
else:
return current_player_blocks_score, failed_blocks # Return the blocks score for this player for this game |
'''This is a solution to a given Problem statement:
Write a function record_notes() that does the following
A. First asks the user's name.
B. Asks the user to enter a single-line note. After the user enters the note, it is stored in
USERNAME_notes.txt on a newline.
C. Keeps asking the user to enter a note in a loop, or to type "exit" to exit the program.
D. Make sure that killing the program suddenly doesn't result in losing all the notes entered till that point.
E. You should be able to call record_notes() multiple times without deleting previous notes.
'''
import os
def record_notes():
user_name = input("Enter your name: ")
user_name = user_name + ".txt"
os.path.isfile('./user_name')
with open ( user_name, 'a+') as filePointer:
while( True):
text_input = input("Enter a Single Line Note: ")
if( text_input == "exit"):
print("Exiting")
break;
else:
filePointer.write(text_input)
filePointer.write("\n")
record_notes() |
# my_stuff={"key1":123,'key2':"value2","key3":{'123':[1,2,"grabme"]}}
# print(my_stuff["key3"]['123'][2].upper())
mystuff={'lunch':'puri','bfast':'eggs'} |
import turtle
from math import sqrt, sin, cos, pi
tela = turtle.Screen()
eletron = turtle.Turtle()
eletron.shape('circle')
eletron2 = turtle.Turtle()
eletron2.shape('circle')
a = 100
a2 = 50
b = a/2
b2 = a2*2
eletron.up()
eletron.setpos(a,0)
eletron.down()
eletron2.up()
eletron2.setpos(a2,0)
eletron2.down()
'''while True:
for angulo in range(361):
r = raio*sin(3*(pi*angulo/180))
x = r*cos(pi*angulo/180)
y = r*sin(pi*angulo/180)
eletron.setpos(x,y)'''
while True:
for angulo in range(361):
r = (a * b)/sqrt(a**2*sin(pi*angulo/180)**2 + b**2*cos(pi*angulo/180)**2)
r2 = (a2 * b2)/sqrt(a2**2*sin(pi*angulo/180)**2 + b2**2*cos(pi*angulo/180)**2)
x = r*cos(pi*angulo/180)
x2 = r2*cos(pi*angulo/180)
y = r*sin(pi*angulo/180)
y2 = r2*sin(pi*angulo/180)
xr = x*cos(pi/4) - y*sin(pi/4)
yr = x*sin(pi/4) + y*cos(pi/4)
eletron.setpos(xr,yr)
eletron.speed(10)
eletron2.setpos(x2,y2)
|
with open('../resources/input_day_2.txt', 'r') as input_file:
entries = []
for line in input_file.readlines():
character_condition = line.split(':')[0]
entries.append({
'password': line.split(':')[1].strip(),
'needed_character': character_condition.split(' ')[1],
'min_times': int(character_condition.split(' ')[0].split('-')[0]),
'max_times': int(character_condition.split(' ')[0].split('-')[1])
})
def valid_password(entry) -> bool:
character_count = entry['password'].count(entry['needed_character'])
return entry['min_times'] <= character_count <= entry['max_times']
def valid_password_v2(entry) -> bool:
password = entry['password']
expected_char = entry['needed_character']
first_char = password[entry['min_times'] - 1]
second_char = password[entry['max_times'] - 1]
if first_char == expected_char:
return second_char != expected_char
else:
return second_char == expected_char
if __name__ == "__main__":
valid_passwords = 0
for entry in entries:
if valid_password_v2(entry):
valid_passwords += 1
print(f"{valid_passwords} valid passwords")
|
"""
Created on 16/12/2019
@author: Sunny Raj
"""
"""
problem statement:
Write a program to multiply matrices
"""
#method to setup the value of row and column for input matrices
def criteria_setup():
while True:
try:
value=int(input())
break
except ValueError:
print("try again with proper value")
return value
# method/function to take input in matrix
def value_input(row,col):
#initializing empty matrix
matrix = []
#looping through the given row value
for index_x in range(row):
#initializing a temperory variable
temp=[]
#looping through the given column value
for index_y in range(col):
while True:
try:
value = int(input("enter value for [{}],[{}]".format(index_x,index_y)))
break
except ValueError:
print("try again with proper integer value")
#adding values to one row
temp.append(value)
#Aadding list into a list
matrix.append(temp)
#returning the 2d list / matrix
return matrix
#function to print row wise matrix
def display_matrix(matrix):
for mat in matrix:
print(mat)
#function that will take matrix and scalar matrix as input and gives multiplication of that
def matrix_multiplication(row_one,col_one,row_two,col_two,matrix_one,matrix_two):
#initializing the empty matrix
matrix = []
#looping through row value of first matrix
for col in range(row_one):
temp=[]
#looping through the column value of second matrix
for row in range(col_two):
temp.append(0)
matrix.append(temp)
#doing the multiplication
for index_x in range(len(matrix_one)):
for index_y in range(len(matrix_two[0])):
for index_z in range(len(matrix_two)):
#calcularting
matrix[index_x][index_y] += matrix_one[index_x][index_z] * matrix_two[index_z][index_y]
#returning the multiplicated matrix
return matrix
#runner function which is letting ecexuting this module
def runner():
while True:
try:
print("Enter row value for first matrix")
row_one=criteria_setup()
print("Enter column value for first matrix")
col_one = criteria_setup()
print("enter row value for second matrix")
row_two = criteria_setup()
print("enter column value for second matrix")
col_two=criteria_setup()
assert row_two==col_one and col_two==row_one
break
except AssertionError:
print("value of row of first matrix should be equal to value of column of second matrix and vice versa")
print("Start entering value for matrix one")
matrix_one= value_input(row_one,col_one)
print("start entering values for matrix two")
matrix_two=value_input(row_two,col_two)
print("your entered first matrix is :")
display_matrix(matrix_one)
print("your entered second matrix ix :")
display_matrix(matrix_two)
multiplied_matrix=matrix_multiplication(row_one,col_one,row_two,col_two,matrix_one,matrix_two)
print("matrix after multiplication is :")
display_matrix(multiplied_matrix)
runner() |
#importing necessarry libraries
#importing flask , jsonify,request
from flask import Flask, jsonify, request
import pymongo
#seeting name to run this file as flask app
app = Flask(__name__)
#making a mongo db client to interact eith mongodb server
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
#making an object of database with the help of mongodb client
my_database = myclient["BookManager"]
#making an object of bookstore collection to perform query operations
my_col = my_database["bookstore"]
#base url directed towards getting whole table
@app.route('/')
def index():
return show_collections()
#method that takes get type of request
#returns the list of collections that are present in current database
@app.route('/db', methods=['GET'])
def show_collections():
#obtaining the list of collection names present inside database
my_result=my_database.list_collection_names()
#returning json response
return jsonify(my_result)
#method that takes get type of request
#returns the list of enteries that are present in current collection
@app.route('/entries', methods=['GET'])
def get_collection_items():
#obtaining the list of collection names present inside database
my_result=list(my_col.find())
#looping just to remove object id
for i in range(len(my_result)):
#making object id 0
my_result[i]['_id']=0
#returning json response
return jsonify(my_result)
#method that takes post type of request
#returns the list of enteries that are present in current collection after inserting one
@app.route('/create', methods=['POST'])
def create_collection_item():
#taking json request
creation_data = request.json
#inserting json request into database
my_col.insert_one(creation_data)
#fetching data after created entry and returning updated collection
return get_collection_items()
#method that takes post type of request
#returns the list of enteries that are present in current collection after deleting the requested entry
@app.route('/delete', methods=['POST'])
def delete_collection_item():
#taking json request
deletion_data = request.json
#inserting json request into database
my_col.delete_one(deletion_data)
#fetching data after created entry and returning updated collection
return get_collection_items()
#method that takes post type of request
#returns the list of enteries that are present in current collection after updating the requested entry
@app.route('/update', methods=['POST'])
def update_collection_item():
#taking json request
updation_data = request.json
#inserting json request into database
my_col.update_one(updation_data[0],updation_data[1])
#fetching data after created entry and returning updated collection
return get_collection_items()
if __name__ == '__main__':
app.run(debug=True) |
tup1 = ('physics', 'chemistry', 1997, 2000)
tup2 = (1, 2, 3, 4, 5, 6, 7 )
print("tup1[0]: ", tup1[0])
print("tup2[1:5]: ", tup2[1:5])
tup1 = (12, 34.56)
tup2 = ('abc', 'xyz')
# Following action is not valid for tuples
# tup1[0] = 100;
# So let's create a new tuple as follows
tup3 = tup1 + tup2
print(tup3)
tup = ('physics', 'chemistry', 1997, 2000)
print(tup)
del tup;
print("After deleting tup : ")
print(tup)
|
def is_ugly(num, divisor):
print(f"Divisor is {divisor}")
if(divisor <= 1 ):
return True
if(
(num % divisor == 0
and divisor not in [2,3,5])
or
(divisor in [2,3,4] and num % divisor != 0)
):
return False
return is_ugly(num, divisor-1);
number = int(input("Enter Number of ugly numbers to be printed "))
print(number);
print(is_ugly(number, (number// 2))) |
degreeF = float(input("Enter temperature in degree F "))
degreeC = (5/9)*(degreeF - 32)
print(f" Converted value is {degreeC} ") |
import sqlite3
class database:
def __init__(self, db_name):
self.conn = sqlite3.connect(db_name)
self.cur = self.conn.cursor()
def create_table(self, table_name, cols):
if len(cols) > 0 and bool(table_name):
command = f'create table if not exists {table_name}('
for col in cols.values():
name, type, constraints = col.values()
if constraints:
command += f'{name} {type} {constraints},'
else:
command += f'{name} {type},'
command = command[0:len(command)-1]
command += ')'
self.cur.execute(command)
self.conn.commit()
def insert_values(self, table_name, values):
if table_name and values:
for row_values in values.values():
command = f'insert into {table_name} values('
for value in row_values.values():
command += f'{value},'
command = command[0:len(command)-1]
command += ')'
self.cur.execute(command)
self.conn.commit()
elif not table_name:
print('Failer 1 : table name is not identified')
elif not values:
print('Failer 2 : no value found')
else:
print('Failer 1, 2 : Table name is not identified and no value found')
def query(self,query_strcture):
command ='select '
db_cols = {
1: {
'col_name': 'c1',
'data_type': 'TEXT',
'constraints': ''
},
2: {
'col_name': 'c2',
'data_type': 'INTEGER',
'constraints': 'NOT NULL'
},
3: {
'col_name': 'c3',
'data_type': 'TEXT',
'constraints': 'UNIQUE'
},
}
db_data = {
1: {'c1': '\'fffff\'',
'c2': 96455,
'c3': '"hello"'},
2:
{'c1': '\'qqqqqq\'',
'c2': 65465,
'c3': '"welcome"'},
3:
{'c1': '\'ffnbf g\'',
'c2': 9849418,
'c3': '"hai"'},
}
db_query={
'query':'*',
'from ':'userC',
'where':'c2 > 1000'
}
db = database('a.sqlite3')
db.create_table(table_name='userC', cols=db_cols)
db.insert_values(table_name='userC', values=db_data)
|
# # import libraries
from urllib.request import urlopen
from bs4 import BeautifulSoup
quote_page = "https://en.wikipedia.org/wiki/Ada_Lovelace"
# # query the website and return the html to the variable page
page = urlopen(quote_page)
soup = BeautifulSoup(page, 'html.parser')
name = soup.find(attrs={'id': 'firstHeading'})
name = name.text.strip()
print(name)
|
"""
Implementation of Sequential Backward Selection
Python Machine Learning Ch 4
"""
import numpy as np
from sklearn.base import clone
from itertools import combinations
from sklearn.cross_validation import train_test_split
from sklearn.metrics import accuracy_score
class SBS():
def __init__(self, estimator, k_features, test_size=0.25,
scoring=accuracy_score, random_state=1):
self.estimator = clone(estimator) # constructs a new estimator with the same parameters (deep copy)
self.k_features = k_features # desired number of features
self.test_size = test_size # percentage of data to split off for testing
self.scoring = scoring # scoring metric
self.random_state = random_state # input used for random sampling by test_train_split()
def fit(self, X, y):
"""
X is an m * n matrix and y is an m element vector
m: number of observations
n: number of features per observation
Note that X_train is passed to this function and not the original X.
In other words, the test set (validation set) is not used to perform SBS.
This function goes onto split X_train into training and testing sets for SBS.
"""
# split data into training and testing for SBS
X_train, X_test, y_train, y_test = (
train_test_split(X, y, test_size=self.test_size,
random_state=self.random_state)
)
dim = X_train.shape[1] # number of features
self.indices_ = tuple(range(dim)) # (0, 1, 2, ..., m-1)
self.subsets_ = [self.indices_] # [(0, 1, 2, ..., m-1)]
# score the original set containing all n features
score = self._calc_score(X_train, y_train, X_test, y_test, self.indices_)
self.scores_ = [score] # instantiate scores_ as a list with m-score
while dim > self.k_features: # while d > k (there are still dimensions to remove)
scores = [] # accumulate potential scores
subsets = [] # accumulate potential subsets
# for each subset of size dim-1 (combinations returns all r-element subsets)
for p in combinations(self.indices_, r=dim-1):
score = self._calc_score(X_train, y_train, X_test, y_test, p) # calc score for this combination
scores.append(score) # append score to scores
subsets.append(p) # append p to subsets
best = np.argmax(scores) # a maximum accuracy score determines the best subset
self.indices_ = subsets[best] # append the best subset to indices_
self.subsets_.append(self.indices_) # append the best subset to subsets_
dim -= 1 # decrement dim
self.scores_.append(scores[best]) # append the best score to scores_
self.k_score_ = self.scores_[-1] # upon reaching k features, report the last score
return self # return sbs instance after fitting
def transform(self, X):
return X[:, self.indices_] # projection to retain only the columns in self.indices_
def _calc_score(self, X_train, y_train, X_test, y_test, indices):
self.estimator.fit(X_train[:, indices], y_train) # use the estimator to fit X with columns in indices
y_pred = self.estimator.predict(X_test[:, indices]) # use the estimator to generate y_pred vector
score = self.scoring(y_test, y_pred) # use the scoring method to evaluate model
return score
# EOF
|
# Convert WAV file(s) to MP3 using Pydub (http://pydub.com/)
# Imports
import os
import pydub
import glob
# Load local WAV files(s)
wav_files = glob.glob('../test/*.wav')
# Iterate and convert
for wav_file in wav_files:
mp3_file = os.path.splitext(wav_file)[0] + '.mp3'
sound = pydub.AudioSegment.from_wav(wav_file)
sound.export(mp3_file, format="mp3")
os.remove(wav_file)
# Print complete message to console
print("WAV to MP3 conversion complete")
|
import numpy as np
contador = np.arange(10)
km2 = np.array([44410., 5712., 37123., 0., 25757.])
anos2 = np.array([2003, 1991, 1990, 2019, 2006])
dados = np.array([km2, anos2])
item = 6
index = item - 1
print(contador[index])
print(dados[1][2]) # array[linha][coluna] |
class Stack:
def __init__(self):
self.items = []
self.length = 0
def push(self, val):
self.items.append(val)
self.length += 1
def pop(self):
if self.empty():
return None
self.length -= 1
return self.items.pop()
def size(self):
return self.length
def peek(self):
if self.empty():
return None
return self.items[0]
def empty(self):
return self.length == 0
def __str__(self):
return str(self.items)
precedence = {}
precedence['*'] = 3
precedence['/'] = 3
precedence['+'] = 2
precedence['-'] = 2
precedence['('] = 1
def convert(expression):
print(__convert(expression.split()))
def __convert(tokens):
postfix = []
opstack = Stack()
for token in tokens:
if token.isidentifier():
postfix.append(token)
elif token == '(':
opstack.push(token)
elif token == ')':
while True:
temp = opstack.pop()
if temp is None or temp == '(':
break
elif not temp.isidentifier():
postfix.append(temp)
else: # must be operator
if not opstack.empty():
temp = opstack.peek()
while not opstack.empty() and precedence[temp] >= precedence[token] and token.isidentifier():
postfix.append(opstack.pop())
temp = opstack.peek()
opstack.push(token)
while not opstack.empty():
postfix.append(opstack.pop())
return postfix
convert("a * ( b + c ) * ( d - g ) * h")
|
# Joshua Chan
# 1588459
import datetime
items_list = []
manufacturer_file = input("Enter the filename of Manufacturers List")
with open(manufacturer_file) as file:
data = file.readlines()
for row in data:
row_dict = dict()
fields = row.split(',')
row_dict['item_id'] = fields[0]
row_dict['manufacturer_name'] = fields[1]
row_dict['item_type'] = fields[2]
row_dict['damaged_ind'] = fields[3].replace('\n', '')
items_list.append(row_dict)
# The code above will accept the input and open the corresponding file and add items to a dictionary
price_file = input("Enter the filename with Price data:")
with open(price_file) as file:
data = file.readlines()
for row in data:
fields = row.split(',')
for item in items_list:
if item['item_id'] == fields[0]:
item['price'] = int(fields[1].replace('\n', ''))
# The code above will accept the input and open the corresponding file and add items to a dictionary
service_file = input("Enter the filename of Service Date List")
with open(service_file) as file:
data = file.readlines()
for row in data:
fields = row.split(',')
for item in items_list:
if item['item_id'] == fields[0]:
item['service_date'] = fields[1].replace('\n', '')
# The code above will accept the input and open the corresponding file and add items to a dictionary
items_list = sorted(items_list, key=lambda i: i['manufacturer_name'])
with open('FullInventory.csv', 'w') as inventory_file:
for item in items_list:
inventory_file.write(
item['item_id'] + ',' + item['manufacturer_name'] + ',' + item['item_type'] + ',' + str(
item['price']) + ',' +
item['service_date'] + ',' + item['damaged_ind'] + '\n')
# The code above will create the FullInventory file and add the item ID, Manufacturer name, type, price, service date, and if it is damaged
items_by_their_types = dict()
for item in items_list:
if item['item_type'] not in items_by_their_types:
items_by_their_types[item['item_type']] = []
for type in items_by_their_types:
file_name = type + 'Inventory.csv'
with open(file_name, 'w') as file:
for item in items_list:
if item['item_type'] == type:
items_by_their_types[item['item_type']].append(item)
file.write(
item['item_id'] + ',' + item['manufacturer_name'] + ',' + str(item[
'price']) + ',' + item[
'service_date'] + ',' + item['damaged_ind'] + '\n')
CurrentDate = str(datetime.datetime.now())[:10]
CurrentDate = datetime.datetime.strptime(CurrentDate, "%Y-%m-%d")
items_expired = []
with open('PastServiceDateInventory.csv', 'w') as file:
sorted_by_date = sorted(items_list, key=lambda i: i['service_date'])
for item in sorted_by_date:
ExpectedDate = item['service_date']
ExpectedDate = datetime.datetime.strptime(ExpectedDate, "%m/%d/%Y")
if ExpectedDate <= CurrentDate:
items_expired.append(item['item_id'])
file.write(
item['item_id'] + ',' + item['manufacturer_name'] + ',' + item['item_type'] + ',' + str(item[
'price']) + ',' +
item['service_date'] + ',' + item['damaged_ind'] + '\n')
# Above will create a file for items that are past their service date
print(items_expired)
with open('DamagedInveentory.csv', 'w') as file:
sorted_by_price = sorted(items_list, key=lambda i: i['price'], reverse=True)
for item in sorted_by_price:
if item['damaged_ind'] == 'damaged':
file.write(
item['item_id'] + ',' + item['manufacturer_name'] + ',' + item['item_type'] + ',' + str(item[
'price']) + ',' +
item['service_date'] + '\n')
# Above will create a file for damaged items
while 1:
manufacturer = input("Enter the manufacturer: ")
item_type = input("Enter the item_type: ")
items_list = sorted(items_list, key=lambda i: i['price'], reverse=True)
found = False
found_item = None
for item in items_list:
if manufacturer in item['manufacturer_name'] and item_type == item['item_type'] and item[
'damaged_ind'] != 'damaged' and item['item_id'] not in items_expired:
found = True
found_item = item
print('Your Item is:',item['item_id'],item['manufacturer_name'],item['item_type'], item['price'])
# The inputs above will take the user's requirements and find a product for them
if not found:
print('No such Item in inventory')
elif item_type in items_by_their_types:
closest_item = items_by_their_types[item_type][0]
for item in items_by_their_types[item_type]:
if item['damaged_ind'] != 'damaged' and item['item_id'] not in items_expired and item['price']-found_item['price']<closest_item['price']:
print('Your may consider:',item['item_id'],item['manufacturer_name'],item['item_type'], item['price'])
break
# If a product is not found then it will print no such item in inventory, a recommendation will be given as well which is similar to the first
choice = input("'q' to quit")
if choice == 'q':
break
# q will terminate the program |
'''Python file for the pre_order traversal
This is a helper class used to generate the pre-order traversal of a given ast
'''
from ...nodes import AST
from ...nodes import Number_Node, String_Node, UnaryOp_Node, BinaryOp_Node, Function_Node
from .traversal import Traversal
class PreOrderTraversal(Traversal):
def __init__(self):
self.__traversal = []
# Public methods
def traverse(self, ast: AST):
'''
Public method called to get the traversal graph
'''
self.visit(ast)
return self.__traversal
# Node Type Visitor Implementation
def visit_BinaryOp_Node(self, node: BinaryOp_Node, level: int=1):
token = node.token
self.__traversal.append(f"{'>'*level}: {str(token)}")
self.visit(node.left, level=level+1)
self.visit(node.right, level=level+1)
def visit_UnaryOp_Node(self, node: UnaryOp_Node, level: int=1):
token = node.token
self.__traversal.append(f"{'>'*level}: {str(token)}")
self.visit(node.child, level=level+1)
def visit_Function_Node(self, node: Function_Node, level: int=1):
token = node.token
self.__traversal.append(f"{'>'*level}: {str(token)}")
for argument in node.arguments:
self.visit(argument, level=level+1)
def visit_Number_Node(self, node: Number_Node, level: int=1):
token = node.token
self.__traversal.append(f"{'>'*level}: {str(token)}")
def visit_String_Node(self, node: String_Node, level: int=1):
token = node.token
self.__traversal.append(f"{'>'*level}: {str(token)}")
|
'''Python file for common algorithms
Mainly used to store algorithms written to make usage more convenient
'''
def bin_to_decimal(s: str):
'''
Helper function that takes in a binary string and returns the converted decimal number
'''
for c in s:
assert c in set(['.', '1', '0'])
decimal_value = 0
frac = False
frac_power = 1
for c in s:
if c == '.':
frac = True
continue
else:
parsed_c = int(c)
if not frac:
decimal_value *= 2
decimal_value += parsed_c
else:
decimal_value += parsed_c * (2**(-frac_power))
frac_power += 1
return decimal_value
def hex_to_decimal(s: str):
'''
Helper function that takes in a hexadecimal string and returns the converted decimal number
'''
a_ord = ord('A')
for c in s:
assert c in set(['.'] + [str(num) for num in range(10)] + [chr(a_ord + offset) for offset in range(6)])
decimal_value = 0
frac = False
frac_power = 1
for c in s:
if c == '.':
frac = True
continue
else:
if c in set([str(num) for num in range(10)]):
parsed_c = int(c)
elif c in set([chr(a_ord + offset) for offset in range(6)]):
parsed_c = 10 + ord(c) - a_ord
if not frac:
decimal_value *= 16
decimal_value += parsed_c
else:
decimal_value += parsed_c * (16**(-frac_power))
frac_power += 1
return decimal_value
if __name__ == '__main__':
print(bin_to_decimal('1101'))
print(bin_to_decimal('1101.1101'))
print(hex_to_decimal('91ABF.FFF'))
|
'''Python file for compiler's lexer
This contains the Lexer class which handles turning the input text(raw expression) into a series of tokens
'''
# Importing token types
from ..tokens import Token
from ..tokens.token_type import PLUS, MINUS, MUL, DIV, MODULUS, INT_DIV, POWER, LPARAM, RPARAM, COMMA, EOF
from ..tokens.token_type import NUMBER, IDENTIFIER, STRING
from ..tokens.token_type import RESERVED_KEYWORDS
# Building the Lexer class
class Lexer(object):
def __init__(self, text):
self.__text = text
self.__tokens = []
self.__cur_pos = 0
# Class helper methods
def __check_end(self, pos: int):
'''
Helper private method to check if the position given has already reached the end of the text
'''
return pos >= len(self.__text)
def __get_char(self, pos: int):
'''
Helper private method to get the char at a given pos
If the pos has reached the end, return None
'''
if not self.__check_end(pos):
return self.__text[pos]
return None
# TODO: Chuan Hao, implement the syntax error
def __syntax_error(self):
pass
def __error(self):
# Placeholder error method
# TODO: Make proper one
raise Exception('Lexer error')
# Class auxiliary methods
@property
def __cur_char(self):
'''
Auxiliary private method to return the current char of the lexer
'''
return self.__get_char(self.__cur_pos)
@property
def __peek(self):
'''
Auxiliary private method to peek at the next char without moving the lexer
'''
return self.__get_char(self.__cur_pos + 1)
@property
def __is_end(self):
'''
Auxiliary private method to check if the lexer has reached the end
'''
return self.__check_end(self.__cur_pos)
def __advance(self):
'''
Auxiliary private method to advance the lexer to the next character
'''
self.__cur_pos += 1
# Lexer, utility methods
def __is_whitespace(self, c: str):
if c is None:
return False
return c.isspace()
def __is_quote(self, c: str):
if c is None:
return False
return c == "\'"
def __is_digit(self, c: str):
if c is None:
return False
return c.isdigit()
def __is_alpha(self, c: str):
if c is None:
return False
return c.isalpha()
# Lexer logic methods
def __skip_whitespace(self):
'''
Private method used to skip whitespace as it is ignored
'''
while self.__is_whitespace(self.__cur_char):
self.__advance()
return
def __number(self):
'''
Private method used to tokenize number tokens
'''
pos = self.__cur_pos
number_value = ''
# For any digits before, DIGIT*
while self.__is_digit(self.__cur_char):
number_value += self.__cur_char
self.__advance()
# If there is a '.'
if self.__cur_char == '.':
number_value += '.'
self.__advance()
# Rest of DIGIT+
while self.__is_digit(self.__cur_char):
number_value += self.__cur_char
self.__advance()
# Error checking if it was only a .
if number_value == '.':
self.__error()
number_value = float(number_value)
return Token(NUMBER, number_value, pos)
def __identifier(self):
'''
Private method used to tokenize identifiers
Differentiated with no quotes and only alphas
'''
pos = self.__cur_pos
identifier_value = ''
while self.__is_alpha(self.__cur_char):
identifier_value += self.__cur_char
self.__advance()
# Invalid identifier
# Only accepts reserved keywords
if identifier_value not in RESERVED_KEYWORDS:
self.__error()
return Token(IDENTIFIER, identifier_value, pos)
def __string(self):
'''
Private method used to tokenize strings
'''
pos = self.__cur_pos
string_value = ''
# Need first quote
if self.__is_quote(self.__cur_char):
self.__advance()
else:
self.__error()
# Consume all chars in the middle
while not self.__is_quote(self.__cur_char) and self.__cur_char is not None:
string_value += self.__cur_char
self.__advance()
# Need ending quote
if self.__is_quote(self.__cur_char):
self.__advance()
else:
self.__error()
return Token(STRING, string_value, pos)
# Main lexer methods
def __get_next_token(self):
'''
Private method to get the next token from the given text
'''
if not self.__is_end:
# Skipping all the ignored chars
if self.__is_whitespace(self.__cur_char):
self.__skip_whitespace()
return self.__get_next_token()
# Checking single char tokens
if self.__cur_char == '+':
token = Token(PLUS, '+', self.__cur_pos)
self.__advance()
return token
elif self.__cur_char == '-':
token = Token(MINUS, '-', self.__cur_pos)
self.__advance()
return token
elif self.__cur_char == '%':
token = Token(MODULUS, '%', self.__cur_pos)
self.__advance()
return token
elif self.__cur_char == '(':
token = Token(LPARAM, '(', self.__cur_pos)
self.__advance()
return token
elif self.__cur_char == ')':
token = Token(RPARAM, ')', self.__cur_pos)
self.__advance()
return token
elif self.__cur_char == ',':
token = Token(COMMA, ',', self.__cur_pos)
self.__advance()
return token
# Checking double char tokens
if self.__cur_char == '*':
# If POWER
if self.__peek == '*':
token = Token(POWER, '**', self.__cur_pos)
self.__advance()
self.__advance()
return token
# else MUL
token = Token(MUL, '*', self.__cur_pos)
self.__advance()
return token
elif self.__cur_char == '/':
# If INT_DIV
if self.__peek == '/':
token = Token(INT_DIV, '//', self.__cur_pos)
self.__advance()
self.__advance()
return token
# else DIV
token = Token(DIV, '/', self.__cur_pos)
self.__advance()
return token
# Check multi-strings
# Check NUMBER, then IDENTIFIER, then STRING
if self.__is_digit(self.__cur_char) or self.__cur_char == '.':
return self.__number()
elif self.__is_alpha(self.__cur_char):
return self.__identifier()
elif self.__is_quote(self.__cur_char):
return self.__string()
# If not able to tokenize, error
self.__error()
# If we have reached the end, EOF
return Token(EOF, None, self.__cur_pos)
# Public methods
def get_tokens(self):
'''
Public method to get the tokens tokenized by the lexer
'''
# If lexer has already tokenized the text
if len(self.__tokens) > 0:
return self.__tokens
tokens = []
while True:
cur_token = self.__get_next_token()
tokens.append(cur_token)
if cur_token.type == EOF:
break
self.__tokens = tokens
return self.__tokens
|
""" # ЗАДАЧА А
q = int(input())
w = int(input())
e = int(input())
r = int(input())
t = (min(q,w,e,r))
print(t)
"""
""" # ЗАДАЧА B
w = int(input())
s = int(input())
print(w**s)
"""
""" # ЗАДАЧА C
r = int(input())
e = int(input())
f = r ^ e
print(f)
""" |
import math
import random
#### Section 1: Measures of Variance and Central Tendancy
## mean, median, mode, standard variance, standard deviation, and confidence interval
def mean(data):
"""The mean or average of a set of data is the sum of all data
points divided by the amount of data points.
"""
if not isinstance(data, list):
raise Error("input must be of type list")
return
return sum(data)/len(data)
def standard_variance(data):
""" The standard variance is the average distance from each
data point to the mean of the data set
"""
if not isinstance(data, list):
raise Error("input must be of type list")
return
return (sum([x*x for x in data])-sum(data)*mean(data))/(len(data)-1)
def standard_deviation(data):
if not isinstance(data, list):
raise Error("input must be of type list")
return
return math.sqrt(standard_variance(data))
def confidence_interval(data):
if not isinstance(data, list):
raise Error("input must be of type list")
return
standard_deviation(data)/math.sqrt(len(data))
def median(data):
""" Finds the median using Tony Hoare's recursive quickselect algorithm
This method picks the appropriate way to call the recursive method based on
whether the dataset has an even or odd number of members
Average of O(n) time
"""
pivot_fn = random.choice
if len(data) % 2 == 1: # case for datasets of even length
return quickselect(data, len(data) // 2, pivot_fn)
else: # case for odd length
0.5 * (quickselect(data, len(data) / 2 - 1, pivot_fn) + quickselect(data, len(data) / 2, pivot_fn))
def quickselect(data, index, pivot_fn):
if len(data) == 1:
assert index == 0
return data[0]
pivot = pivot_fn(data)
less = [x for x in data if x<pivot] # all points less than the chosen pivot
greater = [x for x in data if x>pivot] # all points greater than the chosen pivot
equal = [x for x in data if x == pivot] # all points equal to the chosen pivot
if index < len(less): # if
return quickselect(less, index, pivot_fn)
elif index < len(less) + len(equal):
return equal[0]
else:
return quickselect(greater, index - (len(less) + len(equal)), pivot_fn)
print(median([5,6,3,2,4,7,1]))
def z_score(data, value):
return (value - mean(data))/standard_deviation(data)
def probability(data, value):
# get z-score and look it up (grr)
return 0 |
# Official Name: Janet Lee
# Lab section: M3
# email: [email protected]
# Assignment: Assignment 2, problem 1.
# Date: September 10, 2019
# Compute a receipt for Gracie's Garden Store
print("Welcome to Gracie's!")
print("Let the sun shine in!")
print()
print("For each item, enter the quantity, then press ENTER")
import math
def main():
#Ask for number of pansies
p=eval(input("PANSIES:"))
#Compute cost of total pansies
dp=(p//12)
sp=(p%12)
tpc=((6.5*(dp))+(.58*(sp)))
#Ask for number of tulip bulbs
tb=eval(input("TULIP BULBS:"))
#Compute cost of total tulip bulbs
qtb=(tb//4)
stb=(tb%4)
ttbc=((2.5*(qtb))+(.7*(stb)))
#Ask for number of rose bushes
rb=eval(input("ROSE BUSHES:"))
#Compute cost of total rose bushes
trb=(rb//3)
srb=(rb%3)
trbc=((20*(trb))+(8.5*(srb)))
#Ask for number of begonias
b=eval(input("BEGONIAS:"))
#Compute cost of total begonias
db=(b//2)
sb=(b%2)
tbc=((30*(db))+(17*(sb)))
#Ask for number of hydrangeas
h=eval(input("HYDRANGEAS:"))
#Compute cost of total hydrangeas
qh=(h//4)
sh=(h%4)
thc=((120*(qh))+(32*(sh)))
#Compute total number of flowers and total cost
tf=p+tb+rb+b+h
tc=tpc+ttbc+trbc+tbc+thc
print()
print()
print("Your Receipt")
print("PANSIES","\t", p, "\t", "$", tpc)
print("TULIP BULBS", "\t", tb, "\t", "$", ttbc)
print("ROSE BUSHES", "\t", rb, "\t", "$", trbc)
print("BEGONIAS","\t", b, "\t", "$", tbc)
print("HYDRANGEAS","\t", h, "\t", "$", thc)
print("----------------------------------------------------")
print("TOTAL","\t","\t", tf, "\t", "$", tc)
main ()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.