text stringlengths 37 1.41M |
|---|
def readString(a):
s = input(a+": ")
return s
def readDigit(a):
s = input(a+": ")
try:
f = int(s)
except ValueError:
f = float(s)
return f
try:
country = readString("country")
wealth = readDigit("wealth")
lifeExp = readDigit("life expectancy")
footPr = readDigit("foot print")
hpi = wealth*lifeExp/footPr
print("De HPI van "+country+" is "+"%0.2f" % hpi +".")
except ValueError as exp:
print("Error", exp) |
import json
with open('input.json,'r') as f:
inputjson = json.load(f)
Remove element from json object
Json to python conversion
Object -> Dict
Array -> List
String ->str
false ->False
null -> None
#Remove element crime from state Object
for state in inputjson['states']:
del state['crime']
#export python dict to Json file
with open('output.json','w') as w:
json.dump(inputjson,w,indent=2)
####
get and parse json from feed or site
import jsonfrom urllib.request import urlopen
with urlopen('https://mysite') as response:
source = response.read()
#convert string to python object
data = json.loads(source)
|
#Currency converter for Euro
def desiredDate(dates): #entered value must be a string
# Input Rapidapikey provided by the rapidapi webpage
RAPIDAPIKEY = 'd88ac81114msh89e702e586cd793p16570djsn90c636b78795'
dates = str(dates)
# import
import http.client
import json
import pandas as pd
import numpy as np
from datetime import date
import matplotlib.pyplot as plt
# Establish the connection to the particular API
conn = http.client.HTTPSConnection("currency-converter5.p.rapidapi.com")
headers = {'x-rapidapi-host': "currency-converter5.p.rapidapi.com",'x-rapidapi-key': RAPIDAPIKEY}
# First we will find the List of available currencies:
# The select API have been provided free of cost and is available for everyone
conn.request("GET", "/currency/list", headers=headers)
resp = conn.getresponse()
data = resp.read().decode("utf-8")
currency = json.loads(data)
# Next, we will check the currency exchange rate based on 1 euro
#This means that we will obtain all the currencies values equal to 1 euro
conn.request("GET", "/currency/convert", headers=headers)
resp = conn.getresponse()
data2 = resp.read().decode("utf-8")
convert = json.loads(data2)
#change the data to a dataframe
currency_df= pd.DataFrame(currency)
print(currency_df)
print("Base amount Value: ",convert['amount'])
print("Currency Base Name: ",convert['base_currency_name'])
print("Currency Base Code: ",convert['base_currency_code'])
# we put the current date to have a better visualization of the output
today = date.today()
print("Today's date:", today)
print('\n')
print('Today, the exchange currency values are:\n')
#change the data to a dataframe
convert_df= pd.DataFrame(convert['rates'])
convert_df = convert_df.drop('rate_for_amount')
print(convert_df)
print('\n')
print(dates, "The requested date exchange currency values are:\n")
# prepare the dynamic code so we may choose which date we want to see the currency
Requesteddate ="/currency/historical/" + dates + ""
conn.request("GET", Requesteddate, headers=headers)
resp = conn.getresponse()
data = resp.read().decode("utf-8")
historical = json.loads(data)
#change the data to a dataframe
historical_df= pd.DataFrame(historical['rates'])
historical_df = historical_df.drop('rate_for_amount')
print(historical_df)
|
# reference: https://github.com/rasbt/deeplearning-models/blob/master/pytorch_ipynb/cnn/cnn-vgg16-celeba.ipynb
# dataset preparation process follows the steps used in the reference
import pandas as pd
import os
# file containing the attributes of each image, such as the gender of the person in the image
# which will be used here
ATTR_PATH = os.path.dirname(os.path.realpath(__file__)) + '/../data/list_attr_celeba.txt'
# file containing the recommended way of partitioning the data into train, validation and test dataset
# where 0=train, 1=validation and 2=test
EVAL_PATH = os.path.dirname(os.path.realpath(__file__)) + '/../data/list_eval_partition.txt'
# read the attr file
# it is separated with whitespaces, thus, we use \s+ which represents 1 or more whitespaces
# skiprows=1 means we skip 1 row from the top of the file, this is because the first row states the number of images
# usecols=['Male'] for gender classfication
attr_df = pd.read_csv(ATTR_PATH, sep='\s+', skiprows=1, usecols=['Male'])
# replace -1 with 0
attr_df.loc[lambda df: df['Male'] == -1] = 0
attr_df.columns = ['Label']
# read partition file
eval_df = pd.read_csv(EVAL_PATH, sep='\s+', header=None)
eval_df.columns = ['Images', 'Partition']
eval_df = eval_df.set_index('Images')
# merge attr_df and eval_df to get image data & its label in the same place
# and we can see which (image, label) belongs to which partition
merged_df = attr_df.merge(eval_df, left_index=True, right_index=True)
# write to csv depending on the partition
# the csv file will be read by custom dataset class
TRAIN_CSV = os.path.dirname(os.path.realpath(__file__)) + '/../data/celeba-train.csv'
VAL_CSV = os.path.dirname(os.path.realpath(__file__)) + '/../data/celeba-val.csv'
TEST_CSV = os.path.dirname(os.path.realpath(__file__)) + '/../data/celeba-test.csv'
merged_df.loc[lambda df: df['Partition'] == 0].to_csv(TRAIN_CSV, columns=['Label'])
merged_df.loc[lambda df: df['Partition'] == 1].to_csv(VAL_CSV, columns=['Label'])
merged_df.loc[lambda df: df['Partition'] == 2].to_csv(TEST_CSV, columns=['Label']) |
# Write regex and scan contract to capture the dates described
regex_dates = r"Signed\son\s(\d{2})/(\d{2})/(\d{4})"
dates = re.search(regex_dates, contract)
# Assign to each key the corresponding match
signature = {
"day": dates.group(2),
"month": dates.group(1),
"year": dates.group(3)
}
# Complete the format method to print-out
print("Our first contract is dated back to {data[year]}.
Particularly, the day {data[day]} of the month {data[month]}.".format(data=signature))
|
# Include both variables and the result of dividing them
print(f"{number1} tweets were downloaded in {number2} minutes indicating a speed of {number1/number2:.1f} tweets per min")
# Replace the substring http by an empty string
print(f"{string1.replace('https', '')}")
# Divide the length of list by 120 rounded to two decimals
print(f"Only {(len(list_links)*100/120):.2f}% of the posts contain links")
|
s = input()
aa=input()
ba=input()
if(s>=a):
if(s<=ba):
print("Yes")
elif(s<=aa):
if(s>=ba):
print("yes")
else:
print("no")
|
a = input()
if (a % 4) == 0:
if (a % 100) == 0:
if (a % 400) == 0:
print(" leap year")
else:
print(" not a leap year")
else:
print(" leap year")
else:
print(" not a leap year")
|
x = input("Enter file name: ")
y = 0
with open(x, 'r') as f:
for c in f:
y += 1
print(y)
|
def reverse(s):
str = ""
for i in s:
str = i + str
return str
s = input()
print (end="")
print (s)
print (end="")
print (reverse(s))
|
x1,k1=input("Enter string and a char:").split(' ')
s=x1.count(k1)
print(s)
|
a=raw_input()
b=raw_input()
if(len(a)>len(b)):
print(a)
elif(len(a)==len(b)):
print(b)
else:
print(b)
|
s =raw_input()
rev = ''.join(reversed(s))
if (s == rev):
print("palindrome")
else:
print("not palindrome")
|
from passwordGenerator import create_password
from Database import getData,addData,\
removeService,editService
def get():
global key
service = input("Enter Service Name: ")
if not getData(service):
print("Service not found")
choice = input("Would you like to enter another Service? (Y/N) : ")
if choice == 'Y' or choice == 'y':
get()
def create():
global key
service = input("Enter Service Name: ")
userName = input("Enter User Name: ")
password = create_password(service)
if addData(service, userName, password) is False:
choice = input("Service already exists. Would you like to add another service? (Y/N)")
if choice == 'y' or choice == 'Y':
create()
else:
print("Your password is: " + password)
def add():
global key
service = input("Enter Service Name: ")
userName = input("Enter User Name: ")
password = input("Enter Password: ")
if addData(service, userName, password) is False:
choice = input("Service already exists. Would you like to add another service? (Y/N)")
if choice == 'y' or choice == 'Y':
add()
def remove():
global key
service = input("Enter Service Name: ")
if removeService(service) is False:
print("Service not found")
choice = input("Would you like to enter another Service? (Y/N) : ")
if choice == 'Y' or choice == 'y':
remove()
def edit():
global key
service = input("Enter Service Name: ")
if editService(service) is False:
print("Service not found")
choice = input("Would you like to enter another Service? (Y/N) : ")
if choice == 'Y' or choice == 'y':
edit()
|
coffees = ["mocha", "cappuccino", "flat white", "latte", "espresso"]
# coffee menu
price_of_coffees = [1, 1, 2, 1, 2]
# prices for coffees
price_total = []
# empty list for later
chosen_coffees = []
# also list for later
trying_for_integer = True
# bool
starting_code = True
# bool
print("\u2022please choose one of the following coffees:{}".format(coffees))
# shows coffee menu
while starting_code:
# *while true
try:
exit_code = input("\u2022If you want to exit the code please press 'q',"
" or if you want to continue please type in 'order' ").lower().strip()
# type 'q' or 'order'
if exit_code == "q":
exit()
# 'q' exits the code
starting_code = False
# it also causes the loop above to stop, thus less bugs
if exit_code == "order":
# if input is 'order'
while trying_for_integer:
# *while true
try:
num_of_coffee = int(input("\u2022 How many coffees would you like?").strip())
# asks for amount of coffees and stores the integer
trying_for_integer = False
# stops this loop
starting_code = False
# stops big loop
except ValueError:
print("Please choose a number")
# catches non-numbers and floats
except NameError:
print("Please choose a name")
# convoluted way of catching name-errors for 'exit_code'
# noinspection PyUnboundLocalVariable
while num_of_coffee > 0:
# while num_of_coffee isn't zero, if it is then the loop stops
try:
coffee_choice = input("\u2022what coffee would you like?").strip().lower()
# what coffee would you like?
chosen_coffees.append(coffee_choice)
# appends answer into 'coffee_choice' list
for chosen_coffee in chosen_coffees:
if chosen_coffee not in coffees:
chosen_coffees.remove(chosen_coffee)
# this code looks at the last inputted coffee_choice and removes it from the list if it's not a coffee
index = coffees.index(coffee_choice)
price = price_of_coffees[index]
price_total.append(price)
# gives the chosen coffee a price if it is a selectable coffee (which it is because of the code above)
print("That {} will cost you ${}".format(coffee_choice, price))
# print the given cost of the chosen coffee
num_of_coffee = num_of_coffee - 1
# every loop of this code minuses one from 'num_of_coffee' until 'num_of_coffees' is zero
except ValueError:
print("please choose a coffee from the menu {}".format(coffees))
# catches incorrect coffee choices
for c in chosen_coffees:
print(" \u2022\t{}".format(c))
# shows total inputted coffees
print("That will cost you ${}, come again!".format(sum(price_total)))
# adds together the prices of all coffees ordered and prints the sum
|
import random
student_dict = {'Eric': 80, 'Scott': 75, 'Jessa': 95, 'Mike': 66}
print("Dictionary Before Shuffling")
print(student_dict)
keys = list(student_dict.keys())
random.shuffle(keys)
ShuffledStudentDict = dict()
for key in keys:
ShuffledStudentDict.update({key: student_dict[key]})
print("\nDictionary after Shuffling")
print(ShuffledStudentDict) |
class Book:
def __init__(self, name,author,tag):
self.name = name
self.author = author
self.tag = tag
container = []
container.append(Book('War and Piece', 'Tolstoy', ['love', 'train']))
container.append(Book('Return from the stars', 'Stanislav Lem', ['future']))
def search_by_name(container, name):
result = []
for book in container:
if name in book.name:
result.append(book)
return result
def filter_by_name(container, name):
return list(filter(lambda book: name in book.name, container))
|
#Sam Krimmel
#1/29/18
#movie.py - asks user for age and prints most scandalous movie they can watch
age = int(input('Enter your age: '))
if age > 17:
print('You can watch NC-17 movies.')
elif age >= 17:
print('You can watch R rated movies.')
elif age >= 13:
print('You can watch PG-13 movies.')
elif age >= 10:
print('You can watch PG movies')
else:
print('You can watch G rated movies')
|
#Sam Krimmel
#1/30/18
#compoundDemo.py - how to use and/or
num = int(input('Enter a number: '))
if num > 0 and num%7 == 0:
print(num, 'is positive and divisible by seven!')
elif num > 0:
print(num, 'is positive but not divisible by seven. :(')
elif num < 0 and num%7 == 0:
print(num, 'is negative and divisible by seven.')
elif num < 0:
print(num, 'is negative but not divisible by seven.')
else:
print('ERROR 404, number not found.')
|
# A Binary Tree Node
class Node:
# Constructor to create a new node
def __init__(self, key):
self.key = key
self.left = None
self.right = None
# A utility function to do inorder traversal of BST
class BST(object):
def __init__(self):
self.root = None
def inorder(self):
A =[]
self._inorder(self.root, A)
return A
def _inorder(self, n, A):
if n is not None:
self._inorder(n.left, A)
A.append(n.key)
self._inorder(n.right, A)
def insert(self, key):
#self.root = self._insert(self.root, key)
if self.root is None:
self.root = Node(key)
return
n = self.root
while True:
if n.key > key:
if n.left is None:
n.left = Node(key)
return
n = n.left
else:
if n.right is None:
n.right = Node(key)
return
n = n.right
def upperBound(self, D): # node.key <= D
ans = None
n = self.root
while n is not None:
if n.key > D:
n = n.left
elif n.key == D:
ans = n
return ans.key
else:
if ans is None or n.key > ans.key:
ans = n
n = n.right
if ans == None:
return None
else:
return ans.key
def lowerBound(self, D): # node.key >= D
ans = None
n = self.root
while n is not None:
if n.key > D:
if ans is None or n.key < ans.key:
ans = n
n = n.left
elif n.key == D:
ans = n
return ans.key
else:
n = n.right
if ans == None:
return None
else:
return ans.key
def _minValueNode(self, n):
current = n
# loop down to find the leftmost leaf
while(current.left is not None):
current = current.left
return current
def delete(self, key):
self.root = self._deleteNode(self.root, key)
# Given a binary search tree and a key, this function
# delete the key and returns the new root
def _deleteNode(self, n, key):
# Base Case
if n is None:
return n
# If the key to be deleted is smaller than the root's
# key then it lies in left subtree
if key < n.key:
n.left = self._deleteNode(n.left, key)
# If the kye to be delete is greater than the root's key
# then it lies in right subtree
elif(key > n.key):
n.right = self._deleteNode(n.right, key)
# If key is same as root's key, then this is the node
# to be deleted
else:
# Node with only one child or no child
if n.left is None :
temp = n.right
n = None
return temp
elif n.right is None :
temp = n.left
n = None
return temp
# Node with two children: Get the inorder successor
# (smallest in the right subtree)
temp = self._minValueNode(n.right)
# Copy the inorder successor's content to this node
n.key = temp.key
# Delete the inorder successor
n.right = self._deleteNode(n.right , temp.key)
return n
bst = BST()
bst.insert(50)
print(bst.inorder())
bst.delete(50)
print(bst.inorder())
|
import io
import sys
import collections
# Simulate the redirect stdin.
if len(sys.argv) > 1:
filename = sys.argv[1]
inp = ''.join(open(filename, "r").readlines())
sys.stdin = io.StringIO(inp)
def prec(c):
if c == '+' or c == '-':
return 1
elif c == '*' or c == '/':
return 2
else:
return 0
def infixToPostfix(A):
ans = []
S = []
for c in A:
if c in ["1","2", "3", "4", "5","6","7", "8","9","0"]:
ans.append(c)
elif c == '(':
S.append(c)
elif c == ')':
while len(S) > 0:
b = S.pop()
if b =='(':
break
ans.append(b)
else:
while len(S) > 0 and prec(S[-1]) >= prec(c):
ans.append(S.pop())
S.append(c)
while len(S) > 0:
ans.append(S.pop())
return "".join(ans)
def main():
t = int(input()) # read a line with a single integer
input()
for i in range(t):
A=[]
for line in sys.stdin:
c = line.strip()
if c =="":
break
A.append(c)
print(infixToPostfix(A))
if i < t -1:
print()
exit(0)
if __name__ == "__main__":
main() |
import io
import sys
import collections
# Simulate the redirect stdin.
if len(sys.argv) > 1:
filename = sys.argv[1]
inp = ''.join(open(filename, "r").readlines())
sys.stdin = io.StringIO(inp)
swap = 0
def merge(A, B):
C = []
i = 0
j = 0
while i < len(A) and j < len(B):
if A[i] <= B[j]:
C.append(A[i])
i+=1
else:
global swap
swap+=len(A)-i
C.append(B[j])
j+=1
if i < len(A):
C = C + A[i:]
if j < len(B):
C = C + B[j:]
return C
def merge_sort(A):
if len(A) <= 1:
return A
n = len(A)
a = merge_sort(A[:n//2])
b = merge_sort(A[n//2:])
return merge(a, b)
def main():
while True:
A=[int(s) for s in input().split()]
if A[0] == 0:
exit(0)
global swap
swap = 0
merge_sort(A[1:])
if swap %2 ==1:
print("Marcelo")
else:
print("Carlos")
if __name__ == "__main__":
main()
|
from abc import ABC, abstractmethod
from PadraoVoaveis import PadraoVoaveis
from PadraoCorrer import PadraoCorrer
class Pato(ABC):
@abstractmethod
def mostrar(self):
pass
def nadar(self):
return "Pato Nadando."
def setComportamento(self, padrao):
if not isinstance(padrao, PadraoVoaveis):
raise Exception("Parâmetro padrao deve ser do tipo PadraoVoaveis")
self.padraoVoaveis = padrao
def comportamentoPato(self):
return self.padraoVoaveis.voar()
def setPadraoCorrer(self, padrao):
if not isinstance(padrao, PadraoCorrer):
raise Exception("Parâmetro padrao deve ser do tipo PadraoCorrer")
self.padraoCorrer = padrao
def correr(self):
return self.padraoCorrer.correr()
|
# KidsCanCode - Intro to Programming
# Rock/Paper/Scissors game
import random
choices = ['r', 'p', 's']
player_wins = ['pr', 'rs', 'sp']
player_score = 0
computer_score = 0
while True:
player_move = input("Your move? ")
if player_move == 'q':
break
computer_move = random.choice(choices)
print("You:", player_move)
print("Me:", computer_move)
combo = player_move + computer_move
if player_move == computer_move:
print("Tie!")
elif combo in player_wins:
print("You win!")
player_score += 1
else:
print("You lose!")
computer_score += 1
print("SCORES:")
print("You: ", player_score)
print("Me: ", computer_score)
|
# Multilinear Regression
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
# loading the data
Toyotta = pd.read_csv("C:\\Users\\nidhchoudhary\\Desktop\\Assignment\\MULTI_LINEAR_REGRESSION\\ToyotaCorolla.csv",encoding='ANSI')
##Creeating Data Set
Toyotta_Cars = Toyotta[["Price","Age_08_04","KM","HP","cc","Doors","Gears","Quarterly_Tax","Weight"]]
##Correlation values
#print(Toyotta_Cars.corr())
import seaborn as sns
sns.pairplot(Toyotta_Cars)
#plt.show()
import statsmodels.formula.api as smf
model1 = smf.ols('Price~Age_08_04+KM+HP+cc+Doors+Gears+Quarterly_Tax+Weight',data= Toyotta_Cars).fit()##0.864
print(model1.params)
print(model1.summary())
##Calculate RMSE Value
predicted_value = model1.predict(Toyotta_Cars)
Error = Toyotta_Cars.Price - predicted_value ###1338.25
#print((np.sqrt(np.mean(Error*Error)),'Rmse Values'))
import statsmodels.api as sm
sm.graphics.influence_plot(model1)
#plt.show()
##From Influence Plot we saw 80 has highest radius so dropping index 80 row
Toyotta_Cars_new = Toyotta_Cars.drop(Toyotta_Cars.index[80],axis=0)
model2 = smf.ols('Price~Age_08_04+KM+HP+cc+Doors+Gears+Quarterly_Tax+Weight',data= Toyotta_Cars_new).fit()##0.864
##print(model2.summary())
final_predict = model2.predict(Toyotta_Cars_new)
#print(final_predict)
##Third model
model3 = smf.ols('Price~np.log(Age_08_04+KM+HP+cc+Doors+Gears+Quarterly_Tax+Weight)',data= Toyotta_Cars_new).fit()##0.4375
print(model3.summary())
model4= smf.ols('np.log(Price)~Age_08_04+KM+HP+cc+Doors+Gears+Quarterly_Tax+Weight',data= Toyotta_Cars_new).fit()##0.869
print(model2.summary())
final_predict = model4.predict(Toyotta_Cars_new)
|
def merge_sort(ls, st, lt):
if st < lt:
m = int((st + lt) / 2)
merge_sort(ls, st, m)
merge_sort(ls, m + 1, lt)
merge(ls, st, m, lt)
def merge(ls, st, m, lt):
a = list()
|
#num = 600851475143
#magnitude = 6.0e11
#so the square root is < 1e6?
#1e6 = 1000000
#1e6 ^2 = 1000000 000000
# so we perform a sieve of eratosthenes to find primes up to 1e6,
# which is guaranteed to find at least one of each pair of factors.
# List of size 1e6
class SieveOfEratosthenes:
# Create a sieve of given size, without checking prime-ness.
# First item in sieve (index 0) represents 1,
# the second item (index 1) represents 2, and so on.
# Thus integer n can be find at sieve[n-1].
# 1 is trivially prime and is ignored for the algorithm.
def __init__(self, size):
super().__init__()
self.size = size
self.index = 1
self.sieve = [True] * size
self.primes = []
# Process sieve to find the next prime, and set all multiples of that number to False.
# Do this by advancing index by 1 until something marked as Prime is found,
# adding it to the list of primes, then marking all multiples as NotPrime.
def _findNextPrime(self):
try:
finished = self._prepareNextPrimeIndex()
if finished:
return
self.primes.append(self.index)
#print(f"Found prime number {self.index}!")
k = 2
while(k * self.index < self.size):
self.sieve[k * self.index] = False
k += 1
except IndexError:
print(f"Error accessing index {self.index} in list size {self.size}")
# Advance index to the next valid index.
# Returns True if index is at the end of the list, False if otherwise
def _prepareNextPrimeIndex(self):
self.index += 1
while (self.index < self.size):
if self.sieve[self.index] == True:
#print("Found index", self.index)
return False
#print(f"Index {self.index} is not prime. Checking next index...")
self.index += 1
return True
def runSieve(self):
while self.index < self.size:
self._findNextPrime()
sieve = SieveOfEratosthenes(1000000)
sieve.runSieve()
num = 600851475143
prime_divisors = []
for div in sieve.primes:
if div > num:
break
while num % div == 0:
prime_divisors.append(div)
greatest_prime_factor = div
num /= div
print(prime_divisors)
print(greatest_prime_factor)
|
"""****************************PASCAL_TRIANGLE V1.1**************************************************"""
from __future__ import print_function # for python version below 3.0, this import is necessary to use that end='' in print function.
def sol(degree):
'''This function will add list of each element into a single list.'''
globals()['deg_order']=degree
globals()['list_ele']=[]
for i in range(deg_order+1):
list_ele.append(calc(i)) #append list items in a list
display() #i called it here so that i dont have to call it in main
def calc(num):
'''this function will generate list of element in each degree and send them to sol()'''
ele=[]
if num==0:
return [1]
elif num==1:
return [1,1]
else:
ele.insert(0,1)
ele.insert(num,1)
for m in range(1,num):
ele.insert(m,(list_ele[num-1][m-1]+list_ele[num-1][m]))#inserts element in respective index of list item
return ele
def display():
'''this will display the triangle as formatted output of triangle'''
length_of_last_list=len(' '.join(map(str,list_ele[-1])))
for i in list_ele:
row=' '.join(map(str,i))
while len(row)<length_of_last_list:
row=' '+row+' '
print(row)
if __name__=='__main__':
degree=int(input("Enter the order of Pascal_tri: "))
sol(degree)
#updated_version_1.1
#author-Dev Parajuli... follow me in instagram- @dev18official
|
"""
Given an array, find out if the array is sorted using recursion.
Time complexity: O(n)
Space complexity: O(n)
"""
def is_sorted(lst):
if len(lst) <= 1:
return True
else:
if lst[0] < lst[1]:
return is_sorted(lst[1:])
else:
return False
return True
assert(is_sorted([1,2,3,4,5]) == True)
assert(is_sorted([3])) == True
assert(is_sorted([])) == True
assert(is_sorted([3,2,4])) == False |
# Animation/Frame generator Library
# Part of the Glitch_Heaven Project
# Copyright 2015 Penaz <penazarea@altervista.org>
import pygame
import os
class Animation(object):
""" This is a simple library that stores frames for a simple animation """
def __init__(self):
""" Constructor - No parameters """
self.frames = []
# Setting this at -1 so the first call of next()
# v----- returns the frame 0 -----v
self.currentframe = -1
def __iter__(self):
""" Allows to return an iterator if necessary """
return self
def __next__(self):
""" Python2 Compatibility Layer"""
return self.next()
def next(self):
"""
This method returns the next frame in the animation,
in a ring array fashion
Returns:
- Next frame from the frame list
"""
# Returns the frame number in a circular fashion
# v----- 0 -> ... -> n-1 -> n -> 0 -----v
self.currentframe = (self.currentframe+1) % len(self.frames)
return self.frames[self.currentframe]
def loadFromDir(self, directory):
"""
Loads the frames from a given directory using List generators,
frames are sorted by name
Keyword Arguments:
- directory: The Directory to load the frames from
Returns:
- Nothing
"""
x = [(os.path.join(directory, f))
for f in os.listdir(directory)
if os.path.isfile(os.path.join(directory, f))]
self.frames = [pygame.image.load(y).convert_alpha() for y in sorted(x)]
def loadFromList(self, lst):
"""
Loads the frames from a given list
Keyword Arguments:
- lst: A list of frames
Returns:
- Nothing
"""
self.frames = lst
|
from generator import generate
import argparse
import random
import string
def main():
parser = argparse.ArgumentParser()
parser.add_argument("--seed",default="random")
parser.add_argument("--maxlen",default=50,type=int)
parser.add_argument("--numnames",default=1,type=int)
args = parser.parse_args()
seed = args.seed#"Q"
maxlen = args.maxlen#50
number_of_names = args.numnames#1
for i in range(number_of_names):
if args.seed == "random":
seed = random.choice(list(string.ascii_uppercase))
name = generate.sample(seed,maxlen)
print(name)
if __name__ == "__main__":
main()
|
from abc import ABC, abstractmethod
from contextlib import closing
import sqlite3
import csv
import re
class Estrategia(ABC):
"""
Classe Base para as estratégias (algoritmos)
"""
@abstractmethod
def execute(self, dados):
""" Método em que o algoritmo é contido.
Implementação do algoritmo na classe filha deve
sobreescrever este método."""
pass
@abstractmethod
def parametros_necessarios(self):
"""Sobreescrever este método para que retorne uma tupla
com a lista de parâmetros necessários.
Exemplo:
('algoritmo', 'dbname', 'host', 'user', 'password')
"""
pass
@abstractmethod
def nome(self):
"""Sobreescrever este método para que
retorne o nome do algoritmo utilizado."""
pass
class Estrategia_SQLite(Estrategia):
def execute(self, dados):
lista_registros = []
db = dados['db']
with closing(sqlite3.connect(db)) as conn:
cursor = conn.cursor()
cursor.execute("SELECT * FROM vendas;")
for linha in cursor.fetchall():
lista_registros.append(linha)
return lista_registros
def parametros_necessarios(self):
return ('algoritmo', 'db')
def nome(self):
return 'Algoritmo SQLite'
class Estrategia_CSV(Estrategia):
def execute(self, dados):
lista_registros = []
arquivo = dados['arquivo']
with open(arquivo, newline='\n') as csvfile:
reader = csv.DictReader(csvfile)
for line in reader:
lista_registros.append(line)
return lista_registros
def parametros_necessarios(self):
return ('algoritmo', 'arquivo')
def nome(self):
return 'Algoritmo CSV'
class Estrategia_Texto1(Estrategia):
def execute(self, dados):
lista_registros = []
arquivo = dados['arquivo']
with open(arquivo) as fp:
reader = fp.readlines()
for line in reader:
if not line[0].isdigit():
continue
data = line[:11].strip()
produto = line[49:].strip()
total = line[36:48].strip()
lista_registros.append((produto, total, data))
return lista_registros
def parametros_necessarios(self):
return ('algoritmo', 'arquivo')
def nome(self):
return 'Algoritmo Texto1'
class Estrategia_Texto2(Estrategia):
def execute(self, dados):
lista_registros = []
arquivo = dados['arquivo']
with open(arquivo) as fp:
reader = fp.readlines()
for line in reader:
pattern = '(?P<data>\d{4}-\d{2}-\d{2})|(?P<produto>[A-z]+\s\d+)|(?P<total>\d+[\.\,]+\d+)'
result = re.findall(pattern, line)
if result:
data = result[0][0]
produto = result[1][1]
total = result[2][2]
lista_registros.append((produto, total, data))
return lista_registros
def parametros_necessarios(self):
return ('algoritmo', 'arquivo')
def nome(self):
return 'Algoritmo Texto2'
|
import pandas as pd
def standardize_all_variables(data, pre_period, post_period):
"""Standardize all columns of a given time series.
Args:
data: Pandas DataFrame with one or more columns
Returns:
dict:
data: standardized data
UnStandardize: function for undoing the transformation of the
first column in the provided data
"""
if not isinstance(data, pd.DataFrame):
raise ValueError("``data`` must be of type `pandas.DataFrame`")
if not (
pd.api.types.is_list_like(pre_period) and pd.api.types.is_list_like(post_period)
):
raise ValueError("``pre_period`` and ``post_period``must be listlike")
data_mu = data.loc[pre_period[0] : pre_period[1], :].mean(skipna=True)
data_sd = data.loc[pre_period[0] : pre_period[1], :].std(skipna=True, ddof=0)
data = data - data_mu
data_sd = data_sd.fillna(1)
data[data != 0] = data[data != 0] / data_sd
y_mu = data_mu[0]
y_sd = data_sd[0]
data_pre = data.loc[pre_period[0] : pre_period[1], :]
data_post = data.loc[post_period[0] : post_period[1], :]
return {
"data_pre": data_pre,
"data_post": data_post,
"orig_std_params": (y_mu, y_sd),
}
def unstandardize(data, orig_std_params):
"""Function for reversing the standardization of the first column in the
provided data.
"""
data = pd.DataFrame(data)
y_mu = orig_std_params[0]
y_sd = orig_std_params[1]
data = data.mul(y_sd, axis=1)
data = data.add(y_mu, axis=1)
return data
def df_print(data, path=None):
if path:
data.to_csv(path)
print(data)
def get_matplotlib(): # pragma: no cover
"""Wrapper function to facilitate unit testing the `plot` tool by removing
the strong dependencies of matplotlib.
Returns:
module matplotlib.pyplot
"""
import matplotlib.pyplot as plt
return plt
|
import numpy as np
def get_downward_diagonal_indices(startRow, startCol, length=3):
list_of_indices = [np.zeros(2) for _ in range(length)]
for i in range(0, length):
list_of_indices[i] = [startRow - 1 - i, startCol + 1 + i]
return list_of_indices
def get_upward_diagonal_indices(startRow, startCol, length=3):
list_of_indices = [np.zeros(2) for _ in range(length)]
for i in range(0, length):
list_of_indices[i] = [startRow + 1 + i, startCol + 1 + i]
return list_of_indices
def get_grid_values(list_of_indices, array):
return np.array([array[x, y] for x, y in list_of_indices])
def print_grid(grid):
print(grid[::-1, ])
def other_token(current_token):
if current_token == 'x':
return 'o'
else:
return 'x'
def search_sequence_numpy(arr, seq):
""" Find sequence in an array using NumPy only.
Parameters
----------
arr : input 1D array
seq : input 1D array
Output
------
Output : 1D Array of indices in the input array that satisfy the
matching of input sequence in the input array.
In case of no match, empty list is returned.
"""
# Store sizes of input array and sequence
Na, Nseq = arr.size, seq.size
# Range of sequence
r_seq = np.arange(Nseq)
# Create 2D array of sliding indices across entire length of input array.
# Match up with the input sequence & get the matching starting indices.
M = (arr[np.arange(Na-Nseq+1)[:, None] + r_seq] == seq).all(1)
return np.any(M) |
import os
with open("input.txt", "r") as f:
count = 0
answers = set()
for line in f:
line = line.strip()
if not line:
# print(answers, len(answers))
count += len(answers)
answers.clear()
# print(answers)
else:
for c in line:
if c not in answers:
answers.add(c)
count += len(answers)
print(count) |
import os
with open("input.txt", "r") as f:
p = 0
count = 0
for line in f:
if p >= len(line.strip()):
# print(p, len(line))
p -= len(line.strip())
if line[p] == '#':
count += 1
p += 3
print(count)
|
class Pet:
def __init__(self, name, type, tricks):
self.name = name
self.type = type
self.tricks = tricks
self.health = 90
self.energy = 0
def sleep(self):
if self.energy + 25 <= 100:
self.energy += 25
else:
self.energy = 100
return self
def eat(self):
if self.health + 10 <= 100:
self.health += 10
else:
self.health = 100
if self.energy + 5 <= 100:
self.energy += 5
else:
self.energy = 100
return self
def play(self):
if self.health + 5 <= 100:
self.health += 5
else:
self.health = 100
return self
def noise(self):
print('roof')
class Dog(Pet):
def __init__(self, name, tricks, type='Dog'):
super().__init__(name, type, tricks)
def sleep(self):
super().sleep()
return self
def eat(self):
super().eat()
return self
def play(self):
super().play()
return self
def noise(self):
print('BARK BARK BARK')
return self
if __name__ == "__main__":
print("the file is being executed directly")
else:
print("The file is being executed because it is imported by another file. The file is called: ", __name__)
|
# Imports modules
from sys import argv
# Unpacks the argv module using two parameters
script, filename = argv
# specifies a txt file and opens the file specified by the "filename" parameter
txt = open(filename)
# prints a string along with the name of the file being opened
print "Here's your file %r:" % filename
# prints the contents of the txt file
print txt.read()
# Prints a string
print "Type the filename again:"
# Creates a variable and assigns user input to it
file_again = raw_input("> ")
txt_again = open(file_again)
print txt_again.read()
|
from datetime import datetime
def isPositiveDay(openPrice, closePrice):
return openPrice < closePrice
def isMarketClosed():
current = datetime.now()
# monday is 0 sunday is 6
day = current.weekday()
hour = current.hour
minute = current.minute
if day > 4: # is weekend
return True
elif hour < 8 or (hour == 8 and minute < 30) or hour > 14: # is earlier than 8:30am or is later than 3pm
return True
else: # weekday but markets are closed
return False |
# Email Slicer
email = input('Enter your Email ID: ').strip()
username = email[ : email.index("@")]
domain_name = email[ email.index("@")+1 : email.index('.') ]
result = "Your Username is '{}' and your domain name is '{}'". format(username, domain_name)
print(result)
|
a = raw_input('Please input num_1:')
a = int(a)
b = raw_input('Please input num_2:')
b = int(b)
c = raw_input('Please input num_3:')
c = int(c)
def sum3Number(a,b,c):
return a+b+c
def average3Number(a,b,c):
return sum3Number(a,b,c)/3
print('sum3Number=%d'%sum3Number(a,b,c))
print('average3Number=%d'%average3Number(a,b,c))
|
from math import inf
arrays = [[1, 2, 3, 2, 6, 6],
[3, 2, 9, 1, 8, 2, 0, 4, 5],
[3, 2, 6, 1, 8, 2, 0, 4, 5],
[1, 3, 2, 2, 3],
[1, 0, 3, 2],
[2, 3, 0]]
def find_jumps_from(arr, i, jumps):
""" finds the minimum number of jumps from i to the end of the array """
# check if we can directly jump to the end
if arr[i] + i >= len(arr):
return 1
if arr[i] == 0:
return -1
min_jumps = inf
for j in range(i + 1, min(len(arr), i + 1 + arr[i])):
# pass dead end
if jumps[j] <= 0:
continue
min_jumps = min(min_jumps, jumps[j])
# if the end is unreachable, return -1
if min_jumps == inf:
return -1
return min_jumps + 1
def find_min_jumps(arr):
""" for a given array, finds the minimum number of jumps from the beginning to the end """
n = len(arr)
# initialize jumps array
jumps = [-1] * n
for i in range(n - 1, -1, -1):
jumps[i] = find_jumps_from(arr, i, jumps)
print(
f"For the following array: {arr}\n\tThe dynamic programming table looks like as follows: {jumps}\n\t"
f"Resulting in {jumps[0]} total jumps")
print("-" * 15)
return jumps[0]
def main():
for arr in arrays:
find_min_jumps(arr)
if __name__ == "__main__":
main()
|
from IPython.display import clear_output
class Shopping():
def __init__(self):
self.shop_list = []
print("Welcome!")
print("You can add, delete, see items in list,")
print("or even quit shopping.")
print()
print("please write add / delete / see / quit ")
def add(self):
item = input("Type an item: ")
self.shop_list.append(item)
def delete(self):
item = input("Type an item: ")
if item in self.shop_list:
self.shop_list.remove(item)
else:
print("Type again!")
def see(self):
if len(self.shop_list) == 0:
print("The cart is empty!!")
for shop in self.shop_list:
print(shop)
my_shopping = Shopping()
while True:
select = input("What will you choose - add, delete, see, quit: ")
if select == "add":
my_shopping.add()
elif select == "delete":
my_shopping.delete()
elif select == "see":
my_shopping.see()
elif select == "quit":
break
else:
print("Wrote wrong, try again!")
|
class Rect:
def __init__(self, x, y, width, height):
self.x = x
self.y = y
self.width = width
self.height = height
def __str__(self):
return str([self.x, self.y, self.width, self.height])
def as_list(self):
return [self.x, self.y, self.width, self.height]
def left(self):
return self.x
def right(self):
return self.x + self.width
def bottom(self):
return self.y
def top(self):
return self.y + self.height
def collides(self, rect2):
if self.right() <= rect2.left():
return False
elif self.left() >= rect2.right():
return False
elif self.top() <= rect2.bottom():
return False
elif self.bottom() >= rect2.top():
return False
else:
return True
def collides_point(self, x, y):
if x >= self.left() and x <= self.right() and y >= self.bottom() and y <= self.top():
return True
return False
def get_intersect(self, rect2):
if self.left() > rect2.left() and self.left() < rect2.right():
left = self.left()
else: # rect2.left() > rect.left() and rect2.left() < rect2.right():
left = rect2.left()
if self.right() > rect2.left() and self.right() < rect2.right():
right = self.right()
else: # rect2.right() > rect.left() and rect2.left() < rect2.right()
right = rect2.right()
if self.bottom() > rect2.bottom() and self.bottom() < rect2.top():
bottom = self.bottom()
else: # rect2.bottom() > rect.bottom() and rect2.bottom() < rect2.top():
bottom = rect2.bottom()
if self.top() > rect2.bottom() and self.top() < rect2.top():
top = self.top()
else: # rect2.top() > rect.bottom() and rect2.bottom() < rect2.top()
top = rect2.top()
width = right - left
height = top - bottom
return Rect(left, bottom, width, height)
|
arr = [7,3,2,1,6,4,9,8]
# arr = [7,3,2,1,6,4,9,8]
c1 = 0
c2 = 0
for i in arr
print (arr) |
import random
import time
lst=['rock','paper','scissor']
user_score=0
pc_score=0
for i in range(1,4):
print(f"{i} of 3 try")
user_choice=input("enter the choice: ")
choice=random.choice(lst)
print(f"pc choice is {choice}")
if user_choice==choice:
print('draw')
elif user_choice=='rock' and choice=='scissor':
print('user wins')
user_score+=1
elif user_choice=='paper' and choice=='rock':
print('user wins')
user_score+=1
elif user_choice=='scissor' and choice=='paper':
print('user wins')
user_score+=1
else:
print('pc wins')
pc_score+=1
time.sleep(2)
print("\n\n\nfinal result\n")
if user_score > pc_score:
print("u win!!!!")
elif user_score==pc_score:
print("drawwwwwwwwwww")
else:
print("loserrrr!!!!!!!")
|
import functions
import utils
if __name__ == '__main__':
print("Wprowadź numer macierzy którą chcesz wprowadzić: ")
answer = input()
if answer == '1':
functions.gauss_jordan_solver(utils.parse_matrix("matrices/first_matrix"))
elif answer == '2':
functions.gauss_jordan_solver(utils.parse_matrix("matrices/second_matrix"))
elif answer == '3':
functions.gauss_jordan_solver(utils.parse_matrix("matrices/third_matrix"))
elif answer == '4':
functions.gauss_jordan_solver(utils.parse_matrix("matrices/fourth_matrix"))
elif answer == '5':
functions.gauss_jordan_solver(utils.parse_matrix("matrices/fifth_matrix"))
elif answer == '6':
functions.gauss_jordan_solver(utils.parse_matrix("matrices/sixth_matrix"))
elif answer == '7':
functions.gauss_jordan_solver(utils.parse_matrix("matrices/seventh_matrix"))
elif answer == '8':
functions.gauss_jordan_solver(utils.parse_matrix("matrices/eighth_matrix"))
elif answer == '9':
functions.gauss_jordan_solver(utils.parse_matrix("matrices/ninth_matrix"))
elif answer == '10':
functions.gauss_jordan_solver(utils.parse_matrix("matrices/tenth_matrix"))
elif answer == '11':
functions.gauss_jordan_solver(utils.parse_matrix("matrices/55"))
elif answer == '12':
functions.gauss_jordan_solver(utils.parse_matrix("matrices/66"))
elif answer == '13':
functions.gauss_jordan_solver(utils.parse_matrix("matrices/77"))
elif answer == '14':
functions.gauss_jordan_solver(utils.parse_matrix("matrices/88"))
elif answer == '15':
functions.gauss_jordan_solver(utils.parse_matrix("matrices/99"))
elif answer == '16':
functions.gauss_jordan_solver(utils.parse_matrix("matrices/100100"))
elif answer == '17':
functions.gauss_jordan_solver(utils.parse_matrix("matrices/10001000"))
else:
print("nie ma takiego numeru")
quit(0)
|
import math
n1 = float(input('Digite um valor: '))
print('O valor a pagar é R${}', math.trunc(n1))
|
print('\033[32m-=-\033[m' * 20)
print('\033[32m***************** Aprovador de Empréstimos *****************\033[m')
print('\033[32m-=-\033[m' * 20)
vc = float(input('Inisira o valor da casa: R$'))
s = float(input('Insira seu salário: R$'))
qa = int(input('Insira em quantos anos pretende pagar: '))
vm = vc / (qa * 12)
print('Para pagar uma casa de R${:.2f} em {} anos'.format(vc, qa), end ='')
print(' a prestação será de: R${:.2f}' .format(vm))
if vm <= (s*0.3):
print('Empréstimo aprovado com sucesso, o valor mensal será de: {}R${:.2f}{}' .format('\033[1;31m', vm, '\033[m'))
else:
print('Empréstimo negado, o valor da parcela é maior que 30% do seu salário.')
|
print('\033[33m-=-\033[m' * 20)
print('\033[33m************ Sequência de Fibonacci ************\033[m')
print('\033[33m-=-\033[m' * 20)
i = int(input('Quantos termos para ser mostrados? '))
t1 = 0
t2 = 1
print('{} → {}'.format(t1, t2), end=' ')
c = 3
while c <= i:
t3 = t1 + t2
print('→ {}'.format(t3), end=' ')
t1 = t2
t2 = t3
c += 1
print('\nFim')
|
print('\033[33m-=-\033[m' * 20)
print('\033[33m************* Números pares *************\033[m')
print('\033[33m-=-\033[m' * 20)
for c in range(1, 51):
if c%2 == 0:
print(c)
print('Apenas esses são pares entre 1 e 50.') |
n = float(input('Insira quantos km terá sua viagem: '))
if n <= 200:
print('O preço será de: R${:.2f}' .format(n*0.5))
else:
print('O preço será de: R${:.2f}' .format(n*0.45))
|
n = float(input('Digite um valor: '))
print('Você pode comprar UU${}' .format(n/3.27))
|
v = float(input('Qual a velocidade do carro? '))
if v <= 80:
print('Velocidade ok.')
else:
print('Sua multa será de: R${:.2f}' .format((v-80)*7))
|
class TreeNode:
self.val = None
self.right = None
self.left = None
def __init__(self, val):
self.val = val
def defectiveNode(TreeNode root):
parents = [root]
children = []
defective = []
while len(parent)!=None:
for parent in parents:
if parent.left!=None:
if parent.left in children:
#add to defective and de-link the node
defective.append(parent.left)
parent.left = None
else:
children.append(parent.left)
if parent.right!=None:
if parent.right in children:
defective.append(parent.right)
parent.right = None
else:
children.append(parent.right)
#update parent to be children at next level
parent = children
#update children to be new borns at next level
children = []
return defective
|
#!/usr/bin/env python
# check if signs of two integers are opposite
def sign_evaluator(a,b):
return a ^ b < 0
print sign_evaluator(a=3, b=-3)
|
inv = {'rope': 1, 'torch': 6, 'gold coin': 42, 'dagger': 1, 'arrow': 12}
dragon_loot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby']
def display_inventory():
print('Inventory: ')
for i in inv:
print(inv[i], i)
print('Total number of items: ', sum(inv.values()))
def add_to_inventory(inventory, added_items):
for j in added_items:
if j in inventory:
inventory[j] += 1
#checking
else:
inventory[j] = 1
display_inventory()
k = input("Add an item: ") #add an item
dragon_loot.append(k)
add_to_inventory(inv, dragon_loot)
display_inventory() |
import functions # or from functions import square
# to print all sqaures of 0 to 10 using range and for loop # sqaures function is in functions.py file
for i in range(10):
print(f"Square of {i} is {functions.square(i)}")
# or
from functions import square
for i in range(10):
print(f'square of {i} is {square(i)}') |
# Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
# Example:
# Input:
# [
# 1->4->5,
# 1->3->4,
# 2->6
# ]
# Output: 1->1->2->3->4->4->5->6
# Brute force solution:
# Traverse over all the linked lists and collect the values in the array
# sort and itterate over the array ot get the proper value of the nodes
# Create a new linked list with the sorted values as the new nodes
# class Solution:
# def mergeKLists(self, lists: List[ListNode]) -> ListNode:
# self.nodes = []
# head = point = ListNode(0)
# for l in lists:
# while l:
# self.nodes.append(l.val)
# l = l.next
# for x in sorted(self.nodes):
# point.next = ListNode(x)
# point = point.next
# return head.next
# Time: O(N Log N)
# Space: O(N)
# Priority Queue
# Comparing every node which is the head of each linked lists and then putting them into a new node.
#from queue import PriorityQueue
# class Solution:
# def mergeKLists(self, lists: List[ListNode]) -> ListNode:
# head = curr_node = ListNode(None)
# q = PriorityQueue()
# for idx, node in enumerate(lists):
# if node:
# q.put((node.val, idx, node))
# while not q.empty():
# _, idx, curr_node.next = q.get()
# curr_node = curr_node.next
# if curr_node.next:
# q.put((curr_node.next.val, idx, curr_node.next))
# return head.next
# Time: O(N log k) where k is the number of linked lists
# Space: O(N) where creating a new linked lists takes n space and k nodes
# Merge with divide and conquer
# Kind of like merge sort where we separate the lists intwo 2, and then merge them both toghete
# from queue import PriorityQueue
# class Solution:
# def mergeKLists(self, lists: List[ListNode]) -> ListNode:
# if not lists:
# return
# if len(lists) == 1:
# return lists[0]
# mid = math.floor(len(lists)/2)
# left = self.mergeKLists(lists[:mid])
# right = self.mergeKLists(lists[mid:])
# return self.merge(left, right)
# def merge(self, left, right):
# dummy = curr = ListNode(0)
# while left and right:
# if left.val < right.val:
# curr.next = left
# left = left.next
# else:
# curr.next = right
# right = right.next
# curr = curr.next
# curr.next = left or right
# return dummy.next
# Time: O(N log k) where k is the number of linked lists
# Space: O(1)
|
# Given a collection of intervals, merge all overlapping intervals.
# Example 1:
# Input: [[1,3],[2,6],[8,10],[15,18]]
# Output: [[1,6],[8,10],[15,18]]
# Explanation: Since intervals [1,3] and [2,6] overlaps, merge them into [1,6].
# Example 2:
# Input: [[1,4],[4,5]]
# Output: [[1,5]]
# Explanation: Intervals [1,4] and [4,5] are considered overlapping.
# NOTE: input types have been changed on April 15, 2019. Please reset to default code definition to get new method signature.
# class Solution:
# def merge(self, intervals: List[List[int]]) -> List[List[int]]:
# if len(intervals) <= 1:
# return intervals
# intervals.sort()
# res = []
# curr_interval = intervals[0]
# res.append(curr_interval)
# for interval in intervals[1:]:
# curr_end = curr_interval[1]
# next_begin = interval[0]
# next_end = interval[1]
# if curr_end >= next_begin:
# curr_interval[1] = max(curr_end, next_end)
# else:
# curr_interval = interval
# res.append(curr_interval)
# return res
# Time: O(n log n) because we have to sort the intervals
# Space: O(1) since we are sorting inplace and not including the results array |
# Given a 2d grid map of '1's (land) and '0's (water), count the number of islands. An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water.
# Example 1:
# Input:
# 11110
# 11010
# 11000
# 00000
# Output: 1
# Example 2:
# Input:
# 11000
# 11000
# 00100
# 00011
# DFS solution, but can also use a queue using bfs.
class Solution:
def numIslands(self, grid: List[List[str]]) -> int:
if not grid:
return 0
count = 0
for i in range(len(grid)):
for j in range(len(grid[0])):
if grid[i][j] == "1":
self.dfs(grid, i, j)
count += 1
return count
def dfs(self, grid, i, j):
if i < 0 or i >= len(grid) or j < 0 or j >= len(grid[0]) or grid[i][j] != "1":
return
grid[i][j] = "0"
self.dfs(grid, i + 1, j)
self.dfs(grid, i - 1, j)
self.dfs(grid, i, j + 1)
self.dfs(grid, i, j - 1)
# Time: O(n * m) where n and mr are rows and columns of the matrix respectively
# Time: O(n * m) n and m rows and columns for the recursive stack.
# BFS METHOD
# from collections import deque
# class Solution:
# def numIslands(self, grid: List[List[str]]) -> int:
# count = 0
# for i in range(len(grid)):
# for j in range(len(grid[0])):
# if grid[i][j] == "1":
# queue = deque([(i, j)])
# count += 1
# while queue:
# x, y = queue.popleft()
# if x < 0 or x >= len(grid) or y < 0 or y >= len(grid[x]) or grid[x][y] != "1":
# continue
# grid[x][y] = "0"
# queue.append((x + 1, y))
# queue.append((x - 1, y))
# queue.append((x, y - 1))
# queue.append((x, y + 1))
# return count |
# Given a positive integer num, write a function which returns True if num is a perfect square else False.
# Note: Do not use any built-in library function such as sqrt.
# Example 1:
# Input: 16
# Output: true
# Example 2:
# Input: 14
# Output: false
def isPerfectSquare(self, num):
"""
:type num: int
:rtype: bool
"""
if num < 2:
return True
left, right = 2, num // 2
while left <= right:
mid = left + (right - left) // 2
approx_num = mid * mid
if approx_num == num:
return True
if approx_num > num:
right = mid - 1
else:
left = mid + 1
return False
# Time: O(log n) | Space: O(1) |
# You are given an array coordinates, coordinates[i] = [x, y], where [x, y] represents the coordinate of a point. Check if these points make a straight line in the XY plane.
# Input: coordinates = [[1,2],[2,3],[3,4],[4,5],[5,6],[6,7]]
# Output: true
# Example 2:
# Input: coordinates = [[1,1],[2,2],[3,4],[4,5],[5,6],[7,7]]
# Output: false
# Constraints:
# 2 <= coordinates.length <= 1000
# coordinates[i].length == 2
# -10^4 <= coordinates[i][0], coordinates[i][1] <= 10^4
# coordinates contains no duplicate point
def checkStraightLine(coordinates):
dx = coordinates[1][0] - coordinates[0][0]
dy = coordinates[1][1] - coordinates[0][1]
for cx, cy in coordinates[2:]:
cdx, cdy = cx - coordinates[0][0], cy - coordinates[0][1]
if dx * cdy != cdx * dy:
return False
return True
# Time: O(n) | Space: O(1)
|
# Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.
# Example:
# Input: [-2,1,-3,4,-1,2,1,-5,4],
# Output: 6
# Explanation: [4,-1,2,1] has the largest sum = 6.
# Follow up:
# If you have figured out the O(n) solution, try coding another solution using the divide and conquer approach, which is more subtle.
# class Solution:
# def maxSubArray(self, nums: List[int]) -> int:
# max_seq = nums[0]
# curr_sum = nums[0]
# for num in nums[1:]:
# if curr_sum < 0:
# curr_sum = num
# else:
# curr_sum += num
# if curr_sum > max_seq:
# max_seq = curr_sum
# return max_seq
# class Solution:
# def maxSubArray(self, nums: List[int]) -> int:
# max_sum = nums[0]
# curr_sum = max_sum
# for num in nums[1:]:
# curr_sum = max(curr_sum + num, num)
# max_sum = max(curr_sum, max_sum)
# return max_sum
# Time: O(N)
# Space: O(1)
# Divide and Conquer
def maxSubArray(self, nums: List[int]) -> int:
return self.divide_and_conq(nums, 0, len(nums) - 1)
def divide_and_conq(self, nums, left, right):
if left > right:
return float(-inf)
mid = math.floor((left + right)/2)
left_max = curr_sum = 0
for i in range(mid - 1, left - 1, -1):
curr_sum += nums[i]
left_max = max(left_max, curr_sum)
right_max = curr_sum = 0
for i in range(mid + 1, right + 1):
curr_sum += nums[i]
right_max = max(right_max, curr_sum)
left_ans = self.divide_and_conq(nums, left, mid - 1)
right_ans = self.divide_and_conq(nums, mid + 1, right)
return max(left_max + nums[mid] + right_max, max(left_ans, right_ans))
# Time: O(N log N) because we're going through the whole array but splitting it into n sub problems
# Space: O(log N) recursion |
# import datetime
# c = ord('\n')
# today = datetime.datetime.today()
# print(f'game {c} {today:%b %d %y}')
# val = 4
# can = 'dd'
# print(f'i {can} be {val}')
# import time
# count =3
# for i in reversed(range(count +1)):
# if i > 0:
# print(i,end=('>>'), flush=True)
# time.sleep(1)
# else:
# print('start')
# x,y = [int(x) for x in input('Enter Number : ').split()]
# print('The value of x is {} and value of y is {}.'.format(x,y))
# # print ("Hello World")
# val = 500
# def gamer():
# return val
# var = int(input("Find the Number :"))
# if var == val:
# print ('You won')
# else:
# print('Losee')
# print(type(var)) |
from pandas.core.frame import DataFrame
import streamlit as st
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import re
import calendar
import altair as alt
st.title("Maket Segmentation")
st.header("Segmentation Analysis on customer data")
#reading data
dataset_df = pd.read_excel("Dataset.xls")
#replacing negative values in product A column with 0
dataset_df["Product A"] = dataset_df["Product A"].apply(lambda x: x if x > 0 else 0)
#checking if there are any negative values
#st.write((dataset_df["Product A"]<0).any())
#extracting year, month data from date column and geometry from the lat lon columns
dataset_df["year"] = dataset_df["Date"].astype(str).str.extract(r'(\d\d\d\d)')
dataset_df["month"] = dataset_df["Date"].astype(str).str.extract(r'\d{4}-(\d{2})-\d{2}')
dataset_df["month"] = dataset_df["month"].astype(int).apply(lambda x: calendar.month_abbr[x])
dataset_df["geometry"] = dataset_df.apply(lambda row: (row.Latitude, row.Longitude), axis=1)
#showing the cleaned dataframe
if st.checkbox("Show Dataframe"):
st.write("Dataframe has " + str(dataset_df.shape[0]) +" rows and " + str(dataset_df.shape[1])+ " columns")
st.write(dataset_df.head())
#Visualisation
st.subheader("Graph of each product sale")
products = ["Product A","Product B","Product C"]
choice = st.selectbox("Choose a product",products)
for i in range(len(products)) :
if choice == products[i]:
st.line_chart(dataset_df[products[i]])
st.text("Maximum sale of " + str(products[i]) + " is " + str(dataset_df[products[i]].max()))
st.text("Total sales of " + str(products[i]) + " is " + str(dataset_df[products[i]].sum()))
st.write("Product B has highest number of sales followed by Product A and Product C respectively")
st.subheader("Monthly sales of each product")
choice2 = st.selectbox("choose a product", products)
for i in range(len(products)):
if choice2 == products[i]:
product_per_month = alt.Chart(dataset_df).mark_bar().encode(x=products[i], y="month")
st.altair_chart(product_per_month)
st.subheader("Total sales of all Products per Month")
sales_per_month = alt.Chart(dataset_df).mark_bar(color="red").encode(x="month",y="Sales")
st.altair_chart(sales_per_month)
#df = pd.DataFrame(np.random.randn(200, 3),
#columns=['a', 'b', 'c'])
#c = alt.Chart(df).mark_bar().encode(x='a', y='b', tooltip=['a', 'b'])
#.mark_circle().encode(x='a', y='b', size='c', color='c', tooltip=['a', 'b', 'c'])
#st.altair_chart(c)
st.subheader("Map Location of each Customer")
location_df = dataset_df[["Latitude","Longitude"]].rename(columns={'Latitude':'latitude','Longitude':'longitude'})
st.map(location_df, zoom=15)
#product dataframe with sales as index
#product_df = dataset_df[["Product A","Product B","Product C","CustomerName"]]
#product_df = product_df.set_index("CustomerName")
#st.subheader("Product and sales Chart")
#st.write("Visualisation of different products with amount of sales")
#st.write("Choose a product?")
#products = ["Product A", "Product B", "Product C"]
#choice= st.selectbox("products",products)
#if choice == "Product A":
#st.bar_chart(product_df[["Product A"]])
|
#!/usr/bin/env python3
def make_graph(text):
graph = {}
edges = []
for line in text.split('\n'):
val = -1
v0 = v1 = None
for i in range(len(line)):
char = line[i]
if char in ' ->':
continue
if ord('0') <= ord(char) <= ord('9'):
val = int(line[i:])
break
if ord('A') <= ord(char) <= ord('Z'):
if v0 is None:
v0 = ord(char) - ord('A')
elif v1 is None:
v1 = ord(char) - ord('A')
if val != -1 and v0 is not None and v1 is not None:
if v0 not in graph:
graph[v0] = dict()
if v1 not in graph:
graph[v1] = dict()
graph[v0][v1] = val
edges.append((val, v0, v1))
return graph, edges
def make_array(text):
arr = []
for i in text:
if ord('A') <= ord(i) <= ord('Z'):
arr.append(ord(i) - ord('A'))
return arr
def dijkstra(graph, start, end):
SIZE = 8
MAX = 1000
dist = [MAX] * SIZE
to_reach = [MAX] * SIZE
dist[start] = 0
reached = set([start])
src = start
while len(reached) != SIZE:
for dst in graph[src]:
if dst in reached:
to_reach[dst] = MAX
else:
to_reach[dst] = min(to_reach[dst], graph[src][dst])
dst = min(range(len(to_reach)), key=to_reach.__getitem__)
for i in graph[src]:
newdist = dist[src] + graph[src][i]
if newdist < dist[i]:
dist[i] = newdist
if src == end:
for v in dist:
print('-' if v == MAX else v, end=' ')
print()
return
reached.add(dst)
to_reach[dst] = MAX
src = dst
def dap_sp(graph, top, end):
SIZE = 8
MAX = 1000
dist = [MAX] * SIZE
dist[top[0]] = 0
for src in top:
for dst in graph[src]:
newdist = dist[src] + graph[src][dst]
if newdist < dist[dst]:
dist[dst] = newdist
if src == end:
for v in dist:
print('-' if v == MAX else v, end=' ')
print()
return
def bellman_ford(graph, start):
SIZE = 8
MAX = 1000
dist = [MAX] * SIZE
dist[start] = 0
for time in range(3):
for src in graph:
for dst in graph[src]:
newdist = dist[src] + graph[src][dst]
if newdist < dist[dst]:
dist[dst] = newdist
for v in dist:
print('-' if v == MAX else v, end=' ')
print()
q1 = '''
A->E 2
B->A 37
B->C 14
B->E 41
C->D 10
D->H 4
F->B 32
F->C 38
F->E 79
G->C 65
G->F 19
G->H 4
H->C 57
'''
q1_start = 'G'
q1_end = 'C'
q2 = '''
A->E 31
A->F 1
B->A 21
B->F 16
C->B 22
C->F 41
C->G 5
D->C 35
D->G 49
D->H 50
F->E 31
G->F 34
G->H 2
'''
q2_top = ' D C G H B A F E'
q2_end = 'A'
q3 = '''
A->E 5
B->A 20
B->C 3
D->C 21
F->A 50
F->B 24
F->E 7
F->C 1
G->F 34
G->C 32
H->D 18
H->C 37
H->G 10
'''
q3_start = 'H'
dijkstra(make_graph(q1)[0],
ord(q1_start) - ord('A'),
ord(q1_end) - ord('A'))
dap_sp(make_graph(q2)[0],
make_array(q2_top),
ord(q2_end) - ord('A'))
bellman_ford(make_graph(q3)[0],
ord(q3_start) - ord('A'))
|
'''
利用selenium模拟登录豆瓣
url = 'https://www.douban.com/
user: 19938467368
passward: Huawei12#$
如需要输入验证码
分析:
1. 保存页面成快照
2. 等待用户手动输入验证码
3. 继续自动执行提交等动作
'''
from selenium import webdriver
url = 'https://accounts.douban.com/'
driver = webdriver.Chrome()
driver.get(url)
# 等待(显性,隐性,强制)
driver.implicitly_wait(5)
driver.find_element_by_xpath(
'//*[@id="account"]/div[2]/div[2]/div/div[1]/ul[1]/li[2]').click()
driver.implicitly_wait(2)
driver.find_element_by_id('username').clear()
driver.find_element_by_id('username').send_keys('19938467368')
driver.find_element_by_id('password').clear()
driver.find_element_by_id('password').send_keys('Huawei12#$')
driver.find_element_by_xpath(
'//*[@id="account"]/div[2]/div[2]/div/div[2]/div[1]/div[4]/a').click()
driver.implicitly_wait(1)
print(driver.page_source)
|
# -*- coding: utf-8 -*-
"""
CS 2302 Data Structures
Author: John Rodriguez
Lab 5
Instructor: Olac Fuentes
TA: Anindita Nath
Date: 11/4/19
Purpose: Compare the run times between hash tables with one using chaining and the other using linear probing when
retrieving word embeddings to compare two given words. Then compare to the best running time when using a tree from lab 4.
"""
import numpy as np
import time
class WordEmbedding(object):
def __init__(self, word, embedding):
# word must be a string, embedding can be a list or and array of ints or floats
self.word = word
self.emb = np.array(embedding, dtype=np.float32) # len(embedding=50)
class HashTableLP(object):
# Builds a hash table of size 'size', initilizes items to -1 (which means empty)
# Constructor
def __init__(self, size):
self.item = np.zeros(size,dtype=np.object)-1
# a hash function with length of string k % size of table for linear probing
def length_word_hash_LP(self, k):
if isinstance(k, WordEmbedding):
k = k.word
return len(k) % len(self.item)
# a hash function that has the ASCII value of the first character of k % size of table for linear probing
def ascii_first_hash_LP(self, k):
if isinstance(k, WordEmbedding):
k = k.word
return ord(k[0]) % len(self.item)
# a hash function that has the product of ASCII values from first and last char % size of table for linear probing
def ascii_product_hash_LP(self, k):
if isinstance(k, WordEmbedding):
k = k.word
return (ord(k[0]) * ord(k[-1])) % len(self.item)
# a hash function that has the sum of the ASCII values in k % size of table for linear probing
def ascii_sum_hash_LP(self, k):
if isinstance(k, WordEmbedding):
k = k.word
return sum(map(ord, k)) % len(self.item)
# a recursive hash function that multiplies the ASCII values of all the characters in k + 255 on each value % size of table for linear probing
def recursive_hash_LP(self, k):
if isinstance(k, WordEmbedding):
k = k.word
if len(k) == 0:
return 1
return (ord(k[0]) + 255 * self.recursive_hash_LP(k[1:])) % len(self.item)
# a hash function that has the ASCII value of the last character of k % size of table for linear probing
def custom_hash_LP(self, k):
if isinstance(k, WordEmbedding):
k = k.word
return ord(k[-1]) % len(self.item)
# uses the hash function the user selects
def h(self, k, selection):
if selection == 1:
return self.length_word_hash_LP(k)
if selection == 2:
return self.ascii_first_hash_LP(k)
if selection == 3:
return self.ascii_product_hash_LP(k)
if selection == 4:
return self.ascii_sum_hash_LP(k)
if selection == 5:
return self.recursive_hash_LP(k)
if selection == 6:
return self.custom_hash_LP(k)
# function to insert into a hash table using linear probing
def insert(self, k, selection):
start = self.h(k.word, selection)
for i in range(len(self.item)):
pos = (start + i) % len(self.item)
if isinstance(self.item[pos], WordEmbedding):
if self.item[pos].word == k.word:
return -1
elif self.item[pos] < 0:
self.item[pos] = k
return pos
# returns the embedding of the searched key if found
def find_word_embedding(self, k, selection):
try:
if isinstance(k, WordEmbedding):
k = k.word
start = self.h(k, selection)
for i in range(len(self.item)):
pos = (start + i) % len(self.item)
try:
if self.item[pos].word == k:
return self.item[pos].emb
except AttributeError:
if self.item[pos]<0:
return None
except TypeError:
return
class HashTableChain(object):
# Builds a hash table of size 'size'
# Item is a list of (initially empty) lists
# Constructor
def __init__(self, size):
self.bucket = [[] for i in range(size)]
# a hash function with length of string k % size of table for chanining
def length_word_hash_C(self, k):
if isinstance(k, WordEmbedding):
k = k.word
return len(k) % len(self.bucket)
# a hash function that has ASCII value of the first character of k % size of table for chanining
def ascii_first_hash_C(self, k):
if isinstance(k, WordEmbedding):
k = k.word
return ord(k[0]) % len(self.bucket)
# a hash function that has product of ASCII values from first and last char % size of table for chanining
def ascii_product_hash_C(self, k):
if isinstance(k, WordEmbedding):
k = k.word
return (ord(k[0]) * ord(k[-1])) % len(self.bucket)
# a hash function that has the sum of the ASCII values in k % size of table for chanining
def ascii_sum_hash_C(self, k):
if isinstance(k, WordEmbedding):
k = k.word
return sum(map(ord, k)) % len(self.bucket)
# a recursive hash function that multiplies the ASCII values of all the characters in k + 255 on each value % size of table for chanining
def recursive_hash_C(self, k):
if isinstance(k, WordEmbedding):
k = k.word
if len(k) == 0:
return 1
return (ord(k[0]) + 255 * self.recursive_hash_C(k[1:])) % len(self.bucket)
# a hash function that has ASCII value of the last character of k % size of table for chaining
def custom_hash_C(self, k):
if isinstance(k, WordEmbedding):
k = k.word
return ord(k[-1]) % len(self.bucket)
# uses the hash function the user selects
def h(self, k, selection):
if selection == 1:
return self.length_word_hash_C(k)
if selection == 2:
return self.ascii_first_hash_C(k)
if selection == 3:
return self.ascii_product_hash_C(k)
if selection == 4:
return self.ascii_sum_hash_C(k)
if selection == 5:
return self.recursive_hash_C(k)
if selection == 6:
return self.custom_hash_C(k)
# function to insert into a hash table using chaining
def insert(self, k, selection):
b = self.h(k, selection)
if not k in self.bucket[b]:
self.bucket[b].append(k)
# returns the embedding of the searched key if found
def find_word_embedding(self, k, selection):
b = self.h(k, selection)
for n in self.bucket[b]:
if n.word == k:
return n.emb
return
# checks if a string only contains letters
def only_letters(string):
for letter in string:
if letter.lower() not in "abcdefghijklmnopqrstuvwxyz":
return False
return True
# returns the diffrence between two words using the words embedding
def words_diffrence(a, b):
if a is None or b is None:
return
diffrence = np.dot(a, b)/(np.linalg.norm(a)* np.linalg.norm(b))
return diffrence
#Driver
menu = 0 # used to stay in the menu until one of the two choices are picked
while menu <= 0:
print("Choose table implementation")
print("Type 1 for hash table using chaining or 2 for hash table using linear probing:")
choice = input() # the users input for the menu choice
print("Choice:", choice)
print()
if choice == "1":
print("Type 1 for the length of the string % n")
print("Type 2 for the ascii value (ord(c)) of the first character in the string % n")
print("Type 3 for the product of the ascii values of the first and last characters in the string % n")
print("Type 4 for the sum of the ascii values of the characters in the string % n")
print("Type 5 for recursive function h(”,n) = 1; h(S,n) = (ord(s[0]) + 255*h(s[1:],n))% n")
print("Type 6 for the Custom function")
print("Select a hash function:")
selection = int(input())
print("Selection:", selection)
print()
print("Building hash table with chaining")
print()
file = open('glove.6B.50d.txt', encoding = "utf8") # opens the glove.6B.50d file
table_size = 56432
H = HashTableChain(table_size)
start_time = time.time() #starts timer
for line in file.readlines():
try:
row = line.strip().split(' ')
word = row[0] # stores the word from the file
if only_letters(word) is True: # checks if the word only contains letters
H.insert(WordEmbedding(word, [(i) for i in row[1:]]), selection) # inserts the word and it's embedding into the hash table
except TypeError:
e = 2 # does noting so it can move to the next line in the file
run_time = (time.time() - start_time) #ends timer and stores the result in run_time
print("Hash table stats:")
print("Hash table size:", table_size)
print("Running time for hash table construction:", "%s seconds" % run_time) # outputs the running time of the hash table construction
print()
print("Reading word file to determine similarities")
print()
file2 = open('word file.txt', encoding = "utf8")# opens the file word_file which contains the list of the set of words
print("Word similarities found:")
start_time = time.time() # starts the timer
for line in file2.readlines():
try:
row = line.strip().split(' ')
word1 = row[0]# holds the first word
word2 = row[1]# holds the second word
print("Similarity:",word1, word2, "=", words_diffrence((H.find_word_embedding(word1, selection)), (H.find_word_embedding(word2, selection))))
except IndexError:
e = 2
run_time = (time.time() - start_time) # stores the running time for the hash table query in run_time
print()
print("Running time for hash table query processing:", "%s seconds" % run_time)
menu = 5 #Exits the while loop
elif choice == "2":
print("Type 1 for the length of the string % n")
print("Type 2 for the ascii value (ord(c)) of the first character in the string % n")
print("Type 3 for the product of the ascii values of the first and last characters in the string % n")
print("Type 4 for the sum of the ascii values of the characters in the string % n")
print("Type 5 for recursive function h(”,n) = 1; h(S,n) = (ord(s[0]) + 255*h(s[1:],n))% n")
print("Type 6 for the Custom function")
print("Select a hash function:")
selection = int(input())
print("Selection:", selection)
print()
print("Building hash table with linear probing")
print()
file = open('glove.6B.50d.txt', encoding = "utf8") # opens the glove.6B.50d file
table_size = 100 # I made the table size 100 for the hash table using linear probing to show it works because it takes too long with a larger size
H = HashTableLP(table_size)
start_time = time.time() #starts timer
for line in file.readlines():
try:
row = line.strip().split(' ')
word = row[0] # stores the word from the file
if only_letters(word) is True: # checks if the word only contains letters
H.insert(WordEmbedding(word, [(i) for i in row[1:]]), selection) # inserts the word and it's embedding into the hash table
except TypeError:
e = 2 # does noting so it can move to the next line in the file
run_time = (time.time() - start_time) #ends timer and stores the result in run_time
print("Hash table stats:")
print("Hash table size:", table_size)
print("Running time for hash table construction:", "%s seconds" % run_time) # outputs the running time of the hash table construction
print()
print("Reading word file to determine similarities")
print()
file2 = open('word file.txt', encoding = "utf8")# opens the file word_file which contains the list of the set of words
print("Word similarities found:")
start_time = time.time() # starts the timer
for line in file2.readlines():
try:
row = line.strip().split(' ')
word1 = row[0]# holds the first word
word2 = row[1]# holds the second word
print("Similarity:",word1, word2, "=", words_diffrence((H.find_word_embedding(word1, selection)), (H.find_word_embedding(word2, selection))))
except IndexError:
e = 2
run_time = (time.time() - start_time) # stores the running time for the hash table query in run_time
print()
print("Running time for hash table query processing:", "%s seconds" % run_time)
menu = 5 #Exits the while loop
else: # used if the user doesnt input 1 or 2 as their choice
print("Please select between 1 or 2")
print() |
# -*- coding: utf-8 -*-
"""
CS 2302 Data Structures
Author: John Rodriguez
Lab 2
Instructor: Olac Fuentes
TA: Anindita Nath
Date: 9/22/19
Purpose: use sorting algorithoms, bubble sort and difftent variations of quick sort to order a list
and return index k in that list after it's sorted
"""
import time
# Bubble Sort Function
def select_bubble(L,k):
# condition that checks if the parameteres are valid
if (k < 0) or (k >= len(L)) or (len(L) <= 0):
return -1
# loop that checks if the next number in the list is smaller then the current number
# and switches the two numbers if it is smaller
for i, num in enumerate(L):
try:
if L[i + 1] < num:
L[i] = L[i + 1]
L[i + 1] = num
select_bubble(L,k) # uses recursion to go threw list until sorted
except IndexError:
pass
return L[k]
# Partition Function used for Quick Sort
def partition(L,low,high):
i = ( low-1 ) #i given value of low in the list
pivot = L[high]
for j in range(low, high):
# if the number is smaller than the pviot it is placed to the left
if L[j] < pivot:
i = i + 1
L[i], L[j] = L[j], L[i]
# else it is larger than the pivot and placed to the right
L[i+1], L[high] = L[high], L[i+1]
return (i + 1)
# Quick Sort Function uses Recursion
def select_quick(L,low,high,k):
if (k < 0) or (k >= len(L)) or (len(L) <= 0):
return False
if low < high:
pivot = partition(L, low, high)
select_quick(L, low, (pivot-1), k)# items in the list that are smaller than the
select_quick(L, (pivot+1), high, k)# items in the list that are larger then the pivot
return L[k]
# Quick Sort Function sorts only the left or right of pivot deppending on value of k
def select_modified_quick(L,low,high,k):
if (k < 0) or (k >= len(L)) or (len(L) <= 0):
return False
if low < high:
pivot = partition(L, low, high)
# if will only order items in the list that are smaller than the value of k
if k < pivot:
select_modified_quick(L, low, (pivot-1), k)
# else will only order items in the list that are larger or equal to k
else:
select_modified_quick(L, (pivot+1), high, k)
return L[k]
# Quick Sort Function that uses a stack instead of recursion
def stack_select_quick(L, k):
# makes a stack
high = len(L) - 1 # hold the index of the high
low = 0 # holds the index of the low
size = (high + 1) - low # size of the stack
stack = [0] * (size)
top = -1 #holds the index for the top of the stack
# this pushes the initial values of the low and high
top = top + 1
stack[top] = low
top = top + 1
stack[top] = high
# this pops from stack until it's empty
while top >= 0:
high = stack[top]
top = top - 1
low = stack[top]
top = top - 1
pivot = partition(L, low, high)
# pushes numbers to the left of the pivot to the left of the stack
if (pivot - 1) > low:
top = top + 1
stack[top] = low
top = top + 1
stack[top] = pivot - 1
# pushes numbers to the right of the pivot to the right of the stack
if pivot + 1 < high:
top = top + 1
stack[top] = pivot + 1
top = top + 1
stack[top] = high
return L[k]
# Main
a = 3
#Lists to test if functions work
test1_a = [55, 50, 130, 20, 100, 25, 70, 125, 35, 135, 80, 45, 10, 105, 5, 85, 60, 115, 65, 110, 90, 30, 75, 40, 120, 95, 15, 140]
test1_b = [55, 50, 130, 20, 100, 25, 70, 125, 35, 135, 80, 45, 10, 105, 5, 85, 60, 115, 65, 110, 90, 30, 75, 40, 120, 95, 15, 140]
test1_c = [55, 50, 130, 20, 100, 25, 70, 125, 35, 135, 80, 45, 10, 105, 5, 85, 60, 115, 65, 110, 90, 30, 75, 40, 120, 95, 15, 140]
test1_d = [55, 50, 130, 20, 100, 25, 70, 125, 35, 135, 80, 45, 10, 105, 5, 85, 60, 115, 65, 110, 90, 30, 75, 40, 120, 95, 15, 140]
#bubble sort
print('Bubble Sort')
print("list unsorted")
print(test1_a)
print()
start = time.time()#starts the timer
print(select_bubble(test1_a, a), " is the", (a + 1), "th smallest element in the list")
end = time.time()#ends the timer
print("It took ", (end - start), " seconds to sort")
print()
print("list sorted")
print(test1_a)
print()
print()
#quick sort
print('Quick Sort')
print("list unsorted")
print(test1_b)
print()
start = time.time()#starts the timer
print(select_quick(test1_b, 0, (len(test1_b) - 1), a), " is the", (a + 1), "th smallest element in the list")
end = time.time()#ends the timer
print("It took ", (end - start), " seconds to sort")
print()
print("list sorted")
print(test1_b)
print()
print()
#modified quick sort
print('Modified Quick Sort')
print("list unsorted")
print(test1_c)
print()
start = time.time()#starts the timer
print(select_modified_quick(test1_c, 0, (len(test1_c) - 1), a), " is the", (a + 1), "th smallest element in the list")
end = time.time()#ends the timer
print("It took ", (end - start), " seconds to sort")
print()
print("modified list")
print(test1_c)
print()
print()
#quick sort using a stack
print('Quick Sort using Stack')
print("list unsorted")
print(test1_d)
print()
start = time.time()#starts the timer
print(stack_select_quick(test1_d, a), " is the", (a + 1), "th smallest element in the list")
end = time.time()#ends the timer
print("It took ", (end - start), " seconds to sort")
print()
print("list sorted")
print(test1_d)
print()
print()
|
"""
[basketball.py]
Basketball Plugin
[Author]
Konstantinos Efthymiadis
[About]
Given the event and year as parameters, the plugin will return the countries that won the medal that year
Given the event and country as parameters, the plugin will return the number of medals this country has won
[Commands]
>>> .basketball <<event>> <<year/country>>
returns a string with all the information
>>> .basketball <<event>> <<all>>
returns a table with all the medals of all the years
"""
dataEuroBasket = {
"1935": ["Latvia", "Spain", "Czechoslovakia", "24-18"],
"1937": ["Lithuania", "Italy", "France", "24-23"],
"1939": ["Lithuania", "Latvia", "Poland", "No playOffs"],
"1946": ["Czechoslovakia", "Italy", "Hungary", "34-32"],
"1947": ["USSR", "Czechoslovakia", "Egypt", "56-37"],
"1949": ["Egypt", "France", "Greece", "No playOffs"],
"1951": ["USSR", "Czechoslovakia", "France", "45-44"],
"1953": ["USSR", "Hungary", "France", "No playOffs"],
"1955": ["Hungary", "Czechoslovakia", "USSR", "No playOffs"],
"1957": ["USSR", "Bulgaria", "Czechoslovakia", "No playOffs"],
"1959": ["USSR", "Czechoslovakia", "France", "No playOffs"],
"1961": ["USSR", "Yugoslavia", "Bulgaria", "60-53"],
"1963": ["USSR", "Poland", "Yugoslavia", "61-45"],
"1965": ["USSR", "Yugoslavia", "Poland", "58-49"],
"1967": ["USSR", "Czechoslovakia", "Poland", "89-77"],
"1969": ["USSR", "Yugoslavia", "Czechoslovakia", "81-72"],
"1971": ["USSR", "Yugoslavia", "Italy", "69-64"],
"1973": ["Yugoslavia", "Spain", "USSR", "78-67"],
"1975": ["Yugoslavia", "USSR", "Italy", "No playOffs"],
"1977": ["Yugoslavia", "USSR", "Czechoslovakia", "74-61"],
"1979": ["USSR", "Israel", "Yugoslavia", "98-76"],
"1981": ["USSR", "Yugoslavia", "Czechoslovakia", "84-67"],
"1983": ["Italy", "Spain", "USSR", "105-96"],
"1985": ["USSR", "Czechoslovakia", "Italy", "120-89"],
"1987": ["Greece", "USSR", "Yugoslavia", "103-101"],
"1989": ["Yugoslavia", "Greece", "USSR", "98-77"],
"1991": ["Yugoslavia", "Italy", "Spain", "88-73"],
"1993": ["Germany", "Russia", "Croatia", "71-70"],
"1995": ["Yugoslavia", "Lithuania", "Croatia", "96-90"],
"1997": ["Yugoslavia", "Italy", "Russia", "61-49"],
"1999": ["Italy", "Spain", "Yugoslavia", "64-56"],
"2001": ["Yugoslavia", "Turkey", "Spain", "78-69"],
"2003": ["Lithuania", "Spain", "Italy", "93-84"],
"2005": ["Greece", "Germany", "France", "78-62"],
"2007": ["Russia", "Spain", "Lithuania", "60-59"],
"2009": ["Spain", "Serbia", "Greece", "85-63"],
"2011": ["Spain", "France", "Russia", "98-85"],
"2013": ["France", "Lithuania", "Spain", "80-66"],
"2015": ["Spain", "Lithuania", "France", "80-63"],
"2017": ["Slovenia", "Serbia", "Spain", "93-85"],
"2022": ["Spain", "France", "Germany", "88-76"],
}
dataWorldCup = {
"1950": ["Argentina", "USA", "Chile", "64-50"],
"1954": ["USA", "Brazil", "Philippines", "62-41"],
"1959": ["Brazil", "USA", "Chile", "81-67"],
"1963": ["Brazil", "Yugoslavia", "USSR", "90-71"],
"1967": ["USSR", "Yugoslavia", "Brazil", "71-59"],
"1970": ["Yugoslavia", "Brazil", "USSR", "80-55"],
"1974": ["USSR", "Yugoslavia", "USA", "79-82"],
"1978": ["Yugoslavia", "USSR", "Brazil", "82-81"],
"1982": ["USSR", "USA", "Yugoslavia", "95-94"],
"1986": ["USA", "USSR", "Yugoslavia", "87-85"],
"1990": ["Yugoslavia", "USSR", "USA", "92-75"],
"1994": ["USA", "Russia", "Croatia", "137-91"],
"1998": ["Yugoslavia", "Russia", "USA", "64-62"],
"2002": ["Yugoslavia", "Argentina", "Germany", "84-77"],
"2006": ["Spain", "Greece", "USA", "70-47"],
"2010": ["USA", "Turkey", "Lithuania", "81-64"],
"2014": ["USA", "Serbia", "France", "129-92"],
"2019": ["Spain", "Argentina", "France", "95-75"],
}
class Plugin:
def __init__(self):
pass
def __accordingToYear__(year, event):
dataEvent = {}
if event == "eu":
dataEvent = dataEuroBasket
elif event == "wc":
dataEvent = dataWorldCup
if year in dataEvent:
data = dataEvent.get(year)
text = "Gold: " + data[0] + "\nSilver: " + data[1] + "\nBronze: " + data[2]
if data[3] != "No playOffs":
text += "\nFinal Score:\n" + data[0] + " " + data[3] + " " + data[1]
return text
else:
return "No results for that year"
def __accordingToCountry__(country, event):
dataEvent = {}
if event == "eu":
dataEvent = dataEuroBasket
elif event == "wc":
dataEvent = dataWorldCup
goldMedal = 0
silverMedal = 0
bronzeMedal = 0
for value in dataEvent.values():
if value[0].upper() == country.upper():
goldMedal += 1
elif value[1].upper() == country.upper():
silverMedal += 1
elif value[2].upper() == country.upper():
bronzeMedal += 1
if goldMedal == silverMedal and silverMedal == bronzeMedal and bronzeMedal == 0:
return "The country: " + country + " does not have any medal"
else:
text = (
country
+ " Medals:\n"
+ "Gold: "
+ str(goldMedal)
+ "\nSilver: "
+ str(silverMedal)
+ "\nBronze: "
+ str(bronzeMedal)
+ "\nTotal Medals: "
+ str(goldMedal + silverMedal + bronzeMedal)
)
return text
def __createTable__(maxLen, word):
whiteCharacters = maxLen - len(word)
text = ""
for i in range(0, whiteCharacters // 2):
text += " "
text += word
for i in range(whiteCharacters // 2, whiteCharacters):
text += " "
text += "|"
return text
def __allTheMedalsAllTheYears__(event):
dataEvent = {}
text = ""
if event == "eu":
dataEvent = dataEuroBasket
text = "European Basketball Championship\n"
elif event == "wc":
dataEvent = dataWorldCup
text = "FIBA Basketball World Cup\n"
if not dataEvent:
return
maxForGold = -1
maxForSilver = -1
maxForBronze = -1
for value in dataEvent.values():
if len(value[0]) > maxForGold:
maxForGold = len(value[0])
if len(value[1]) > maxForSilver:
maxForSilver = len(value[1])
if len(value[2]) > maxForBronze:
maxForBronze = len(value[2])
goldMedal = "Gold Medal"
silverMedal = "Silver Medal"
bronzeMedal = "Bronze Medal"
if len(goldMedal) > maxForGold:
maxForGold = len(goldMedal)
if len(silverMedal) > maxForSilver:
maxForSilver = len(silverMedal)
if len(bronzeMedal) > maxForBronze:
maxForBronze = len(bronzeMedal)
text += "|Year|"
text += Plugin.__createTable__(maxForGold, goldMedal)
text += Plugin.__createTable__(maxForSilver, silverMedal)
text += Plugin.__createTable__(maxForBronze, bronzeMedal)
text += "\n"
for key in dataEvent.keys():
text += "|" + key + "|"
temp = dataEvent.get(key)
text += Plugin.__createTable__(maxForGold, temp[0])
text += Plugin.__createTable__(maxForSilver, temp[1])
text += Plugin.__createTable__(maxForBronze, temp[2])
text += "\n"
return text
def run(self, incoming, methods, info, bot_info):
try:
msgs = info["args"][1:][0].split()
if info["command"] == "PRIVMSG" and len(msgs) == 3 and msgs[0] == ".basketball":
event = msgs[1]
if msgs[2] == "all":
methods["send"](info["address"], Plugin.__allTheMedalsAllTheYears__(msgs[1]))
elif msgs[2].isnumeric():
methods["send"](info["address"], Plugin.__accordingToYear__(msgs[2], msgs[1]))
else:
methods["send"](
info["address"], Plugin.__accordingToCountry__(msgs[2], msgs[1])
)
except Exception as e:
print("Something Wrong. There is a Plugin Error: ", e)
|
"""
[roman_numeral.py]
Roman Numeral Converter Plugin
[Author]
Nick Wiley
[About]
Returns the roman numeral equivalent of the number inputted
[Commands]
>>> .roman <number>
returns number represented in roman numerals
"""
class Plugin:
def __init__(self):
pass
def __convert_roman_numeral(self, num):
"""Converts number into a roman numeral"""
roman_numerals = [
"I",
"II",
"III",
"IV",
"V",
"VI",
"VII",
"VIII",
"IX",
"X",
"L",
"C",
"D",
"M",
]
if num >= 1000:
num -= 1000
return roman_numerals[13] + Plugin.__convert_roman_numeral(self, num)
elif num >= 500:
num -= 500
return roman_numerals[12] + Plugin.__convert_roman_numeral(self, num)
elif num >= 400:
num -= 400
return (
roman_numerals[11] + roman_numerals[12] + Plugin.__convert_roman_numeral(self, num)
)
elif num >= 100:
num -= 100
return roman_numerals[11] + Plugin.__convert_roman_numeral(self, num)
elif num >= 90:
num -= 90
return (
roman_numerals[9] + roman_numerals[11] + Plugin.__convert_roman_numeral(self, num)
)
elif num >= 50:
num -= 50
return roman_numerals[10] + Plugin.__convert_roman_numeral(self, num)
elif num >= 40:
num -= 40
return (
roman_numerals[9] + roman_numerals[10] + Plugin.__convert_roman_numeral(self, num)
)
elif num > 10:
num -= 10
return roman_numerals[9] + Plugin.__convert_roman_numeral(self, num)
elif num > 0:
return roman_numerals[num - 1]
else:
return ""
def run(self, incoming, methods, info, bot_info):
try:
msgs = info["args"][1:][0].split()
if info["command"] == "PRIVMSG":
if len(msgs) > 1:
if msgs[0] == ".roman":
num = int(msgs[1])
if num < 1:
methods["send"](info["address"], "Input a number greater than 0")
else:
methods["send"](
info["address"],
Plugin.__convert_roman_numeral(self, num),
)
except Exception as e:
print("Error with roman_numeral plugin:", e)
|
""" player class """
# pylint: disable=E1601
import game_init
class Player:
"""player class"""
def __init__(self, nr, chips, username):
"""player initialization"""
self.__position_nr = nr
self.__general_name = "player" + str(nr)
self.__username = username
self.__chips = chips
self.__hand = []
self.add_position(nr)
def number(self):
"""show number"""
return self.__number
def general_name(self):
"""general name"""
return self.__general_name
def show_player_hand(self):
"""show hand"""
return self.__hand
def add_hand(self, hand):
"""adding hand to player"""
self.__hand = hand
def chips(self):
"""show chips"""
return self.__chips
def increase_chips(self, win_chips):
"""winning money"""
self.__chips = self.__chips + win_chips
def decrease_chips(self, lost_chips):
"""losing money"""
self.__chips = self.__chips - lost_chips
def position_nr(self):
"""show position number"""
return self.__position_nr
def position_name(self):
"""show position name"""
return self.__position_name
def add_position(self, position_nr):
"""adding position"""
if position_nr >= 0 and position_nr <= 5:
self.__position_nr = position_nr
if self.__position_nr == 0:
self.__position_name = "Small Blind"
elif self.__position_nr == 1:
self.__position_name = "Big Blind"
elif self.__position_nr == 2:
self.__position_name = "Under the Gun"
elif self.__position_nr == 3:
self.__position_name = "Middle"
elif self.__position_nr == 4:
self.__position_name = "Tail"
else:
self.__position_name = "Dealer"
else:
print("Position nr is too big or too little")
pass
def bet(self, amount):
"""change game_init to the file where the game info is stored"""
game_init.game[2].increase_pot(amount)
self.decrease_chips(0)
def get_name(self):
"""show player's name"""
return self.__username
def add_card_to_hand(self, card):
"""add a card to the player's hand"""
index = len(self.__hand.show_hand_obj())
self.__hand.show_hand_obj().append(card)
|
"""
Task 2.
Write a program that queries the user for persons’ names and ages and saves them into a dictionary with name as a key and age as a value. When the user enters an empty string as a name,
the program outputs the dictionary and terminates.
Example run:
Enter a name or an empty string to stop: James
Enter age: 25
Enter a name or an empty string to stop: Jane
Enter age: 31
Enter a name or an empty string to stop:
{'James' : 25, 'Jane' : 31 }
"""
user_dict = {}
while True:
name = str(input('Enter a name or an empty string to stop:'))
if name == "":
print(user_dict)
break
else:
age = str(input('Enter age:'))
user_dict[name] = age
|
"""
Write a procedure remove_duplicates(n), which finds and removes duplicate items from a list
given as an argument. Hence, after the procedure is called, only a single instance of each item
can be found in a list.
lst = [1, 2, 1, 3, 3, 2, -1, 5, 3, 5, -1, 2, 5]
remove_duplicates(lst)
print (lst)
[1, 2, 3, -1, 5]
"""
def duplicate_remover(x):
# Convert to dictionary from list
dict_from_list = dict.fromkeys(x)
list_from_dict = list(dict_from_list)
return list_from_dict
lst = [1, 2, 1, 3, 3, 2, -1, 5, 3, 5, -1, 2, 5]
mylist = duplicate_remover(lst)
print(mylist)
|
#Question3
def strCase(userStr):
upCase =0
lowCase =0
for i in userStr:
ascNum = ord(i)
#print(ascNum)
if((ascNum >= 65 and ascNum <=90)):
upCase = upCase + 1
else:
lowCase = lowCase + 1
print("Uppercase Letters:",upCase)
print("Lowercase letters:",lowCase)
#Input a string from user
userStr = input('Enter a string:')
strCase(userStr)
|
#Function are defined here
#Name function
def funcName(firstName,lastName):
fName = (firstName +" "+ lastName)
return (fName)
#Percent function
def perMarks(listMark,noSubj):
totMark=sum(listMarks)
marksPer = totMark/noSubj
return marksPer
#Marks Fucntion
def totMarks(listMark):
totMark=sum(listMarks)
return totMark
# Grading Function
def funcGrade(marksPer):
if(int(markPer) >= 95):
return('A')
elif(int(markPer) >= 85 and int(markPer) <= 95):
return('B')
elif(int(markPer) >= 75 and int(markPer) <= 85):
return('C')
elif(int(markPer) >= 65 and int(markPer) <= 75):
return('D')
else:
return("FAILED")
#Master function
def masterFunc(firstName,lastName,listMarks,noSubj,marksPer):
print(funcName(firstName,lastName))
print("Your Percentage:", perMarks(listMarks,noSubj))
print("Your Grade:", funcGrade(marksPer))
# Input
firstName = input("Please Enter your first name:")
lastName = input("Please Enter your last name:")
noSubj = int(input("Please enter the number of subjects"))
#Declaring an empty list for marks
listMarks = []
for i in range (0,noSubj):
markSubj = float(input("Enter the marks of subject:"))
listMarks.append(markSubj)
marksPer = perMarks(listMarks,noSubj)
#Printing
masterFunc(firstName,lastName,listMarks,noSubj,marksPer)
|
#Main Function
def main():
#declaring an empty list to add objects of class Course
courseList = []
courseListFunc(courseList)
#declaring an empty list to add objects of class Student
stdList = []
studentList(stdList, courseList)
choice = 0
while choice >= 0:
#calling of menu()
menu()
choice = int(input("Enter your choice: "))
if choice == 1:
print("--Course ID-- --Course Name-- --Course Credit--")
#iterating to print the list of available courses
for i in range(courseList.__len__()):
Course.getCourse(courseList[i])
print()
print()
if choice == 2:
print("--Student ID-- --Student Name--")
#iterating to print the list of students
for i in range(stdList.__len__()):
Student.dispStudent(stdList[i])
print()
if choice == 3:
#iterating to print the list of students and their enrollement
for i in range(stdList.__len__()):
Student.stuEnrollment(stdList[i],0)
print()
if choice == 4:
#Checking if fees is paid or not
for i in range(stdList.__len__()):
if stdList[i].checkFee() == True:
Student.stuEnrollment(stdList[i],1)
else:
#if fee is not paid
Student.dispStudent(stdList[i])
print("Please pay the tuiton fees",Student.calFee(stdList[i]),"baht")
print()
if choice == 0:
print("Exit")
#SuperClass person defined
class Person:
def __init__(self):
self.__Fname = " "
self.__Lname = " "
def printName(self):
self.__Fname = input("Enter First Name:")
self.__Lname = input("Enter Last Name:")
#Inherting the student class
class Student(Person):
def __init__(self):
super().__init__(self)
self.__Fname = " "
self.__Lname = " "
self.__stdID = " "
self.__noOfCourses = ""
self.__feePaid = " "
self.__listCourses = " "
self.__listGrader = " "
#function to check if fees is paid or not
def checkFee(self):
if(self.paidFee == 1):
x = True
return(bool(x))
else:
x = False
return(bool(x))
#using acceser and mutators
def stdFee(self):
tot = 0;
for i in range (0,self.__noOfCourses):
tot = tot + course.courseCredit(self.listCourses[i])
return(tot * 500)
#function to calculate and return GPA of a student
def calGPA(self):
sum = 0
x = 0
stdGradeList = []
for i in range(self.__noOfCourses):
sum += Course.crsCredit(self.__listCourses[i])
for i in range(self.__noOfCourses) :
if self.__listGrader[i] == "A":
gradeW = 4
elif self.__listGrader[i] == "B":
gradeW = 3
elif self.__listGrader[i] == "C":
gradeW = 2
elif self.__listGrader[i] == "D":
gradeW = 1
else:
gradeW = 0
stdGradeList.append(gradeW)
for i in range(self.__noOfCourses):
totCred += Course.crsCredit(self.__listCourses[i]) * stdGradeList[i]
stdGPA = totCred / sum
return(stdGPA)
#Using Functions to display student info
def dispStudent(self):
print(self.studentId, end =" ")
Person.getPerson(self)
def stuEnrollment(self, flag):
print(self.studentId, end = "")
Person.getPerson(self)
print("--Course ID -- --Course Name-- --Course Credit Grades--")
for i in range(self.__noOfCourses):
Course.getCourse(self.__listCourses[i])
print(self.__listGrader[i])
tutionFee = Student.calFee(self)
if(flag == 0):
print("Tuition Fee:",tuitionFee,"baht")
else:
print("Tuition Fee paid:",tuitionFee,"baht")
stdGPA = Student.calGPA(self)
print("Student GPA:",stdGPA)
class Course:
#Constructor
def __init__(self,__courseID,__courseName,__courseCredits):
self.__courseName = ""
self.__courseID = ""
self.__courseCredits = ""
#returning credits
def creditCourse(self):
return(self.__courseCredits)
#Printing the details of the student
def detailCourse(self):
print(self.__courseName)
print(self.__courseID)
print(self.__courseCredits)
#Course menu
def courseMenu():
print("***MENU***")
print("1.List Courses")
print("2.List Students")
print("3.List Students and Enrollment")
print("4.Grade Report")
print("0.Exit")
def courseListFunc(courseList):
i = 0
while(i <= 6):
CourseIdFunc = int(input("Enter Course ID:"))
CourseSubFunc = input("Enter Course Name:")
CourseCrFunc = int(input("Enter the course credits:"))
objCrs = Course(CourseIdFunc,CourseSubFunc,CourseCrFunc)
courseList.append(objCrs)
i = i+1
def studentList(stdList, courseList):
objStu = Student(12345, "John Wayn", 4,1,[cousreList[0],cousreList[1],cousreList[5],cousreList[6]],['A','B','B','A'])
stdList.append(objStu)
objStu = Student(12346, "Jane March", 5,1,[cousreList[1],cousreList[2],cousreList[4],cousreList[5],cousreList[6]],['A','B','B','C','D'])
stdList.append(objStu)
objStu = Student(12347, "Marry Dolphin", 5,0,[cousreList[0],cousreList[3],cousreList[4],cousreList[5],cousreList[6]],['C','B','C','A','B'])
stdList.append(objStu)
#Calling the Main Function
main()
|
for i in range(10):
print("begin")
print("i is", i)
i += 2
print("i is", i)
print("end")
|
# -*- coding: utf-8 -*-
from typing import List
def binary_search_recursive(arr: List[int], low: int, high: int, x: int) -> int:
"""
recursive_version
如果x in arr,傳回x的index,否則傳回-1
若x在arr中出現多次時,mid不一定會回傳最先出現的index, 需要再額外的判斷
"""
if high >= low:
mid = (high + low) // 2
if arr[mid] == x:
# match
return mid
elif arr[mid] > x:
# take left half
return binary_search_recursive(arr, low, mid - 1, x)
else:
# take right half
return binary_search_recursive(arr, mid + 1, high, x)
else:
# not match
return -1
def binary_search_iter(arr: List[int], x: int) -> int:
"""
iterative_version
如果x in arr,傳回x的index,否則傳回-1
若x在arr中出現多次時,mid不一定會回傳最先出現的index, 需要再額外的判斷
"""
low = 0
high = len(arr) - 1
while low <= high:
mid = (low + high) // 2
if arr[mid] < x:
# take right half
low = mid + 1
elif arr[mid] > x:
# take left half
upper = mid - 1
else:
# match
return mid
# not match
return -1
|
import numpy as np
class Node:
def __init__(self, value, previous, next, is_start=False):
self.value = value
self.previous = previous
self.next = next
self.is_start = is_start
# Linked-in list implementation of Queue
class Queue:
def __init__(self):
self.start_node = None
self.end_node = None
def add_element(self, element):
if self.start_node is None:
node = Node(value=element, previous=None, next=None, is_start=True)
self.start_node = node
self.end_node = node
del node
else:
node = Node(value=element, previous=self.end_node, next=None, is_start=False)
self.end_node.next = node
self.end_node = node
del node
def remove_element(self):
if self.start_node is None:
return None
else:
node = self.start_node
if self.start_node.next is None:
self.start_node = None
self.end_node = None
else:
self.start_node = node.next
self.start_node.previous = None
return node.value
def construct_queue(self, inputs):
print('Constructing queue.')
for curr_idx, curr_input in enumerate(inputs):
print(curr_input),
self.add_element(element=curr_input)
print('')
def traverse(self):
curr_node = self.start_node
print('Traversing queue.')
while curr_node is not None:
print(curr_node.value),
curr_node = curr_node.next
print('')
if __name__ == '__main__':
inputs = np.array([4, 21, 45, 12, 3, 1])
queue_obj = Queue()
queue_obj.construct_queue(inputs=inputs)
queue_obj.traverse()
|
import numpy as np
import queue
import stack
class TreeNode:
def __init__(self, value, left=None, right=None, is_root=False):
self.value = value
self._left = left
self._right = right
self.is_root = is_root
self.is_visited = False
def find_position_for_element(self, element):
assert element is not None
if element <= self.value:
if self._left is not None:
return self._left.find_position_for_element(element)
else:
return self, 0
else:
if self._right is not None:
return self._right.find_position_for_element(element)
else:
return self, 1
def add_child(self, position, element):
child_node = TreeNode(value=element)
if position == 0:
# left position
self._left = child_node
elif position == 1:
# right position
self._right = child_node
else:
raise NotImplementedError
del position, child_node
def preorder_traversal(self):
# node
print(self.value),
# left child
if self._left is not None:
self._left.preorder_traversal()
# right child
if self._right is not None:
self._right.preorder_traversal()
def inorder_traversal(self):
# left child
if self._left is not None:
self._left.inorder_traversal()
# node
print(self.value),
# right child
if self._right is not None:
self._right.inorder_traversal()
def postorder_traversal(self):
# left child
if self._left is not None:
self._left.postorder_traversal()
# right child
if self._right is not None:
self._right.postorder_traversal()
# node
print(self.value),
def is_leaf_node(self):
if (self._left is None) and (self._right is None):
return True
else:
return False
def depth_first_traverse_recursion(self):
assert not self.is_visited
self.is_visited = True
depth = 0
# left child
if (self._left is not None) and (not self._left.is_visited):
left_subtree_depth = self._left.depth_first_traverse_recursion()
depth = max(depth, left_subtree_depth)
# right child
if (self._right is not None) and (not self._right.is_visited):
right_subtree_depth = self._right.depth_first_traverse_recursion()
depth = max(depth, right_subtree_depth)
# node itself
print(self.value),
self.is_visited = False
depth += 1
return depth
def max_depth_recursion(self):
if self.is_leaf_node():
return 1
else:
# left child
if self._left is not None:
left_subtree_depth = self._left.max_depth_recursion()
else:
left_subtree_depth = 0
# right child
if self._right is not None:
right_subtree_depth = self._right.max_depth_recursion()
else:
right_subtree_depth = 0
return max(left_subtree_depth, right_subtree_depth)+1
def path_sums_recursion(self, path_sum, sum=0):
sum += self.value
if self.is_leaf_node():
if sum == path_sum:
return True
else:
return False
else:
# left child
if (self._left is not None) and (not self._left.is_visited):
is_path_sum_match_left_subtree = self._left.path_sums_recursion(path_sum=path_sum, sum=sum)
else:
is_path_sum_match_left_subtree = False
# right child
if (self._right is not None) and (not self._right.is_visited):
is_path_sum_match_right_subtree = self._right.path_sums_recursion(path_sum=path_sum, sum=sum)
else:
is_path_sum_match_right_subtree = False
return is_path_sum_match_left_subtree | is_path_sum_match_right_subtree
def depth_first_traverse(self):
traversed_nodes = []
max_depth = 0
stack_obj = stack.Stack()
assert not self.is_visited
self.is_visited = True
stack_obj.push(self)
max_depth = max(max_depth, stack_obj.depth)
while not stack_obj.is_empty():
curr_node = stack_obj.peek()
# print('Peeked {}.'.format(curr_node.value))
assert curr_node is not None
is_leaf_node_pushed = False
if not curr_node.is_leaf_node():
if (curr_node._left is not None) and (not curr_node._left.is_visited):
curr_node._left.is_visited = True
stack_obj.push(curr_node._left)
# print('Pushing left {}.'.format(curr_node._left.value))
is_leaf_node_pushed = True
max_depth = max(stack_obj.depth, max_depth)
elif (curr_node._right is not None) and (not curr_node._right.is_visited):
curr_node._right.is_visited = True
stack_obj.push(curr_node._right)
# print('Pushing right {}.'.format(curr_node._right.value))
is_leaf_node_pushed = True
max_depth = max(stack_obj.depth, max_depth)
if not is_leaf_node_pushed:
curr_node = stack_obj.pop()
traversed_nodes.append(curr_node)
# print('Popping {}.'.format(curr_node.value))
for curr_node in traversed_nodes:
curr_node.is_visited = False
print(curr_node.value),
print('')
print(max_depth)
return traversed_nodes, max_depth
@staticmethod
def split_inorder_into_left_and_right_subtree_elements(inorder_elements, root_element):
# assume unique elements
root_in_inorder_idx = np.where(inorder_elements == root_element)[0]
assert root_in_inorder_idx.size == 1
root_in_inorder_idx = root_in_inorder_idx[0]
left_subtree_elements = inorder_elements[:root_in_inorder_idx]
right_subtree_elements = inorder_elements[root_in_inorder_idx+1:]
return left_subtree_elements, right_subtree_elements
@staticmethod
def select_subset_of_elements_from_array_keeping_order(ordered_arr, elements_to_select):
assert ordered_arr.dtype == elements_to_select.dtype
ordered_indices_of_elements = np.zeros(elements_to_select.size, ordered_arr.dtype)
count_idx = 0
for curr_idx, curr_element in enumerate(ordered_arr):
if curr_element in elements_to_select:
ordered_indices_of_elements[count_idx] = curr_element
count_idx += 1
return ordered_indices_of_elements
@staticmethod
def construct_binary_tree_from_inorder_and_postorder_traversal(inorder_elements, postorder_elements):
# assume unique elements
num_elements = inorder_elements.size
assert num_elements == postorder_elements.size
assert np.unique(inorder_elements).size == num_elements
assert np.unique(postorder_elements).size == num_elements
if num_elements == 0:
return None
else:
root_element = postorder_elements[-1]
inorder_left_subtree_elements, inorder_right_subtree_elements = \
TreeNode.split_inorder_into_left_and_right_subtree_elements(
inorder_elements=inorder_elements,
root_element=root_element,
)
postorder_left_subtree_elements = TreeNode.select_subset_of_elements_from_array_keeping_order(
ordered_arr=postorder_elements,
elements_to_select=inorder_left_subtree_elements,
)
postorder_right_subtree_elements = TreeNode.select_subset_of_elements_from_array_keeping_order(
ordered_arr=postorder_elements,
elements_to_select=inorder_right_subtree_elements,
)
root_node = TreeNode(value=root_element)
root_node._left = TreeNode.construct_binary_tree_from_inorder_and_postorder_traversal(
inorder_elements=inorder_left_subtree_elements,
postorder_elements=postorder_left_subtree_elements,
)
root_node._right = TreeNode.construct_binary_tree_from_inorder_and_postorder_traversal(
inorder_elements=inorder_right_subtree_elements,
postorder_elements=postorder_right_subtree_elements,
)
return root_node
@staticmethod
def construct_binary_tree_from_inorder_and_preorder_traversal(inorder_elements, preorder_elements):
# assume unique elements
num_elements = inorder_elements.size
assert num_elements == preorder_elements.size
assert np.unique(inorder_elements).size == num_elements
assert np.unique(preorder_elements).size == num_elements
if num_elements == 0:
return None
else:
root_element = preorder_elements[0]
inorder_left_subtree_elements, inorder_right_subtree_elements = \
TreeNode.split_inorder_into_left_and_right_subtree_elements(
inorder_elements=inorder_elements,
root_element=root_element,
)
preorder_left_subtree_elements = TreeNode.select_subset_of_elements_from_array_keeping_order(
ordered_arr=preorder_elements,
elements_to_select=inorder_left_subtree_elements,
)
preorder_right_subtree_elements = TreeNode.select_subset_of_elements_from_array_keeping_order(
ordered_arr=preorder_elements,
elements_to_select=inorder_right_subtree_elements,
)
root_node = TreeNode(value=root_element)
root_node._left = TreeNode.construct_binary_tree_from_inorder_and_preorder_traversal(
inorder_elements=inorder_left_subtree_elements,
preorder_elements=preorder_left_subtree_elements,
)
root_node._right = TreeNode.construct_binary_tree_from_inorder_and_preorder_traversal(
inorder_elements=inorder_right_subtree_elements,
preorder_elements=preorder_right_subtree_elements,
)
return root_node
class BinaryTree:
def __init__(self):
self._root = None
def construct_from_inorder_and_postorder(self, inorder_elements, postorder_elements):
self._root = TreeNode.construct_binary_tree_from_inorder_and_postorder_traversal(
inorder_elements=inorder_elements,
postorder_elements=postorder_elements,
)
def construct_from_inorder_and_preorder(self, inorder_elements, preorder_elements):
self._root = TreeNode.construct_binary_tree_from_inorder_and_preorder_traversal(
inorder_elements=inorder_elements,
preorder_elements=preorder_elements,
)
def add_element(self, element):
if self._root is None:
print('Adding {} as a root node.'.format(element))
self._root = TreeNode(element, left=None, right=None, is_root=True)
else:
parent_node, position = self._root.find_position_for_element(element=element)
print('Adding {} as a {} child to {}.'.format(element, position, parent_node.value))
parent_node.add_child(position=position, element=element)
def construct_binary_tree(self, inputs):
print('........Construction of Tree .......')
for curr_idx, curr_input in enumerate(inputs):
self.add_element(curr_input)
print('')
def breadth_first_traversal(self):
if self._root is None:
print('Tree is empty.')
else:
queue_obj = queue.Queue()
queue_obj.add_element(self._root)
while True:
curr_node = queue_obj.remove_element()
if curr_node is None:
break
else:
print(curr_node.value),
if curr_node._left is not None:
queue_obj.add_element(curr_node._left)
if curr_node._right is not None:
queue_obj.add_element(curr_node._right)
def depth_first_traveral_recursion(self):
# using function call stack
if self._root is None:
print('Tree is empty.')
else:
print('Depth first recursion without stack.')
max_depth = self._root.depth_first_traverse_recursion()
print('')
print(max_depth)
def match_two_lists_nodes_by_value(self, list1, list2):
for curr_idx, curr_node_list1 in enumerate(list1):
curr_node_list2 = list2[curr_idx]
if curr_node_list1.value != curr_node_list2.value:
return False
return True
def _mirror_image(self, node1, node2):
if (node1 is not None) and (node2 is not None):
if node2.value != node2.value:
return False
else:
return self._mirror_image(node1._right, node2._left) & self._mirror_image(node1._left, node2._right)
elif (node1 is None) and (node2 is None):
return True
else:
return False
def is_symmetric(self):
print('Is Symmetric?')
root_node = self._root
if root_node is None:
return None
else:
if root_node.is_leaf_node():
return True
else:
return self._mirror_image(root_node._left, root_node._right)
def max_depth(self):
if self._root is None:
return 0
else:
return self._root.max_depth_recursion()
def path_sums_recursion(self, path_sum):
if self._root is None:
if path_sum == 0:
return True
else:
return False
else:
return self._root.path_sums_recursion(path_sum=path_sum)
def depth_first_traveral(self):
if self._root is None:
print('Tree is empty.')
else:
traversed_nodes, max_depth = self._root.depth_first_traverse()
def construct_binary_tree_for_symmetry_and_test(self):
self._root = TreeNode(value=1, is_root=True)
self._root._left = TreeNode(value=2)
self._root._right = TreeNode(value=2)
self._root._left._left = TreeNode(value=3)
self._root._left._right = TreeNode(value=4)
self._root._right._left = TreeNode(value=4)
self._root._right._right = TreeNode(value=3)
is_symmetric = self.is_symmetric()
print('is_symmetric', is_symmetric)
def traversal(self, traveral_type):
if self._root is not None:
if traveral_type == 'pre_order':
print('.......Pre-order traversal........')
self._root.preorder_traversal()
print('')
elif traveral_type == 'in_order':
print('.......In-order traversal........')
self._root.inorder_traversal()
print('')
elif traveral_type == 'post_order':
print('........Post-order traversal.......')
self._root.postorder_traversal()
print('')
elif traveral_type == 'breadth_first':
print('.......Breadth-First traversal........')
self.breadth_first_traversal()
print('')
elif traveral_type == 'depth_first':
print('.......Depth-First traversal........')
self.depth_first_traveral()
print('')
elif traveral_type == 'depth_first_without_stack':
print('.......Depth-First traversal........')
self.depth_first_traveral_recursion()
print('')
else:
raise AssertionError
else:
print('Empty Tree.')
if __name__ == '__main__':
# traversal and maximum depth
inputs = np.array(['F', 'B', 'G', 'A', 'D', 'I', 'C', 'E', 'H'])
binary_tree_obj = BinaryTree()
binary_tree_obj.construct_binary_tree(inputs=inputs)
binary_tree_obj.traversal(traveral_type='pre_order')
binary_tree_obj.traversal(traveral_type='in_order')
binary_tree_obj.traversal(traveral_type='post_order')
binary_tree_obj.traversal(traveral_type='breadth_first')
binary_tree_obj.traversal(traveral_type='depth_first')
binary_tree_obj.traversal(traveral_type='depth_first_without_stack')
is_symmetric = binary_tree_obj.is_symmetric()
print('is_symmetric', is_symmetric)
max_depth = binary_tree_obj.max_depth()
print('max_depth', max_depth)
# max depth
inputs = np.array([5, 4, 8, 11, 13, 4, 7, 2, 1])
binary_tree_obj = BinaryTree()
binary_tree_obj.construct_binary_tree(inputs=inputs)
max_depth = binary_tree_obj.max_depth()
print('max_depth', max_depth)
# path length
for path_length in [16, 1, 37, 2, 5, 23]:
is_path_length_match = binary_tree_obj.path_sums_recursion(path_sum=path_length)
print('is_path_length_match: {}, {}'.format(path_length, is_path_length_match))
binary_tree_obj.construct_binary_tree_for_symmetry_and_test()
# construct binary tree from inorder and postorder traversal
# inorder_elements = np.array([9, 3, 15, 20, 7])
# postorder_elements = np.array([9, 15, 7, 20, 3])
inorder_elements = np.array([9, 5, 1, 7, 2, 12, 8, 4, 3, 11])
postorder_elements = np.array([9, 1, 2, 12, 7, 5, 3, 11, 4, 8])
binary_tree_obj = BinaryTree()
binary_tree_obj.construct_from_inorder_and_postorder(
inorder_elements=inorder_elements,
postorder_elements=postorder_elements,
)
binary_tree_obj.traversal(traveral_type='in_order')
binary_tree_obj.traversal(traveral_type='post_order')
# construct binary tree from inorder and postorder traversal
inorder_elements = np.array([9, 3, 15, 20, 7])
preorder_elements = np.array([3, 9, 20, 15, 7])
binary_tree_obj = BinaryTree()
binary_tree_obj.construct_from_inorder_and_preorder(
inorder_elements=inorder_elements,
preorder_elements=preorder_elements,
)
binary_tree_obj.traversal(traveral_type='in_order')
binary_tree_obj.traversal(traveral_type='pre_order')
|
import math
class Solution(object):
def isPowerOfTwo(self, n):
"""
:type n: int
:rtype: bool
"""
if n < 0:
return False
if n == 0:
return False
elif n == 1:
return True
n = float(n)
while n != 2.0:
n = n/2
if (n % 1) != 0.0:
return False
return True
|
class Solution(object):
def longestPalindrome(self, s):
"""
:type s: str
:rtype: int
"""
if not s:
return 0
char_count_map = {}
for curr_char in s:
if curr_char not in char_count_map:
char_count_map[curr_char] = 0
char_count_map[curr_char] += 1
palindrome_len = 0
is_odd_count_observed = False
for curr_char in char_count_map:
curr_count = char_count_map[curr_char]
if (curr_count % 2) == 0:
palindrome_len += curr_count
else:
is_odd_count_observed = True
if curr_count >= 3:
palindrome_len += (curr_count-1)
if is_odd_count_observed:
palindrome_len += 1
return palindrome_len
|
import heapq
"""
# Definition for an Interval.
class Interval:
def __init__(self, start=None, end=None):
self.start = start
self.end = end
"""
class Solution(object):
def employeeFreeTime(self, schedule):
"""
:type schedule: [[Interval]]
:rtype: [Interval]
"""
if not schedule:
return []
start_times_heap = []
for curr_emp in schedule:
for curr_interval_obj in curr_emp:
# print(curr_interval_obj.start, curr_interval_obj.end)
start_times_heap.append((curr_interval_obj.start, curr_interval_obj.end))
del curr_interval_obj
del curr_emp
heapq.heapify(start_times_heap)
curr_time = start_times_heap[0][0]
free_intervals = list()
while start_times_heap:
start, end = heapq.heappop(start_times_heap)
print(curr_time, start, end)
if curr_time < start:
curr_free_interval = Interval(start=curr_time, end=start)
free_intervals.append(curr_free_interval)
if end > curr_time:
curr_time = end
return free_intervals
|
class Solution(object):
def fizzBuzz(self, n):
"""
:type n: int
:rtype: List[str]
"""
out = []
for x in range(1, n+1):
s = ''
if (x % 3) == 0:
s += 'Fizz'
if (x % 5) == 0:
s += 'Buzz'
if s:
out.append(s)
else:
out.append(str(x))
return out
|
import math
class Solution(object):
def invalid_sol(self, x):
sqrt_val = math.sqrt(x)
return int(sqrt_val)
def binary_search(self, x):
if x <= 1:
return x
elif 2 <= x <= 3:
return 1
elif 4 <= x <= 8:
return 2
left_val = 2
right_val = x/2
# print(left_val, right_val)
if left_val == right_val:
return left_val
while left_val < right_val:
mid_val = (left_val+right_val)/2
mid_val_sqr = mid_val**2
print(left_val, right_val, mid_val)
if mid_val_sqr > x:
right_val = mid_val-1
else:
if (mid_val+1)**2 <= x:
left_val = mid_val+1
else:
return mid_val
assert left_val == right_val
return left_val
def mySqrt(self, x):
"""
:type x: int
:rtype: int
"""
return self.binary_search(x=x)
|
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def diameterOfBinaryTree(self, root):
if root is None:
return 0
_, max_path_len = self._diameterOfBinaryTree(root=root)
# number of nodes along the path minus one
assert max_path_len >= 1
diameter = max_path_len-1
del max_path_len
return diameter
def _diameterOfBinaryTree(self, root, max_path_len=0):
"""
:type root: TreeNode
:rtype: int
"""
assert root is not None
if root.left is not None:
left_subtree_max, max_path_len = self._diameterOfBinaryTree(root.left, max_path_len=max_path_len)
else:
left_subtree_max = 0
if root.right is not None:
right_subtree_max, max_path_len = self._diameterOfBinaryTree(root.right, max_path_len=max_path_len)
else:
right_subtree_max = 0
max_of_node = 1 + max(left_subtree_max, right_subtree_max)
path_including_curr_node = 1 + left_subtree_max + right_subtree_max
if path_including_curr_node > max_path_len:
max_path_len = path_including_curr_node
return max_of_node, max_path_len
|
import collections
class Solution(object):
def order_chars(self, w1, w2):
len_w1 = len(w1)
len_w2 = len(w2)
n = min(len_w1, len_w2)
for j in range(n):
if w1[j] == w2[j]:
continue
else:
return [w1[j], w2[j]]
return None
def topological_sort(self, node, node_children_map, chars_stack, visited, under_exploration):
assert node not in visited
visited.add(node)
under_exploration.add(node)
for curr_child in node_children_map[node]:
if curr_child not in visited:
is_cycle = self.topological_sort(
node=curr_child, node_children_map=node_children_map,
chars_stack=chars_stack, visited=visited,
under_exploration=under_exploration,
)
if is_cycle:
return True
else:
if curr_child in under_exploration:
return True
chars_stack.append(node)
under_exploration.remove(node)
return False
def alienOrder(self, words):
"""
:type words: List[str]
:rtype: str
"""
words = [x for x in words if x.strip()]
if not words:
return ""
nodes = set()
for w in words:
for c in w:
nodes.add(c)
nodes = list(nodes)
node_children_map = collections.defaultdict(set)
n = len(words)
for i in xrange(n-1):
w1 = words[i]
w2 = words[i+1]
edge = self.order_chars(w1=w1, w2=w2)
if edge is None:
continue
node_children_map[edge[0]].add(edge[1])
chars_stack = list()
visited = set()
under_exploration = set()
for curr_node in nodes:
if curr_node not in visited:
is_cycle = self.topological_sort(curr_node, node_children_map, chars_stack, visited, under_exploration)
if is_cycle:
return ""
lexical_order = ''
while chars_stack:
lexical_order += chars_stack.pop()
return lexical_order
|
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def path_from_leaf_node(self, leaf_node):
path = []
curr_node = leaf_node
while curr_node is not None:
path.append(curr_node)
curr_node = curr_node.parent
path.reverse()
return path
def dfs_search_recursive(self, root_node, end_node):
end_node_found = self._dfs_traversal(
root_node=root_node, end_node=end_node,
)
path = self.path_from_leaf_node(
leaf_node=end_node_found,
)
return path
def _dfs_traversal(self, root_node, end_node):
# only one traversal path possible
assert root_node is not None
assert end_node is not None
if not hasattr(root_node, 'parent'):
root_node.parent = None
if root_node == end_node:
return root_node
else:
for curr_child in [root_node.left, root_node.right]:
if curr_child is not None:
curr_child.parent = root_node
node_searched = self._dfs_traversal(root_node=curr_child, end_node=end_node)
if node_searched is not None:
return node_searched
return None
def lowestCommonAncestor(self, root, p, q):
p_traversal = self.dfs_search_recursive(root_node=root, end_node=p)
if p_traversal is None:
return None
q_traversal = self.dfs_search_recursive(root_node=root, end_node=q)
if q_traversal is None:
return None
min_traversal_len = min(len(p_traversal), len(q_traversal))
common_ancestor = root
for curr_idx in range(min_traversal_len):
if p_traversal[curr_idx] == q_traversal[curr_idx]:
common_ancestor = p_traversal[curr_idx]
else:
break
assert common_ancestor is not None
return common_ancestor
|
import numpy as np
class Pixel:
def __init__(self, color, sr, sc):
self.color = color
self.sr = sr
self.sc = sc
class Solution(object):
def floodFill(self, image, sr, sc, newColor):
"""
:type image: List[List[int]]
:type sr: int
:type sc: int
:type newColor: int
:rtype: List[List[int]]
"""
num_rows = len(image)
num_cols = len(image[0])
queue = []
visited = set()
old_color = image[sr][sc]
pixel = Pixel(color=old_color, sr=sr, sc=sc)
queue.append(pixel)
visited.add((sr, sc))
del pixel
while queue:
pixel = queue.pop(0)
# change the color
image[pixel.sr][pixel.sc] = newColor
neighbor_pixel_choices = [
(pixel.sr-1, pixel.sc), (pixel.sr+1, pixel.sc),
(pixel.sr, pixel.sc-1), (pixel.sr, pixel.sc+1),
]
for curr_neighbor_pixel in neighbor_pixel_choices:
row_idx, col_idx = curr_neighbor_pixel
print(curr_neighbor_pixel)
# valid neighbor
if (0 <= row_idx < num_rows) and (0 <= col_idx < num_cols):
curr_color = image[row_idx][col_idx]
print(curr_color)
# selecting neighbors with same color as the starting pixel
if curr_color != old_color:
continue
if curr_neighbor_pixel in visited:
continue
visited.add(curr_neighbor_pixel)
curr_neighbor_pixel_obj = Pixel(
color=curr_color,
sr=row_idx,
sc=col_idx,
)
queue.append(curr_neighbor_pixel_obj)
del curr_neighbor_pixel_obj
return image
|
class Solution(object):
def merge(self, nums1, m, nums2, n):
"""
:type nums1: List[int]
:type m: int
:type nums2: List[int]
:type n: int
:rtype: None Do not return anything, modify nums1 in-place instead.
"""
num1_right_ptr = m+n-1
nums1_left_ptr = m-1
nums2_right_ptr = n-1
while nums2_right_ptr >= 0:
curr_val_for_store = nums2[nums2_right_ptr]
if (nums1_left_ptr < 0) or (curr_val_for_store > nums1[nums1_left_ptr]):
nums1[num1_right_ptr] = curr_val_for_store
nums2_right_ptr -= 1
num1_right_ptr -= 1
else:
nums1[num1_right_ptr] = nums1[nums1_left_ptr]
nums1_left_ptr -= 1
num1_right_ptr -= 1
|
import time
import queue
import threading
def cpu_work(i):
work_rate = pow(2, 26)
print("{} : Work {} rate is {}".format(threading.current_thread(), i, work_rate))
for z in range(work_rate):
i += 1
return i
def cpu_worker(external_queue):
while True:
item = external_queue.get()
if item is None:
break
cpu_work(item)
external_queue.task_done()
def perform_work_by_threads_(number_of_threads, works_as_list):
print("Threads are ", number_of_threads)
q = queue.Queue()
for work in works_as_list:
q.put(work)
threads = []
for x in range(number_of_threads):
t = threading.Thread(target=cpu_worker, args=(q,))
threads.append(t)
t.start()
q.join()
for x in range(number_of_threads):
q.put(None)
for t in threads:
t.join()
if __name__ == "__main__":
works = [0, 1, 2, 3, 4, 5]
# print("Main thread working...")
# t_zero = time.time()
# for w in works:
# t0 = time.time()
# ret = cpu_work(w)
# # print("Work {} with return {} spent {} secs.".format(w, ret, time.time() - t0))
# print("Total Work spent {} secs.".format(time.time() - t_zero))
threads_n = [4, 5, 6]
for tn in threads_n:
t0 = time.time()
perform_work_by_threads_(tn, works)
print("Total Work with threads spent {} secs.".format(time.time() - t0))
print("Bye Bye!!!")
|
class DegreeDistribution:
def __init__(self, network):
"""
Computes the degree distribution of a network. Make sure that both degree 0 and the maximum degree
are included!
"""
# TODO: initialise a list to store the observations for each degree (including degree 0!)
self.maxDegree = network.max_degree()
self.Size = network
self.histogram = [0] * (self.maxDegree + 1)
# TODO: fill the histogram with the degree distribution
for k, node in network.nodes.items():
deg = node.degree()
self.histogram[deg] = self.histogram[deg] + 1
# TODO: normalize with amount of nodes in network
def normalisation(self):
self.normalisation = []
max_Degree = 0
while max_Degree <= self.maxDegree:
self.normalisation.append((float(self.histogram[max_Degree])/self.Size.size()))
max_Degree += 1
return self.normalisation
|
#Write a program that prints the numbers from 1 to 100
#But for multiples of three it will print “Fizz” instead of the number.
#For the multiples of five it will print “Buzz” and For multiples
#of both three and five it will print “FizzBuzz” .
def print_number(n):
''' print 'Fizz'for multiples of three,print'Buzz'for multiples
of five and print 'FizzBuzz' for multiples of three and five'''
for i in range(1,n):
if i%3==0 and i%5==0:
print("FizzBuzz")
elif i%3==0:
print("Fizz")
elif i%5==0 :
print("Buzz")
else:
print(i)
print_number(101)
|
from graph.Graph import GraphBase
from graph.base import Edge, Node
from list.DoubleLinkedList import ListaDoppiamenteCollegata as List
class GraphAdjacencyList(GraphBase):
"""
A graph, implemented as an adjacency list.
Each node u has a list containing its adjacent nodes, that is nodes v such
that exists an edges (u,v).
---
Memory Complexity: O(|V|+|E|)
"""
def __init__(self):
"""
Constructor.
"""
super().__init__()
self.adj = {} # adjacency lists {nodeID:listOfAdjacentNodes}
def numEdges(self):
"""
Return the number of edges.
:return: the number of edges.
"""
return sum(len(adj_list) for adj_list in self.adj.values())
def addNode(self, elem):
"""
Add a new node with the specified value.
:param elem: the node value.
:return: the create node.
"""
newnode = super().addNode(elem) # create a new node with the correct ID
self.nodes[newnode.id] = newnode # add the new node to the dictionary
self.adj[newnode.id] = List() # create the adjacency list for the new node
return newnode
def deleteNode(self, nodeId):
"""
Remove the specified node.
:param nodeId: the node ID (integer).
:return: void.
"""
# look for the node
found = False
for node in self.nodes.items():
if nodeId == node[0]:
found = True
break
# if node does not exist, return
if not found: return
# remove the node from the set of nodes, that is to remove the node
# from the dictionary nodes
del self.nodes[nodeId]
# remove all edges starting from the node, that is to remove the
# adjacency list for the node
del self.adj[nodeId]
# remove all edges pointing to the node, that is to remove the node
# from all the adjacency lists
for adj in self.adj.values():
curr = adj.getFirstRecord()
while curr is not None:
if curr.elem == nodeId:
adj.deleteRecord(curr)
curr = curr.next
def getNode(self, id):
"""
Return the node, if exists.
:param id: the node ID (integer).
:return: the node, if exists; None, otherwise.
"""
return None if id not in self.nodes else self.nodes[id]
def getNodes(self):
"""
Return the list of nodes.
:return: the list of nodes.
"""
return list(self.nodes.values())
def insertEdge(self, tail, head, weight=None):
"""
Add a new edge.
:param tail: the tail node ID (integer).
:param head: the head node ID (integer).
:param weight: the (optional) edge weight (floating-point).
:return: the created edge, if created; None, otherwise.
"""
# if tail and head exist, add the entry into the adjacency list
if tail in self.nodes and head in self.nodes: #TODO overwrite if edge already exists
self.adj[tail].addAsLast(head)
def deleteEdge(self, tail, head):
"""
Remove the specified edge.
:param tail: the tail node ID (integer).
:param head: the head node ID (integer).
:return: void.
"""
# if tail and head exist, delete the edge
if tail in self.nodes and head in self.nodes:
curr = self.adj[tail].getFirstRecord()
while curr is not None:
if curr.elem == head:
self.adj[tail].deleteRecord(curr)
break
curr = curr.next
def getEdge(self, tail, head):
"""
Return the node, if exists.
:param tail: the tail node ID (integer).
:param head: the head node ID (integer).
:return: the edge, if exists; None, otherwise.
"""
if tail in self.nodes and head in self.nodes:
curr = self.adj[tail].getFirstRecord()
while curr is not None:
if curr.elem == head:
return Edge(tail, head, None)
curr = curr.next
return None
def getEdges(self):
"""
Return the list of edges.
:return: the list of edges.
"""
edges = []
for adj_item in self.adj.items():
curr = adj_item[1].getFirstRecord()
while curr is not None:
edges.append(Edge(adj_item[0], curr.elem, None))
curr = curr.next
return edges
def isAdj(self, tail, head):
"""
Checks if two nodes ar adjacent.
:param tail: the tail node ID (integer).
:param head: the head node ID (integer).
:return: True, if the two nodes are adjacent; False, otherwise.
"""
# if tail and head exist, look for the entry in the adjacency list
if super().isAdj(tail, head) == True:
curr = self.adj[tail].getFirstRecord()
while curr is not None:
nodeId = curr.elem
if nodeId == head:
return True
curr = curr.next
# else, return False
return False
def getAdj(self, nodeId):
"""
Return all nodes adjacent to the one specified.
:param nodeId: the node id.
:return: the list of nodes adjacent to the one specified.
"""
result = []
curr = self.adj[nodeId].getFirstRecord()
while curr is not None:
result.append(curr.elem)
curr = curr.next
return result
def deg(self, nodeId):
"""
Return the node degree.
:param nodeId: the node id.
:return: the node degree.
"""
if nodeId not in self.nodes:
return 0
else:
return len(self.adj[nodeId])
def print(self):
"""
Print the graph.
:return: void.
"""
# if the adjacency list is empty ...
if self.isEmpty():
print ("Adjacency List: EMPTY")
return
# else ...
print("Adjacency Lists:")
for adj_item in self.adj.items():
print("{}:{}".format(adj_item[0], adj_item[1]))
if __name__ == "__main__":
graph = GraphAdjacencyList()
graph.print()
# add nodes
nodes = []
for i in range(3):
node = graph.addNode(i)
print("Node inserted:", node)
nodes.append(node)
graph.print()
# connect all nodes
for node_src in nodes:
for node_dst in nodes:
if node_src != node_dst:
print("---")
print("Adjacent nodes {},{}: {}"
.format(node_src.id, node_dst.id,
graph.isAdj(node_src.id, node_dst.id)))
graph.insertEdge(node_src.id, node_dst.id,
node_src.id + node_dst.id)
print("Edge inserted: from {} to {}".format(node_src.id,
node_dst.id))
print("Adjacent nodes {},{}: {}"
.format(node_src.id, node_dst.id,
graph.isAdj(node_src.id, node_dst.id)))
graph.print()
print("---")
# num nodes/edges
print("Num Nodes:", graph.numNodes())
print("Num Edges:", graph.numEdges())
# degree
for node in nodes:
print("Degree node {}: {}".format(node.id, graph.deg(node.id)))
# get specific node
for node in nodes:
print("Node {}: {}".format(node.id, graph.getNode(node.id)))
# get all nodes
print("Nodes:", [str(i) for i in graph.getNodes()])
# get specific edge
for node_src in nodes:
for node_dst in nodes:
print("Edge {},{}: {}".format(node_src.id, node_dst.id, graph.getEdge(node_src.id, node_dst.id)))
# get all edges
print("Edges:", [str(i) for i in graph.getEdges()])
# execute a generic search
for node in nodes:
tree = graph.genericSearch(node.id)
s = tree.BFS()
print("Generic Search with root {}: {}".format(node.id,
[str(item) for item in s]))
# execute a BFS
for node in nodes:
s = graph.bfs(node.id)
print("BFS with root {}: {}".format(node.id,
[str(item) for item in s]))
# execute a DFS
for node in nodes:
s = graph.dfs(node.id)
print("DFS with root {}: {}".format(node.id,
[str(item) for item in s]))
# remove all nodes
for node in nodes:
graph.deleteNode(node.id)
print("Node removed:", node.id)
graph.print() |
class Node:
"""
The graph basic element: node.
"""
def __init__(self, id, value):
"""
Constructor.
:param id: node ID (integer).
:param value: node value.
"""
self.id = id
self.value = value
def __eq__(self, other):
"""
Equality operator.
:param other: the other node.
:return: True if ids are equal; False, otherwise.
"""
return self.id == other.id
def __str__(self):
"""
Returns the string representation of the node.
:return: the string representation of the node.
"""
return "[{}:{}]".format(self.id, self.value)
class Edge:
"""
The graph basic element: (weighted) edge.
"""
def __init__(self, tail, head, weight=None):
"""
Constructor.
:param tail: the tail node ID (integer).
:param head: the head node ID (integer).
:param weight: the (optional) edge weight (floating-point).
"""
self.head = head
self.tail = tail
self.weight = weight
def __cmp__(self, other):
"""
Compare two edges with respect to their weight.
:param other: the other edge to compare.
:return: 1 if the weight is greater than the other;
-1 if the weight is less than the other; 0, otherwise.
"""
if self.weight > other.weight:
return 1
elif self.weight < other.weight:
return -1
else:
return 0
def __lt__(self, other):
"""
Less than operator.
:param other: the other edge.
:return: True, if the weight is less than the others; False, otherwise.
"""
return self.weight < other.weight
def __gt__(self, other):
"""
Greater than operator.
:param other: the other edge.
:return: True, if the weight is greater than the others; False, otherwise.
"""
return self.weight > other.weight
def __eq__(self, other):
"""
Equality operator.
:param other: the other edge.
:return: True if weights are equal; False, otherwise.
"""
return self.weight == other.weight
def __str__(self):
"""
Returns the string representation of the edge.
:return: the string representation of the edge.
"""
return "({},{},{})".format(self.tail, self.head, self.weight)
def getTail(self):
return "{}".format(self.tail)
def getHead(self):
return "{}".format(self.head)
if __name__ == "__main__":
node_src = Node(0, "SRC")
print('Node created:', node_src)
node_dst = Node(1, "DST")
print('Node created:', node_dst)
edge = Edge(node_src.id, node_dst.id, 1.5)
print('Edge created:', edge)
print(edge.head)
|
import numpy as np
def h(x, i):
return x[i + 1] - x[i] if i + 1 < len(x) else x[i] - x[i - 1]
def m(x, i):
return h(x, i - 1) / (h(x, i + 1) + h(x, i))
def l(x, i):
return h(x, i) / (h(x, i + 1) + h(x, i))
# returns list of answer for matrix
def calc_matrix(n, x, y, diff2, a):
m_a = np.zeros((n + 1) ** 2).reshape(n + 1, n + 1)
# m_a[0][0] = 2
m_a[0][0] = (y[1] - y[0]) / h(x, 0)
m_a[0][1] = 1
for i in range(1, n):
m_a[i][i - 1] = m(x, i)
m_a[i][i] = 2
m_a[i][i + 1] = l(x, i)
m_a[n][n - 1] = 1
m_a[n][n] = (y[n] - y[n - 1]) / h(x, 0)
# m_a[n][n] = 2
m_b = np.zeros(n + 1)
m_b[0] = 3 * (y[1] - y[0]) / h(x, 1) - h(x, 1) * diff2(a, x[0]) / 2
for i in range(1, n):
m_b[i] = 3 * (m(x, i) * (y[i + 1] - y[i]) / h(x, i + 1) + l(x, i) * (y[i] - y[i - 1]) / h(x, i))
m_b[n] = 3 * ((y[n] - y[n - 1]) / h(x, n)) + h(x, n) * diff2(a, x[n]) / 2
m_res = np.linalg.solve(m_a, m_b)
return m_res
|
# Реализовать функцию my_func(), которая принимает три позиционных аргумента,
# и возвращает сумму наибольших двух аргументов.
def my_func(a , b, c):
if a <= b or a <= c:
return b + c
elif b <= a or b <= c:
return a + c
else:
return a + b
print(f'Cумма двух наибольших чисел = {my_func(int(input("Введите значение a ")), int(input("Введите значение b ")), int(input("Введите значение c ")))}')
|
# Для списка реализовать обмен значений соседних элементов,
# т.е. Значениями обмениваются элементы с индексами 0 и 1, 2 и 3 и т.д.
# При нечетном количестве элементов последний сохранить на своем месте. Для заполнения списка элементов необходимо
# использовать функцию input().
n = int(input('Введите колличесто элементов списака:' )) # считываем количество элемент в списке
my_list = []
i = 0
while i <n:
my_list.append(input('Введите значение списка:'))
i += 1
print(f'Вы создали список{my_list}')
if len(my_list) % 2 == 0: # считаем длину списка определяем четный или нет
i = 0
while i < len(my_list): #работаем с индексом елементов списка
index_elem = my_list[i]
my_list[i] = my_list[i+1]
my_list[i+1] = index_elem
i += 2
else:
i = 0
while i < len(my_list) - 1:
index_elem = my_list[i]
my_list[i] = my_list[i + 1]
my_list[i + 1] = index_elem
i += 2
print(f'Немного посортируем список {my_list}')
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.