psf/black code formatting (#1421)

* added sol3.py for problem_20

* added sol4.py for problem_06

* ran `black .` on `\Python`
This commit is contained in:
Ankur Chattopadhyay 2019-10-22 22:43:48 +05:30 committed by Christian Clauss
parent 11e2207182
commit 7592cba417
28 changed files with 413 additions and 252 deletions

View File

@ -1,5 +1,5 @@
def encrypt(input_string: str, key: int) -> str: def encrypt(input_string: str, key: int) -> str:
result = '' result = ""
for x in input_string: for x in input_string:
if not x.isalpha(): if not x.isalpha():
result += x result += x
@ -11,7 +11,7 @@ def encrypt(input_string: str, key: int) -> str:
def decrypt(input_string: str, key: int) -> str: def decrypt(input_string: str, key: int) -> str:
result = '' result = ""
for x in input_string: for x in input_string:
if not x.isalpha(): if not x.isalpha():
result += x result += x
@ -24,15 +24,15 @@ def decrypt(input_string: str, key: int) -> str:
def brute_force(input_string: str) -> None: def brute_force(input_string: str) -> None:
key = 1 key = 1
result = '' result = ""
while key <= 94: while key <= 94:
for x in input_string: for x in input_string:
indx = (ord(x) - key) % 256 indx = (ord(x) - key) % 256
if indx < 32: if indx < 32:
indx = indx + 95 indx = indx + 95
result = result + chr(indx) result = result + chr(indx)
print(f'Key: {key}\t| Message: {result}') print(f"Key: {key}\t| Message: {result}")
result = '' result = ""
key += 1 key += 1
return None return None
@ -40,7 +40,7 @@ def brute_force(input_string: str) -> None:
def main(): def main():
while True: while True:
print(f'{"-" * 10}\n Menu\n{"-", * 10}') print(f'{"-" * 10}\n Menu\n{"-", * 10}')
print(*["1.Encrpyt", "2.Decrypt", "3.BruteForce", "4.Quit"], sep='\n') print(*["1.Encrpyt", "2.Decrypt", "3.BruteForce", "4.Quit"], sep="\n")
choice = input("What would you like to do?: ") choice = input("What would you like to do?: ")
if choice not in ["1", "2", "3", "4"]: if choice not in ["1", "2", "3", "4"]:
print("Invalid choice, please enter a valid choice") print("Invalid choice, please enter a valid choice")

View File

@ -7,6 +7,7 @@ class Node(object):
Treap's node Treap's node
Treap is a binary tree by value and heap by priority Treap is a binary tree by value and heap by priority
""" """
def __init__(self, value: int = None): def __init__(self, value: int = None):
self.value = value self.value = value
self.prior = random() self.prior = random()
@ -20,10 +21,7 @@ class Node(object):
return "'%s: %.5s'" % (self.value, self.prior) return "'%s: %.5s'" % (self.value, self.prior)
else: else:
return pformat( return pformat(
{ {"%s: %.5s" % (self.value, self.prior): (self.left, self.right)},
"%s: %.5s"
% (self.value, self.prior): (self.left, self.right)
},
indent=1, indent=1,
) )
@ -33,6 +31,7 @@ class Node(object):
right = str(self.right or "") right = str(self.right or "")
return value + left + right return value + left + right
def split(root: Node, value: int) -> Tuple[Node, Node]: def split(root: Node, value: int) -> Tuple[Node, Node]:
""" """
We split current tree into 2 trees with value: We split current tree into 2 trees with value:
@ -61,6 +60,7 @@ def split(root: Node, value: int) -> Tuple[Node, Node]:
root.right, right = split(root.right, value) root.right, right = split(root.right, value)
return (root, right) return (root, right)
def merge(left: Node, right: Node) -> Node: def merge(left: Node, right: Node) -> Node:
""" """
We merge 2 trees into one. We merge 2 trees into one.
@ -82,6 +82,7 @@ def merge(left: Node, right: Node) -> Node:
right.left = merge(left, right.left) right.left = merge(left, right.left)
return right return right
def insert(root: Node, value: int) -> Node: def insert(root: Node, value: int) -> Node:
""" """
Insert element Insert element
@ -94,6 +95,7 @@ def insert(root: Node, value: int) -> Node:
left, right = split(root, value) left, right = split(root, value)
return merge(merge(left, node), right) return merge(merge(left, node), right)
def erase(root: Node, value: int) -> Node: def erase(root: Node, value: int) -> Node:
""" """
Erase element Erase element
@ -102,10 +104,11 @@ def erase(root: Node, value: int) -> Node:
Split all nodes with values greater into right. Split all nodes with values greater into right.
Merge left, right Merge left, right
""" """
left, right = split(root, value-1) left, right = split(root, value - 1)
_, right = split(right, value) _, right = split(right, value)
return merge(left, right) return merge(left, right)
def inorder(root: Node): def inorder(root: Node):
""" """
Just recursive print of a tree Just recursive print of a tree
@ -154,13 +157,16 @@ def interactTreap(root, args):
return root return root
def main(): def main():
"""After each command, program prints treap""" """After each command, program prints treap"""
root = None root = None
print("enter numbers to creat a tree, + value to add value into treap, - value to erase all nodes with value. 'q' to quit. ") print(
"enter numbers to creat a tree, + value to add value into treap, - value to erase all nodes with value. 'q' to quit. "
)
args = input() args = input()
while args != 'q': while args != "q":
root = interactTreap(root, args) root = interactTreap(root, args)
print(root) print(root)
args = input() args = input()
@ -168,7 +174,9 @@ def main():
print("good by!") print("good by!")
pass pass
if __name__ == "__main__": if __name__ == "__main__":
import doctest import doctest
doctest.testmod() doctest.testmod()
main() main()

View File

@ -1,45 +1,48 @@
def merge(a,b,m,e): def merge(a, b, m, e):
l=a[b:m+1] l = a[b : m + 1]
r=a[m+1:e+1] r = a[m + 1 : e + 1]
k=b k = b
i=0 i = 0
j=0 j = 0
while i<len(l) and j<len(r): while i < len(l) and j < len(r):
#change sign for Descending order # change sign for Descending order
if l[i]<r[j]: if l[i] < r[j]:
a[k]=l[i] a[k] = l[i]
i+=1 i += 1
else: else:
a[k]=r[j] a[k] = r[j]
j+=1 j += 1
k+=1 k += 1
while i<len(l): while i < len(l):
a[k]=l[i] a[k] = l[i]
i+=1 i += 1
k+=1 k += 1
while j<len(r): while j < len(r):
a[k]=r[j] a[k] = r[j]
j+=1 j += 1
k+=1 k += 1
return a return a
def mergesort(a,b,e):
def mergesort(a, b, e):
""" """
>>> mergesort([3,2,1],0,2) >>> mergesort([3,2,1],0,2)
[1, 2, 3] [1, 2, 3]
>>> mergesort([3,2,1,0,1,2,3,5,4],0,8) >>> mergesort([3,2,1,0,1,2,3,5,4],0,8)
[0, 1, 1, 2, 2, 3, 3, 4, 5] [0, 1, 1, 2, 2, 3, 3, 4, 5]
""" """
if b<e: if b < e:
m = (b+e)//2 m = (b + e) // 2
#print("ms1",a,b,m) # print("ms1",a,b,m)
mergesort(a,b,m) mergesort(a, b, m)
#print("ms2",a,m+1,e) # print("ms2",a,m+1,e)
mergesort(a,m+1,e) mergesort(a, m + 1, e)
#print("m",a,b,m,e) # print("m",a,b,m,e)
merge(a,b,m,e) merge(a, b, m, e)
return a return a
if __name__ == "__main__": if __name__ == "__main__":
import doctest import doctest
doctest.testmod() doctest.testmod()

View File

@ -11,6 +11,7 @@ a=daBcd and b="ABC"
daBcd -> capitalize a and c(dABCd) -> remove d (ABC) daBcd -> capitalize a and c(dABCd) -> remove d (ABC)
""" """
def abbr(a, b): def abbr(a, b):
""" """
>>> abbr("daBcd", "ABC") >>> abbr("daBcd", "ABC")

View File

@ -20,6 +20,7 @@ def fracKnapsack(vl, wt, W, n):
else sum(vl[:k]) else sum(vl[:k])
) )
if __name__ == "__main__": if __name__ == "__main__":
import doctest import doctest

View File

@ -76,7 +76,7 @@ if __name__ == "__main__":
expected_subseq = "GTAB" expected_subseq = "GTAB"
ln, subseq = longest_common_subsequence(a, b) ln, subseq = longest_common_subsequence(a, b)
## print("len =", ln, ", sub-sequence =", subseq) ## print("len =", ln, ", sub-sequence =", subseq)
import doctest import doctest
doctest.testmod() doctest.testmod()

View File

@ -29,6 +29,7 @@ def isSumSubset(arr, arrLen, requiredSum):
# print(subset[i]) # print(subset[i])
print(subset[arrLen][requiredSum]) print(subset[arrLen][requiredSum])
if __name__ == "__main__": if __name__ == "__main__":
import doctest import doctest

View File

@ -8,37 +8,39 @@ Python:
""" """
# Create universe of discourse in python using linspace () # Create universe of discourse in python using linspace ()
import numpy as np import numpy as np
X = np.linspace(start=0, stop=75, num=75, endpoint=True, retstep=False) X = np.linspace(start=0, stop=75, num=75, endpoint=True, retstep=False)
# Create two fuzzy sets by defining any membership function (trapmf(), gbellmf(),gaussmf(), etc). # Create two fuzzy sets by defining any membership function (trapmf(), gbellmf(),gaussmf(), etc).
import skfuzzy as fuzz import skfuzzy as fuzz
abc1=[0,25,50]
abc2=[25,50,75] abc1 = [0, 25, 50]
young = fuzz.membership.trimf(X,abc1) abc2 = [25, 50, 75]
middle_aged = fuzz.membership.trimf(X,abc2) young = fuzz.membership.trimf(X, abc1)
middle_aged = fuzz.membership.trimf(X, abc2)
# Compute the different operations using inbuilt functions. # Compute the different operations using inbuilt functions.
one = np.ones(75) one = np.ones(75)
zero = np.zeros((75,)) zero = np.zeros((75,))
#1. Union = max(µA(x), µB(x)) # 1. Union = max(µA(x), µB(x))
union = fuzz.fuzzy_or(X, young, X, middle_aged)[1] union = fuzz.fuzzy_or(X, young, X, middle_aged)[1]
#2. Intersection = min(µA(x), µB(x)) # 2. Intersection = min(µA(x), µB(x))
intersection = fuzz.fuzzy_and(X, young, X, middle_aged)[1] intersection = fuzz.fuzzy_and(X, young, X, middle_aged)[1]
#3. Complement (A) = (1- min(µA(x)) # 3. Complement (A) = (1- min(µA(x))
complement_a = fuzz.fuzzy_not(young) complement_a = fuzz.fuzzy_not(young)
#4. Difference (A/B) = min(µA(x),(1- µB(x))) # 4. Difference (A/B) = min(µA(x),(1- µB(x)))
difference = fuzz.fuzzy_and(X, young, X, fuzz.fuzzy_not(middle_aged)[1])[1] difference = fuzz.fuzzy_and(X, young, X, fuzz.fuzzy_not(middle_aged)[1])[1]
#5. Algebraic Sum = [µA(x) + µB(x) (µA(x) * µB(x))] # 5. Algebraic Sum = [µA(x) + µB(x) (µA(x) * µB(x))]
alg_sum = young + middle_aged - (young*middle_aged) alg_sum = young + middle_aged - (young * middle_aged)
#6. Algebraic Product = (µA(x) * µB(x)) # 6. Algebraic Product = (µA(x) * µB(x))
alg_product = young*middle_aged alg_product = young * middle_aged
#7. Bounded Sum = min[1,(µA(x), µB(x))] # 7. Bounded Sum = min[1,(µA(x), µB(x))]
bdd_sum = fuzz.fuzzy_and(X, one, X, young+middle_aged)[1] bdd_sum = fuzz.fuzzy_and(X, one, X, young + middle_aged)[1]
#8. Bounded difference = min[0,(µA(x), µB(x))] # 8. Bounded difference = min[0,(µA(x), µB(x))]
bdd_difference = fuzz.fuzzy_or(X, zero, X, young-middle_aged)[1] bdd_difference = fuzz.fuzzy_or(X, zero, X, young - middle_aged)[1]
#max-min composition # max-min composition
#max-product composition # max-product composition
# Plot each set A, set B and each operation result using plot() and subplot(). # Plot each set A, set B and each operation result using plot() and subplot().
@ -46,55 +48,55 @@ import matplotlib.pyplot as plt
plt.figure() plt.figure()
plt.subplot(4,3,1) plt.subplot(4, 3, 1)
plt.plot(X,young) plt.plot(X, young)
plt.title("Young") plt.title("Young")
plt.grid(True) plt.grid(True)
plt.subplot(4,3,2) plt.subplot(4, 3, 2)
plt.plot(X,middle_aged) plt.plot(X, middle_aged)
plt.title("Middle aged") plt.title("Middle aged")
plt.grid(True) plt.grid(True)
plt.subplot(4,3,3) plt.subplot(4, 3, 3)
plt.plot(X,union) plt.plot(X, union)
plt.title("union") plt.title("union")
plt.grid(True) plt.grid(True)
plt.subplot(4,3,4) plt.subplot(4, 3, 4)
plt.plot(X,intersection) plt.plot(X, intersection)
plt.title("intersection") plt.title("intersection")
plt.grid(True) plt.grid(True)
plt.subplot(4,3,5) plt.subplot(4, 3, 5)
plt.plot(X,complement_a) plt.plot(X, complement_a)
plt.title("complement_a") plt.title("complement_a")
plt.grid(True) plt.grid(True)
plt.subplot(4,3,6) plt.subplot(4, 3, 6)
plt.plot(X,difference) plt.plot(X, difference)
plt.title("difference a/b") plt.title("difference a/b")
plt.grid(True) plt.grid(True)
plt.subplot(4,3,7) plt.subplot(4, 3, 7)
plt.plot(X,alg_sum) plt.plot(X, alg_sum)
plt.title("alg_sum") plt.title("alg_sum")
plt.grid(True) plt.grid(True)
plt.subplot(4,3,8) plt.subplot(4, 3, 8)
plt.plot(X,alg_product) plt.plot(X, alg_product)
plt.title("alg_product") plt.title("alg_product")
plt.grid(True) plt.grid(True)
plt.subplot(4,3,9) plt.subplot(4, 3, 9)
plt.plot(X,bdd_sum) plt.plot(X, bdd_sum)
plt.title("bdd_sum") plt.title("bdd_sum")
plt.grid(True) plt.grid(True)
plt.subplot(4,3,10) plt.subplot(4, 3, 10)
plt.plot(X,bdd_difference) plt.plot(X, bdd_difference)
plt.title("bdd_difference") plt.title("bdd_difference")
plt.grid(True) plt.grid(True)
plt.subplots_adjust(hspace = 0.5) plt.subplots_adjust(hspace=0.5)
plt.show() plt.show()

View File

@ -1,5 +1,6 @@
INF = float("inf") INF = float("inf")
class Dinic: class Dinic:
def __init__(self, n): def __init__(self, n):
self.lvl = [0] * n self.lvl = [0] * n
@ -7,16 +8,17 @@ class Dinic:
self.q = [0] * n self.q = [0] * n
self.adj = [[] for _ in range(n)] self.adj = [[] for _ in range(n)]
''' """
Here we will add our edges containing with the following parameters: Here we will add our edges containing with the following parameters:
vertex closest to source, vertex closest to sink and flow capacity vertex closest to source, vertex closest to sink and flow capacity
through that edge ... through that edge ...
''' """
def add_edge(self, a, b, c, rcap=0): def add_edge(self, a, b, c, rcap=0):
self.adj[a].append([b, len(self.adj[b]), c, 0]) self.adj[a].append([b, len(self.adj[b]), c, 0])
self.adj[b].append([a, len(self.adj[a]) - 1, rcap, 0]) self.adj[b].append([a, len(self.adj[a]) - 1, rcap, 0])
#This is a sample depth first search to be used at max_flow # This is a sample depth first search to be used at max_flow
def depth_first_search(self, vertex, sink, flow): def depth_first_search(self, vertex, sink, flow):
if vertex == sink or not flow: if vertex == sink or not flow:
return flow return flow
@ -32,7 +34,7 @@ class Dinic:
self.ptr[vertex] = self.ptr[vertex] + 1 self.ptr[vertex] = self.ptr[vertex] + 1
return 0 return 0
#Here we calculate the flow that reaches the sink # Here we calculate the flow that reaches the sink
def max_flow(self, source, sink): def max_flow(self, source, sink):
flow, self.q[0] = 0, source flow, self.q[0] = 0, source
for l in range(31): # l = 30 maybe faster for random data for l in range(31): # l = 30 maybe faster for random data
@ -58,36 +60,35 @@ class Dinic:
return flow return flow
#Example to use
''' # Example to use
"""
Will be a bipartite graph, than it has the vertices near the source(4) Will be a bipartite graph, than it has the vertices near the source(4)
and the vertices near the sink(4) and the vertices near the sink(4)
''' """
#Here we make a graphs with 10 vertex(source and sink includes) # Here we make a graphs with 10 vertex(source and sink includes)
graph = Dinic(10) graph = Dinic(10)
source = 0 source = 0
sink = 9 sink = 9
''' """
Now we add the vertices next to the font in the font with 1 capacity in this edge Now we add the vertices next to the font in the font with 1 capacity in this edge
(source -> source vertices) (source -> source vertices)
''' """
for vertex in range(1, 5): for vertex in range(1, 5):
graph.add_edge(source, vertex, 1) graph.add_edge(source, vertex, 1)
''' """
We will do the same thing for the vertices near the sink, but from vertex to sink We will do the same thing for the vertices near the sink, but from vertex to sink
(sink vertices -> sink) (sink vertices -> sink)
''' """
for vertex in range(5, 9): for vertex in range(5, 9):
graph.add_edge(vertex, sink, 1) graph.add_edge(vertex, sink, 1)
''' """
Finally we add the verices near the sink to the vertices near the source. Finally we add the verices near the sink to the vertices near the source.
(source vertices -> sink vertices) (source vertices -> sink vertices)
''' """
for vertex in range(1, 5): for vertex in range(1, 5):
graph.add_edge(vertex, vertex+4, 1) graph.add_edge(vertex, vertex + 4, 1)
#Now we can know that is the maximum flow(source -> sink) # Now we can know that is the maximum flow(source -> sink)
print(graph.max_flow(source, sink)) print(graph.max_flow(source, sink))

View File

@ -125,6 +125,7 @@ class Decision_Tree:
print("Error: Decision tree not yet trained") print("Error: Decision tree not yet trained")
return None return None
class Test_Decision_Tree: class Test_Decision_Tree:
"""Decision Tres test class """Decision Tres test class
""" """
@ -139,12 +140,9 @@ class Test_Decision_Tree:
""" """
squared_error_sum = np.float(0) squared_error_sum = np.float(0)
for label in labels: for label in labels:
squared_error_sum += ((label-prediction) ** 2) squared_error_sum += (label - prediction) ** 2
return np.float(squared_error_sum/labels.size)
return np.float(squared_error_sum / labels.size)
def main(): def main():

View File

@ -2,19 +2,23 @@ import matplotlib.pyplot as plt
import pandas as pd import pandas as pd
# Importing the dataset # Importing the dataset
dataset = pd.read_csv('https://s3.us-west-2.amazonaws.com/public.gamelab.fun/dataset/position_salaries.csv') dataset = pd.read_csv(
"https://s3.us-west-2.amazonaws.com/public.gamelab.fun/dataset/position_salaries.csv"
)
X = dataset.iloc[:, 1:2].values X = dataset.iloc[:, 1:2].values
y = dataset.iloc[:, 2].values y = dataset.iloc[:, 2].values
# Splitting the dataset into the Training set and Test set # Splitting the dataset into the Training set and Test set
from sklearn.model_selection import train_test_split from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0) X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0)
# Fitting Polynomial Regression to the dataset # Fitting Polynomial Regression to the dataset
from sklearn.preprocessing import PolynomialFeatures from sklearn.preprocessing import PolynomialFeatures
from sklearn.linear_model import LinearRegression from sklearn.linear_model import LinearRegression
poly_reg = PolynomialFeatures(degree=4) poly_reg = PolynomialFeatures(degree=4)
X_poly = poly_reg.fit_transform(X) X_poly = poly_reg.fit_transform(X)
pol_reg = LinearRegression() pol_reg = LinearRegression()
@ -23,15 +27,17 @@ pol_reg.fit(X_poly, y)
# Visualizing the Polymonial Regression results # Visualizing the Polymonial Regression results
def viz_polymonial(): def viz_polymonial():
plt.scatter(X, y, color='red') plt.scatter(X, y, color="red")
plt.plot(X, pol_reg.predict(poly_reg.fit_transform(X)), color='blue') plt.plot(X, pol_reg.predict(poly_reg.fit_transform(X)), color="blue")
plt.title('Truth or Bluff (Linear Regression)') plt.title("Truth or Bluff (Linear Regression)")
plt.xlabel('Position level') plt.xlabel("Position level")
plt.ylabel('Salary') plt.ylabel("Salary")
plt.show() plt.show()
return return
viz_polymonial() viz_polymonial()
# Predicting a new result with Polymonial Regression # Predicting a new result with Polymonial Regression
pol_reg.predict(poly_reg.fit_transform([[5.5]])) pol_reg.predict(poly_reg.fit_transform([[5.5]]))
#output should be 132148.43750003 # output should be 132148.43750003

View File

@ -29,7 +29,118 @@ def test_n31():
""" """
assert n31(4) == ([4, 2, 1], 3) assert n31(4) == ([4, 2, 1], 3)
assert n31(11) == ([11, 34, 17, 52, 26, 13, 40, 20, 10, 5, 16, 8, 4, 2, 1], 15) assert n31(11) == ([11, 34, 17, 52, 26, 13, 40, 20, 10, 5, 16, 8, 4, 2, 1], 15)
assert n31(31) == ([31, 94, 47, 142, 71, 214, 107, 322, 161, 484, 242, 121, 364, 182, 91, 274, 137, 412, 206, 103, 310, 155, 466, 233, 700, 350, 175, 526, 263, 790, 395, 1186, 593, 1780, 890, 445, 1336, 668, 334, 167, 502, 251, 754, 377, 1132, 566, 283, 850, 425, 1276, 638, 319, 958, 479, 1438, 719, 2158, 1079, 3238, 1619, 4858, 2429, 7288, 3644, 1822, 911, 2734, 1367, 4102, 2051, 6154, 3077, 9232, 4616, 2308, 1154, 577, 1732, 866, 433, 1300, 650, 325, 976, 488, 244, 122, 61, 184, 92, 46, 23, 70, 35, 106, 53, 160, 80, 40, 20, 10, 5, 16, 8, 4, 2, 1], 107) assert n31(31) == (
[
31,
94,
47,
142,
71,
214,
107,
322,
161,
484,
242,
121,
364,
182,
91,
274,
137,
412,
206,
103,
310,
155,
466,
233,
700,
350,
175,
526,
263,
790,
395,
1186,
593,
1780,
890,
445,
1336,
668,
334,
167,
502,
251,
754,
377,
1132,
566,
283,
850,
425,
1276,
638,
319,
958,
479,
1438,
719,
2158,
1079,
3238,
1619,
4858,
2429,
7288,
3644,
1822,
911,
2734,
1367,
4102,
2051,
6154,
3077,
9232,
4616,
2308,
1154,
577,
1732,
866,
433,
1300,
650,
325,
976,
488,
244,
122,
61,
184,
92,
46,
23,
70,
35,
106,
53,
160,
80,
40,
20,
10,
5,
16,
8,
4,
2,
1,
],
107,
)
if __name__ == "__main__": if __name__ == "__main__":

View File

@ -22,13 +22,13 @@ def explicit_euler(ode_func, y0, x0, stepsize, x_end):
>>> y[-1] >>> y[-1]
144.77277243257308 144.77277243257308
""" """
N = int(np.ceil((x_end - x0)/stepsize)) N = int(np.ceil((x_end - x0) / stepsize))
y = np.zeros((N + 1,)) y = np.zeros((N + 1,))
y[0] = y0 y[0] = y0
x = x0 x = x0
for k in range(N): for k in range(N):
y[k + 1] = y[k] + stepsize*ode_func(x, y[k]) y[k + 1] = y[k] + stepsize * ode_func(x, y[k])
x += stepsize x += stepsize
return y return y
@ -38,4 +38,3 @@ if __name__ == "__main__":
import doctest import doctest
doctest.testmod() doctest.testmod()

View File

@ -11,7 +11,7 @@ def factorial(input_number: int) -> int:
""" """
if input_number < 0: if input_number < 0:
raise ValueError('Input input_number should be non-negative') raise ValueError("Input input_number should be non-negative")
elif input_number == 0: elif input_number == 0:
return 1 return 1
else: else:

View File

@ -39,7 +39,9 @@ def main():
nums = input("Enter two integers separated by comma (,): ").split(",") nums = input("Enter two integers separated by comma (,): ").split(",")
num_1 = int(nums[0]) num_1 = int(nums[0])
num_2 = int(nums[1]) num_2 = int(nums[1])
print(f"greatest_common_divisor({num_1}, {num_2}) = {greatest_common_divisor(num_1, num_2)}") print(
f"greatest_common_divisor({num_1}, {num_2}) = {greatest_common_divisor(num_1, num_2)}"
)
print(f"By iterative gcd({num_1}, {num_2}) = {gcd_by_iterative(num_1, num_2)}") print(f"By iterative gcd({num_1}, {num_2}) = {gcd_by_iterative(num_1, num_2)}")
except (IndexError, UnboundLocalError, ValueError): except (IndexError, UnboundLocalError, ValueError):
print("Wrong input") print("Wrong input")

View File

@ -1,5 +1,6 @@
""" Multiply two numbers using Karatsuba algorithm """ """ Multiply two numbers using Karatsuba algorithm """
def karatsuba(a, b): def karatsuba(a, b):
""" """
>>> karatsuba(15463, 23489) == 15463 * 23489 >>> karatsuba(15463, 23489) == 15463 * 23489
@ -8,19 +9,19 @@ def karatsuba(a, b):
True True
""" """
if len(str(a)) == 1 or len(str(b)) == 1: if len(str(a)) == 1 or len(str(b)) == 1:
return (a * b) return a * b
else: else:
m1 = max(len(str(a)), len(str(b))) m1 = max(len(str(a)), len(str(b)))
m2 = m1 // 2 m2 = m1 // 2
a1, a2 = divmod(a, 10**m2) a1, a2 = divmod(a, 10 ** m2)
b1, b2 = divmod(b, 10**m2) b1, b2 = divmod(b, 10 ** m2)
x = karatsuba(a2, b2) x = karatsuba(a2, b2)
y = karatsuba((a1 + a2), (b1 + b2)) y = karatsuba((a1 + a2), (b1 + b2))
z = karatsuba(a1, b1) z = karatsuba(a1, b1)
return ((z * 10**(2*m2)) + ((y - z - x) * 10**(m2)) + (x)) return (z * 10 ** (2 * m2)) + ((y - z - x) * 10 ** (m2)) + (x)
def main(): def main():

View File

@ -1,4 +1,4 @@
''' """
Sieve of Eratosthenes Sieve of Eratosthenes
Input : n =10 Input : n =10
@ -9,7 +9,8 @@ Output: 2 3 5 7 11 13 17 19
you can read in detail about this at you can read in detail about this at
https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes
''' """
def prime_sieve_eratosthenes(num): def prime_sieve_eratosthenes(num):
""" """
@ -21,20 +22,20 @@ def prime_sieve_eratosthenes(num):
2 3 5 7 11 13 17 19 2 3 5 7 11 13 17 19
""" """
primes = [True for i in range(num + 1)] primes = [True for i in range(num + 1)]
p = 2 p = 2
while p * p <= num: while p * p <= num:
if primes[p] == True: if primes[p] == True:
for i in range(p*p, num+1, p): for i in range(p * p, num + 1, p):
primes[i] = False primes[i] = False
p+=1 p += 1
for prime in range(2, num+1): for prime in range(2, num + 1):
if primes[prime]: if primes[prime]:
print(prime, end=" ") print(prime, end=" ")
if __name__ == "__main__": if __name__ == "__main__":
num = int(input()) num = int(input())

View File

@ -51,21 +51,21 @@ def qr_householder(A):
# determine scaling factor # determine scaling factor
alpha = np.linalg.norm(x) alpha = np.linalg.norm(x)
# construct vector v for Householder reflection # construct vector v for Householder reflection
v = x + np.sign(x[0])*alpha*e1 v = x + np.sign(x[0]) * alpha * e1
v /= np.linalg.norm(v) v /= np.linalg.norm(v)
# construct the Householder matrix # construct the Householder matrix
Q_k = np.eye(m - k) - 2.0*v@v.T Q_k = np.eye(m - k) - 2.0 * v @ v.T
# pad with ones and zeros as necessary # pad with ones and zeros as necessary
Q_k = np.block([[np.eye(k), np.zeros((k, m - k))], Q_k = np.block([[np.eye(k), np.zeros((k, m - k))], [np.zeros((m - k, k)), Q_k]])
[np.zeros((m - k, k)), Q_k ]])
Q = Q@Q_k.T Q = Q @ Q_k.T
R = Q_k@R R = Q_k @ R
return Q, R return Q, R
if __name__ == "__main__": if __name__ == "__main__":
import doctest import doctest
doctest.testmod() doctest.testmod()

View File

@ -22,17 +22,17 @@ def runge_kutta(f, y0, x0, h, x_end):
>>> y[-1] >>> y[-1]
148.41315904125113 148.41315904125113
""" """
N = int(np.ceil((x_end - x0)/h)) N = int(np.ceil((x_end - x0) / h))
y = np.zeros((N + 1,)) y = np.zeros((N + 1,))
y[0] = y0 y[0] = y0
x = x0 x = x0
for k in range(N): for k in range(N):
k1 = f(x, y[k]) k1 = f(x, y[k])
k2 = f(x + 0.5*h, y[k] + 0.5*h*k1) k2 = f(x + 0.5 * h, y[k] + 0.5 * h * k1)
k3 = f(x + 0.5*h, y[k] + 0.5*h*k2) k3 = f(x + 0.5 * h, y[k] + 0.5 * h * k2)
k4 = f(x + h, y[k] + h * k3) k4 = f(x + h, y[k] + h * k3)
y[k + 1] = y[k] + (1/6)*h*(k1 + 2*k2 + 2*k3 + k4) y[k + 1] = y[k] + (1 / 6) * h * (k1 + 2 * k2 + 2 * k3 + k4)
x += h x += h
return y return y

View File

@ -7,6 +7,7 @@ single person, one at a time"""
# start[]--> An array that contains start time of all activities # start[]--> An array that contains start time of all activities
# finish[] --> An array that contains finish time of all activities # finish[] --> An array that contains finish time of all activities
def printMaxActivities(start, finish): def printMaxActivities(start, finish):
""" """
>>> start = [1, 3, 0, 5, 8, 5] >>> start = [1, 3, 0, 5, 8, 5]
@ -32,6 +33,7 @@ def printMaxActivities(start, finish):
print(j, end=" ") print(j, end=" ")
i = j i = j
# Driver program to test above function # Driver program to test above function
start = [1, 3, 0, 5, 8, 5] start = [1, 3, 0, 5, 8, 5]
finish = [2, 4, 6, 7, 9, 9] finish = [2, 4, 6, 7, 9, 9]

View File

@ -2,37 +2,38 @@
# Function to print upper half of diamond (pyramid) # Function to print upper half of diamond (pyramid)
def floyd(n): def floyd(n):
''' """
Parameters: Parameters:
n : size of pattern n : size of pattern
''' """
for i in range(0, n): for i in range(0, n):
for j in range(0, n-i-1): # printing spaces for j in range(0, n - i - 1): # printing spaces
print(" ", end = "") print(" ", end="")
for k in range(0, i + 1): # printing stars for k in range(0, i + 1): # printing stars
print("* ", end = "") print("* ", end="")
print() print()
# Function to print lower half of diamond (pyramid) # Function to print lower half of diamond (pyramid)
def reverse_floyd(n): def reverse_floyd(n):
''' """
Parameters: Parameters:
n : size of pattern n : size of pattern
''' """
for i in range(n, 0, -1): for i in range(n, 0, -1):
for j in range(i, 0, -1): # printing stars for j in range(i, 0, -1): # printing stars
print("* ", end = "") print("* ", end="")
print() print()
for k in range(n-i+1, 0, -1): # printing spaces for k in range(n - i + 1, 0, -1): # printing spaces
print(" ", end = "") print(" ", end="")
# Function to print complete diamond pattern of "*" # Function to print complete diamond pattern of "*"
def pretty_print(n): def pretty_print(n):
''' """
Parameters: Parameters:
n : size of pattern n : size of pattern
''' """
if n <= 0: if n <= 0:
print(" ... .... nothing printing :(") print(" ... .... nothing printing :(")
return return
@ -44,7 +45,7 @@ if __name__ == "__main__":
print(r"| /\ | |- | |- |--| |\ /| |-") print(r"| /\ | |- | |- |--| |\ /| |-")
print(r"|/ \| |- |_ |_ |__| | \/ | |_") print(r"|/ \| |- |_ |_ |__| | \/ | |_")
K = 1 K = 1
while(K): while K:
user_number = int(input("enter the number and , and see the magic : ")) user_number = int(input("enter the number and , and see the magic : "))
print() print()
pretty_print(user_number) pretty_print(user_number)

View File

@ -30,14 +30,20 @@ def alternative_password_generator(ctbi, i):
i = i - len(ctbi) i = i - len(ctbi)
quotient = int(i / 3) quotient = int(i / 3)
remainder = i % 3 remainder = i % 3
#chars = ctbi + random_letters(ascii_letters, i / 3 + remainder) + random_number(digits, i / 3) + random_characters(punctuation, i / 3) # chars = ctbi + random_letters(ascii_letters, i / 3 + remainder) + random_number(digits, i / 3) + random_characters(punctuation, i / 3)
chars = ctbi + random(ascii_letters, quotient + remainder) + random(digits, quotient) + random(punctuation, quotient) chars = (
ctbi
+ random(ascii_letters, quotient + remainder)
+ random(digits, quotient)
+ random(punctuation, quotient)
)
chars = list(chars) chars = list(chars)
shuffle(chars) shuffle(chars)
return "".join(chars) return "".join(chars)
# random is a generalised function for letters, characters and numbers
#random is a generalised function for letters, characters and numbers
def random(ctbi, i): def random(ctbi, i):
return "".join(choice(ctbi) for x in range(i)) return "".join(choice(ctbi) for x in range(i))
@ -56,9 +62,13 @@ def random_characters(ctbi, i):
def main(): def main():
length = int(input("Please indicate the max length of your password: ").strip()) length = int(input("Please indicate the max length of your password: ").strip())
ctbi = input("Please indicate the characters that must be in your password: ").strip() ctbi = input(
"Please indicate the characters that must be in your password: "
).strip()
print("Password generated:", password_generator(length)) print("Password generated:", password_generator(length))
print("Alternative Password generated:", alternative_password_generator(ctbi, length)) print(
"Alternative Password generated:", alternative_password_generator(ctbi, length)
)
print("[If you are thinking of using this passsword, You better save it.]") print("[If you are thinking of using this passsword, You better save it.]")

View File

@ -27,11 +27,11 @@ def solution(n):
44 44
""" """
a = [0,1] a = [0, 1]
i = 0 i = 0
while a[i] <= n: while a[i] <= n:
a.append(a[i] + a[i+1]) a.append(a[i] + a[i + 1])
if a[i+2] > n: if a[i + 2] > n:
break break
i += 1 i += 1
sum = 0 sum = 0

View File

@ -1,12 +1,14 @@
#run using python fibonacci_search.py -v # run using python fibonacci_search.py -v
''' """
@params @params
arr: input array arr: input array
val: the value to be searched val: the value to be searched
output: the index of element in the array or -1 if not found output: the index of element in the array or -1 if not found
return 0 if input array is empty return 0 if input array is empty
''' """
def fibonacci_search(arr, val): def fibonacci_search(arr, val):
""" """
@ -23,28 +25,30 @@ def fibonacci_search(arr, val):
length = len(arr) length = len(arr)
if length == 0: if length == 0:
return 0 return 0
while (fibNext < len(arr)): while fibNext < len(arr):
fib_N_2 = fib_N_1 fib_N_2 = fib_N_1
fib_N_1 = fibNext fib_N_1 = fibNext
fibNext = fib_N_1 + fib_N_2 fibNext = fib_N_1 + fib_N_2
index = -1; index = -1
while (fibNext > 1): while fibNext > 1:
i = min(index + fib_N_2, (length-1)) i = min(index + fib_N_2, (length - 1))
if (arr[i] < val): if arr[i] < val:
fibNext = fib_N_1 fibNext = fib_N_1
fib_N_1 = fib_N_2 fib_N_1 = fib_N_2
fib_N_2 = fibNext - fib_N_1 fib_N_2 = fibNext - fib_N_1
index = i index = i
elif (arr[i] > val): elif arr[i] > val:
fibNext = fib_N_2 fibNext = fib_N_2
fib_N_1 = fib_N_1 - fib_N_2 fib_N_1 = fib_N_1 - fib_N_2
fib_N_2 = fibNext - fib_N_1 fib_N_2 = fibNext - fib_N_1
else : else:
return i return i
if (fib_N_1 and index < length-1) and (arr[index+1] == val): if (fib_N_1 and index < length - 1) and (arr[index + 1] == val):
return index+1; return index + 1
return -1 return -1
if __name__ == "__main__": if __name__ == "__main__":
import doctest import doctest
doctest.testmod() doctest.testmod()

View File

@ -35,6 +35,7 @@ def bubble_sort(collection):
if __name__ == "__main__": if __name__ == "__main__":
import time import time
user_input = input("Enter numbers separated by a comma:").strip() user_input = input("Enter numbers separated by a comma:").strip()
unsorted = [int(item) for item in user_input.split(",")] unsorted = [int(item) for item in user_input.split(",")]
start = time.process_time() start = time.process_time()

View File

@ -14,21 +14,29 @@ def double_sort(lst):
>>> double_sort([-3, 10, 16, -42, 29]) == sorted([-3, 10, 16, -42, 29]) >>> double_sort([-3, 10, 16, -42, 29]) == sorted([-3, 10, 16, -42, 29])
True True
""" """
no_of_elements=len(lst) no_of_elements = len(lst)
for i in range(0,int(((no_of_elements-1)/2)+1)): # we dont need to traverse to end of list as for i in range(
for j in range(0,no_of_elements-1): 0, int(((no_of_elements - 1) / 2) + 1)
if (lst[j+1]<lst[j]): # applying bubble sort algorithm from left to right (or forwards) ): # we dont need to traverse to end of list as
temp=lst[j+1] for j in range(0, no_of_elements - 1):
lst[j+1]=lst[j] if (
lst[j]=temp lst[j + 1] < lst[j]
if (lst[no_of_elements-1-j]<lst[no_of_elements-2-j]): # applying bubble sort algorithm from right to left (or backwards) ): # applying bubble sort algorithm from left to right (or forwards)
temp=lst[no_of_elements-1-j] temp = lst[j + 1]
lst[no_of_elements-1-j]=lst[no_of_elements-2-j] lst[j + 1] = lst[j]
lst[no_of_elements-2-j]=temp lst[j] = temp
if (
lst[no_of_elements - 1 - j] < lst[no_of_elements - 2 - j]
): # applying bubble sort algorithm from right to left (or backwards)
temp = lst[no_of_elements - 1 - j]
lst[no_of_elements - 1 - j] = lst[no_of_elements - 2 - j]
lst[no_of_elements - 2 - j] = temp
return lst return lst
if __name__ == "__main__": if __name__ == "__main__":
print("enter the list to be sorted") print("enter the list to be sorted")
lst = [int(x) for x in input().split()] # inputing elements of the list in one line lst = [int(x) for x in input().split()] # inputing elements of the list in one line
sorted_lst=double_sort(lst) sorted_lst = double_sort(lst)
print("the sorted list is") print("the sorted list is")
print(sorted_lst) print(sorted_lst)