mirror of
https://github.com/TheAlgorithms/Python.git
synced 2025-02-25 10:28:39 +00:00
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:
parent
11e2207182
commit
7592cba417
@ -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")
|
||||||
|
@ -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
|
||||||
@ -106,6 +108,7 @@ def erase(root: Node, value: int) -> Node:
|
|||||||
_, 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()
|
||||||
|
@ -23,6 +23,7 @@ def merge(a,b,m,e):
|
|||||||
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)
|
||||||
@ -40,6 +41,8 @@ def mergesort(a,b,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()
|
||||||
|
@ -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")
|
||||||
|
@ -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
|
||||||
|
|
||||||
|
@ -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
|
||||||
|
|
||||||
|
@ -8,10 +8,12 @@ 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]
|
abc1 = [0, 25, 50]
|
||||||
abc2 = [25, 50, 75]
|
abc2 = [25, 50, 75]
|
||||||
young = fuzz.membership.trimf(X, abc1)
|
young = fuzz.membership.trimf(X, abc1)
|
||||||
|
@ -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,11 +8,12 @@ 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])
|
||||||
@ -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))
|
||||||
|
|
||||||
|
|
||||||
|
@ -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,14 +140,11 @@ 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():
|
||||||
"""
|
"""
|
||||||
In this demonstration we're generating a sample data set from the sin function in numpy.
|
In this demonstration we're generating a sample data set from the sin function in numpy.
|
||||||
|
@ -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,13 +27,15 @@ 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
|
||||||
|
113
maths/3n+1.py
113
maths/3n+1.py
@ -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__":
|
||||||
|
@ -38,4 +38,3 @@ if __name__ == "__main__":
|
|||||||
import doctest
|
import doctest
|
||||||
|
|
||||||
doctest.testmod()
|
doctest.testmod()
|
||||||
|
|
||||||
|
@ -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:
|
||||||
|
@ -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")
|
||||||
|
@ -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,7 +9,7 @@ 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
|
||||||
@ -20,7 +21,7 @@ def karatsuba(a, b):
|
|||||||
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():
|
||||||
|
@ -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,7 +22,6 @@ 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
|
||||||
|
|
||||||
@ -35,6 +35,7 @@ def prime_sieve_eratosthenes(num):
|
|||||||
if primes[prime]:
|
if primes[prime]:
|
||||||
print(prime, end=" ")
|
print(prime, end=" ")
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
num = int(input())
|
num = int(input())
|
||||||
|
|
||||||
|
@ -57,8 +57,7 @@ def qr_householder(A):
|
|||||||
# 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
|
||||||
@ -68,4 +67,5 @@ def qr_householder(A):
|
|||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
import doctest
|
import doctest
|
||||||
|
|
||||||
doctest.testmod()
|
doctest.testmod()
|
||||||
|
@ -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]
|
||||||
|
@ -2,10 +2,10 @@
|
|||||||
|
|
||||||
# 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="")
|
||||||
@ -16,10 +16,10 @@ def floyd(n):
|
|||||||
|
|
||||||
# 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="")
|
||||||
@ -27,12 +27,13 @@ def reverse_floyd(n):
|
|||||||
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)
|
||||||
|
@ -31,13 +31,19 @@ def alternative_password_generator(ctbi, i):
|
|||||||
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.]")
|
||||||
|
|
||||||
|
|
||||||
|
@ -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()
|
||||||
|
@ -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()
|
||||||
|
@ -15,17 +15,25 @@ def double_sort(lst):
|
|||||||
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(
|
||||||
|
0, int(((no_of_elements - 1) / 2) + 1)
|
||||||
|
): # we dont need to traverse to end of list as
|
||||||
for j in range(0, no_of_elements - 1):
|
for j in range(0, no_of_elements - 1):
|
||||||
if (lst[j+1]<lst[j]): # applying bubble sort algorithm from left to right (or forwards)
|
if (
|
||||||
|
lst[j + 1] < lst[j]
|
||||||
|
): # applying bubble sort algorithm from left to right (or forwards)
|
||||||
temp = lst[j + 1]
|
temp = lst[j + 1]
|
||||||
lst[j + 1] = lst[j]
|
lst[j + 1] = lst[j]
|
||||||
lst[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)
|
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]
|
temp = lst[no_of_elements - 1 - j]
|
||||||
lst[no_of_elements - 1 - j] = lst[no_of_elements - 2 - j]
|
lst[no_of_elements - 1 - j] = lst[no_of_elements - 2 - j]
|
||||||
lst[no_of_elements - 2 - j] = temp
|
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
|
||||||
|
Loading…
x
Reference in New Issue
Block a user