mirror of
https://github.com/TheAlgorithms/Python.git
synced 2024-11-23 21:11:08 +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
|
@ -18,7 +18,7 @@ def encode_base64(text):
|
|||
i = 0
|
||||
while i < len(s):
|
||||
if i > 0 and ((i / 3 * 4) % 76) == 0:
|
||||
r = r + "\r\n" # for unix newline, put "\n"
|
||||
r = r + "\r\n" # for unix newline, put "\n"
|
||||
|
||||
n = (s[i] << 16) + (s[i + 1] << 8) + s[i + 2]
|
||||
|
||||
|
|
|
@ -1,5 +1,5 @@
|
|||
def encrypt(input_string: str, key: int) -> str:
|
||||
result = ''
|
||||
result = ""
|
||||
for x in input_string:
|
||||
if not x.isalpha():
|
||||
result += x
|
||||
|
@ -11,7 +11,7 @@ def encrypt(input_string: str, key: int) -> str:
|
|||
|
||||
|
||||
def decrypt(input_string: str, key: int) -> str:
|
||||
result = ''
|
||||
result = ""
|
||||
for x in input_string:
|
||||
if not x.isalpha():
|
||||
result += x
|
||||
|
@ -24,15 +24,15 @@ def decrypt(input_string: str, key: int) -> str:
|
|||
|
||||
def brute_force(input_string: str) -> None:
|
||||
key = 1
|
||||
result = ''
|
||||
result = ""
|
||||
while key <= 94:
|
||||
for x in input_string:
|
||||
indx = (ord(x) - key) % 256
|
||||
if indx < 32:
|
||||
indx = indx + 95
|
||||
result = result + chr(indx)
|
||||
print(f'Key: {key}\t| Message: {result}')
|
||||
result = ''
|
||||
print(f"Key: {key}\t| Message: {result}")
|
||||
result = ""
|
||||
key += 1
|
||||
return None
|
||||
|
||||
|
@ -40,7 +40,7 @@ def brute_force(input_string: str) -> None:
|
|||
def main():
|
||||
while True:
|
||||
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?: ")
|
||||
if choice not in ["1", "2", "3", "4"]:
|
||||
print("Invalid choice, please enter a valid choice")
|
||||
|
|
|
@ -7,6 +7,7 @@ class Node(object):
|
|||
Treap's node
|
||||
Treap is a binary tree by value and heap by priority
|
||||
"""
|
||||
|
||||
def __init__(self, value: int = None):
|
||||
self.value = value
|
||||
self.prior = random()
|
||||
|
@ -20,10 +21,7 @@ class Node(object):
|
|||
return "'%s: %.5s'" % (self.value, self.prior)
|
||||
else:
|
||||
return pformat(
|
||||
{
|
||||
"%s: %.5s"
|
||||
% (self.value, self.prior): (self.left, self.right)
|
||||
},
|
||||
{"%s: %.5s" % (self.value, self.prior): (self.left, self.right)},
|
||||
indent=1,
|
||||
)
|
||||
|
||||
|
@ -33,6 +31,7 @@ class Node(object):
|
|||
right = str(self.right or "")
|
||||
return value + left + right
|
||||
|
||||
|
||||
def split(root: Node, value: int) -> Tuple[Node, Node]:
|
||||
"""
|
||||
We split current tree into 2 trees with value:
|
||||
|
@ -61,12 +60,13 @@ def split(root: Node, value: int) -> Tuple[Node, Node]:
|
|||
root.right, right = split(root.right, value)
|
||||
return (root, right)
|
||||
|
||||
|
||||
def merge(left: Node, right: Node) -> Node:
|
||||
"""
|
||||
We merge 2 trees into one.
|
||||
Note: all left tree's values must be less than all right tree's
|
||||
"""
|
||||
if (not left) or (not right): # If one node is None, return the other
|
||||
if (not left) or (not right): # If one node is None, return the other
|
||||
return left or right
|
||||
elif left.prior < right.prior:
|
||||
"""
|
||||
|
@ -82,6 +82,7 @@ def merge(left: Node, right: Node) -> Node:
|
|||
right.left = merge(left, right.left)
|
||||
return right
|
||||
|
||||
|
||||
def insert(root: Node, value: int) -> Node:
|
||||
"""
|
||||
Insert element
|
||||
|
@ -94,6 +95,7 @@ def insert(root: Node, value: int) -> Node:
|
|||
left, right = split(root, value)
|
||||
return merge(merge(left, node), right)
|
||||
|
||||
|
||||
def erase(root: Node, value: int) -> Node:
|
||||
"""
|
||||
Erase element
|
||||
|
@ -102,15 +104,16 @@ def erase(root: Node, value: int) -> Node:
|
|||
Split all nodes with values greater into right.
|
||||
Merge left, right
|
||||
"""
|
||||
left, right = split(root, value-1)
|
||||
left, right = split(root, value - 1)
|
||||
_, right = split(right, value)
|
||||
return merge(left, right)
|
||||
|
||||
|
||||
def inorder(root: Node):
|
||||
"""
|
||||
Just recursive print of a tree
|
||||
"""
|
||||
if not root: # None
|
||||
if not root: # None
|
||||
return
|
||||
else:
|
||||
inorder(root.left)
|
||||
|
@ -154,13 +157,16 @@ def interactTreap(root, args):
|
|||
|
||||
return root
|
||||
|
||||
|
||||
def main():
|
||||
"""After each command, program prints treap"""
|
||||
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()
|
||||
while args != 'q':
|
||||
while args != "q":
|
||||
root = interactTreap(root, args)
|
||||
print(root)
|
||||
args = input()
|
||||
|
@ -168,7 +174,9 @@ def main():
|
|||
print("good by!")
|
||||
pass
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
import doctest
|
||||
|
||||
doctest.testmod()
|
||||
main()
|
||||
|
|
|
@ -1,45 +1,48 @@
|
|||
def merge(a,b,m,e):
|
||||
l=a[b:m+1]
|
||||
r=a[m+1:e+1]
|
||||
k=b
|
||||
i=0
|
||||
j=0
|
||||
while i<len(l) and j<len(r):
|
||||
#change sign for Descending order
|
||||
if l[i]<r[j]:
|
||||
a[k]=l[i]
|
||||
i+=1
|
||||
def merge(a, b, m, e):
|
||||
l = a[b : m + 1]
|
||||
r = a[m + 1 : e + 1]
|
||||
k = b
|
||||
i = 0
|
||||
j = 0
|
||||
while i < len(l) and j < len(r):
|
||||
# change sign for Descending order
|
||||
if l[i] < r[j]:
|
||||
a[k] = l[i]
|
||||
i += 1
|
||||
else:
|
||||
a[k]=r[j]
|
||||
j+=1
|
||||
k+=1
|
||||
while i<len(l):
|
||||
a[k]=l[i]
|
||||
i+=1
|
||||
k+=1
|
||||
while j<len(r):
|
||||
a[k]=r[j]
|
||||
j+=1
|
||||
k+=1
|
||||
a[k] = r[j]
|
||||
j += 1
|
||||
k += 1
|
||||
while i < len(l):
|
||||
a[k] = l[i]
|
||||
i += 1
|
||||
k += 1
|
||||
while j < len(r):
|
||||
a[k] = r[j]
|
||||
j += 1
|
||||
k += 1
|
||||
return a
|
||||
|
||||
def mergesort(a,b,e):
|
||||
|
||||
|
||||
def mergesort(a, b, e):
|
||||
"""
|
||||
>>> mergesort([3,2,1],0,2)
|
||||
[1, 2, 3]
|
||||
>>> mergesort([3,2,1,0,1,2,3,5,4],0,8)
|
||||
[0, 1, 1, 2, 2, 3, 3, 4, 5]
|
||||
"""
|
||||
if b<e:
|
||||
m = (b+e)//2
|
||||
#print("ms1",a,b,m)
|
||||
mergesort(a,b,m)
|
||||
#print("ms2",a,m+1,e)
|
||||
mergesort(a,m+1,e)
|
||||
#print("m",a,b,m,e)
|
||||
merge(a,b,m,e)
|
||||
if b < e:
|
||||
m = (b + e) // 2
|
||||
# print("ms1",a,b,m)
|
||||
mergesort(a, b, m)
|
||||
# print("ms2",a,m+1,e)
|
||||
mergesort(a, m + 1, e)
|
||||
# print("m",a,b,m,e)
|
||||
merge(a, b, m, e)
|
||||
return a
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
import doctest
|
||||
|
||||
doctest.testmod()
|
||||
|
|
|
@ -11,6 +11,7 @@ a=daBcd and b="ABC"
|
|||
daBcd -> capitalize a and c(dABCd) -> remove d (ABC)
|
||||
"""
|
||||
|
||||
|
||||
def abbr(a, b):
|
||||
"""
|
||||
>>> abbr("daBcd", "ABC")
|
||||
|
|
|
@ -58,7 +58,7 @@ if __name__ == "__main__":
|
|||
print("\nInvalid input, please try again.")
|
||||
except NameError:
|
||||
print("\n********* Invalid input, good bye!! ************\n")
|
||||
|
||||
|
||||
import doctest
|
||||
|
||||
doctest.testmod()
|
||||
|
|
|
@ -20,6 +20,7 @@ def fracKnapsack(vl, wt, W, n):
|
|||
else sum(vl[:k])
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
import doctest
|
||||
|
||||
|
|
|
@ -76,7 +76,7 @@ if __name__ == "__main__":
|
|||
expected_subseq = "GTAB"
|
||||
|
||||
ln, subseq = longest_common_subsequence(a, b)
|
||||
## print("len =", ln, ", sub-sequence =", subseq)
|
||||
## print("len =", ln, ", sub-sequence =", subseq)
|
||||
import doctest
|
||||
|
||||
doctest.testmod()
|
||||
|
|
|
@ -29,6 +29,7 @@ def isSumSubset(arr, arrLen, requiredSum):
|
|||
# print(subset[i])
|
||||
print(subset[arrLen][requiredSum])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
import doctest
|
||||
|
||||
|
|
|
@ -8,37 +8,39 @@ Python:
|
|||
"""
|
||||
# Create universe of discourse in python using linspace ()
|
||||
import numpy as np
|
||||
|
||||
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).
|
||||
import skfuzzy as fuzz
|
||||
abc1=[0,25,50]
|
||||
abc2=[25,50,75]
|
||||
young = fuzz.membership.trimf(X,abc1)
|
||||
middle_aged = fuzz.membership.trimf(X,abc2)
|
||||
|
||||
abc1 = [0, 25, 50]
|
||||
abc2 = [25, 50, 75]
|
||||
young = fuzz.membership.trimf(X, abc1)
|
||||
middle_aged = fuzz.membership.trimf(X, abc2)
|
||||
|
||||
# Compute the different operations using inbuilt functions.
|
||||
one = np.ones(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]
|
||||
#2. Intersection = min(µA(x), µB(x))
|
||||
# 2. Intersection = min(µA(x), µB(x))
|
||||
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)
|
||||
#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]
|
||||
#5. Algebraic Sum = [µA(x) + µB(x) – (µA(x) * µB(x))]
|
||||
alg_sum = young + middle_aged - (young*middle_aged)
|
||||
#6. Algebraic Product = (µA(x) * µB(x))
|
||||
alg_product = young*middle_aged
|
||||
#7. Bounded Sum = min[1,(µA(x), µB(x))]
|
||||
bdd_sum = fuzz.fuzzy_and(X, one, X, young+middle_aged)[1]
|
||||
#8. Bounded difference = min[0,(µA(x), µB(x))]
|
||||
bdd_difference = fuzz.fuzzy_or(X, zero, X, young-middle_aged)[1]
|
||||
# 5. Algebraic Sum = [µA(x) + µB(x) – (µA(x) * µB(x))]
|
||||
alg_sum = young + middle_aged - (young * middle_aged)
|
||||
# 6. Algebraic Product = (µA(x) * µB(x))
|
||||
alg_product = young * middle_aged
|
||||
# 7. Bounded Sum = min[1,(µA(x), µB(x))]
|
||||
bdd_sum = fuzz.fuzzy_and(X, one, X, young + middle_aged)[1]
|
||||
# 8. Bounded difference = min[0,(µA(x), µB(x))]
|
||||
bdd_difference = fuzz.fuzzy_or(X, zero, X, young - middle_aged)[1]
|
||||
|
||||
#max-min composition
|
||||
#max-product composition
|
||||
# max-min composition
|
||||
# max-product composition
|
||||
|
||||
|
||||
# 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.subplot(4,3,1)
|
||||
plt.plot(X,young)
|
||||
plt.subplot(4, 3, 1)
|
||||
plt.plot(X, young)
|
||||
plt.title("Young")
|
||||
plt.grid(True)
|
||||
|
||||
plt.subplot(4,3,2)
|
||||
plt.plot(X,middle_aged)
|
||||
plt.subplot(4, 3, 2)
|
||||
plt.plot(X, middle_aged)
|
||||
plt.title("Middle aged")
|
||||
plt.grid(True)
|
||||
|
||||
plt.subplot(4,3,3)
|
||||
plt.plot(X,union)
|
||||
plt.subplot(4, 3, 3)
|
||||
plt.plot(X, union)
|
||||
plt.title("union")
|
||||
plt.grid(True)
|
||||
|
||||
plt.subplot(4,3,4)
|
||||
plt.plot(X,intersection)
|
||||
plt.subplot(4, 3, 4)
|
||||
plt.plot(X, intersection)
|
||||
plt.title("intersection")
|
||||
plt.grid(True)
|
||||
|
||||
plt.subplot(4,3,5)
|
||||
plt.plot(X,complement_a)
|
||||
plt.subplot(4, 3, 5)
|
||||
plt.plot(X, complement_a)
|
||||
plt.title("complement_a")
|
||||
plt.grid(True)
|
||||
|
||||
plt.subplot(4,3,6)
|
||||
plt.plot(X,difference)
|
||||
plt.subplot(4, 3, 6)
|
||||
plt.plot(X, difference)
|
||||
plt.title("difference a/b")
|
||||
plt.grid(True)
|
||||
|
||||
plt.subplot(4,3,7)
|
||||
plt.plot(X,alg_sum)
|
||||
plt.subplot(4, 3, 7)
|
||||
plt.plot(X, alg_sum)
|
||||
plt.title("alg_sum")
|
||||
plt.grid(True)
|
||||
|
||||
plt.subplot(4,3,8)
|
||||
plt.plot(X,alg_product)
|
||||
plt.subplot(4, 3, 8)
|
||||
plt.plot(X, alg_product)
|
||||
plt.title("alg_product")
|
||||
plt.grid(True)
|
||||
|
||||
plt.subplot(4,3,9)
|
||||
plt.plot(X,bdd_sum)
|
||||
plt.subplot(4, 3, 9)
|
||||
plt.plot(X, bdd_sum)
|
||||
plt.title("bdd_sum")
|
||||
plt.grid(True)
|
||||
|
||||
plt.subplot(4,3,10)
|
||||
plt.plot(X,bdd_difference)
|
||||
plt.subplot(4, 3, 10)
|
||||
plt.plot(X, bdd_difference)
|
||||
plt.title("bdd_difference")
|
||||
plt.grid(True)
|
||||
|
||||
plt.subplots_adjust(hspace = 0.5)
|
||||
plt.subplots_adjust(hspace=0.5)
|
||||
plt.show()
|
||||
|
|
|
@ -1,5 +1,6 @@
|
|||
INF = float("inf")
|
||||
|
||||
|
||||
class Dinic:
|
||||
def __init__(self, n):
|
||||
self.lvl = [0] * n
|
||||
|
@ -7,16 +8,17 @@ class Dinic:
|
|||
self.q = [0] * n
|
||||
self.adj = [[] for _ in range(n)]
|
||||
|
||||
'''
|
||||
"""
|
||||
Here we will add our edges containing with the following parameters:
|
||||
vertex closest to source, vertex closest to sink and flow capacity
|
||||
through that edge ...
|
||||
'''
|
||||
"""
|
||||
|
||||
def add_edge(self, a, b, c, rcap=0):
|
||||
self.adj[a].append([b, len(self.adj[b]), c, 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):
|
||||
if vertex == sink or not flow:
|
||||
return flow
|
||||
|
@ -31,8 +33,8 @@ class Dinic:
|
|||
return p
|
||||
self.ptr[vertex] = self.ptr[vertex] + 1
|
||||
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):
|
||||
flow, self.q[0] = 0, source
|
||||
for l in range(31): # l = 30 maybe faster for random data
|
||||
|
@ -58,36 +60,35 @@ class Dinic:
|
|||
|
||||
return flow
|
||||
|
||||
#Example to use
|
||||
|
||||
'''
|
||||
# Example to use
|
||||
|
||||
"""
|
||||
Will be a bipartite graph, than it has the vertices near the source(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)
|
||||
source = 0
|
||||
sink = 9
|
||||
'''
|
||||
"""
|
||||
Now we add the vertices next to the font in the font with 1 capacity in this edge
|
||||
(source -> source vertices)
|
||||
'''
|
||||
"""
|
||||
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
|
||||
(sink vertices -> sink)
|
||||
'''
|
||||
"""
|
||||
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.
|
||||
(source vertices -> sink vertices)
|
||||
'''
|
||||
"""
|
||||
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))
|
||||
|
||||
|
||||
|
|
|
@ -125,6 +125,7 @@ class Decision_Tree:
|
|||
print("Error: Decision tree not yet trained")
|
||||
return None
|
||||
|
||||
|
||||
class Test_Decision_Tree:
|
||||
"""Decision Tres test class
|
||||
"""
|
||||
|
@ -139,12 +140,9 @@ class Test_Decision_Tree:
|
|||
"""
|
||||
squared_error_sum = np.float(0)
|
||||
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():
|
||||
|
|
|
@ -2,19 +2,23 @@ import matplotlib.pyplot as plt
|
|||
import pandas as pd
|
||||
|
||||
# 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
|
||||
y = dataset.iloc[:, 2].values
|
||||
|
||||
|
||||
# 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)
|
||||
|
||||
|
||||
# Fitting Polynomial Regression to the dataset
|
||||
from sklearn.preprocessing import PolynomialFeatures
|
||||
from sklearn.linear_model import LinearRegression
|
||||
|
||||
poly_reg = PolynomialFeatures(degree=4)
|
||||
X_poly = poly_reg.fit_transform(X)
|
||||
pol_reg = LinearRegression()
|
||||
|
@ -23,15 +27,17 @@ pol_reg.fit(X_poly, y)
|
|||
|
||||
# Visualizing the Polymonial Regression results
|
||||
def viz_polymonial():
|
||||
plt.scatter(X, y, color='red')
|
||||
plt.plot(X, pol_reg.predict(poly_reg.fit_transform(X)), color='blue')
|
||||
plt.title('Truth or Bluff (Linear Regression)')
|
||||
plt.xlabel('Position level')
|
||||
plt.ylabel('Salary')
|
||||
plt.scatter(X, y, color="red")
|
||||
plt.plot(X, pol_reg.predict(poly_reg.fit_transform(X)), color="blue")
|
||||
plt.title("Truth or Bluff (Linear Regression)")
|
||||
plt.xlabel("Position level")
|
||||
plt.ylabel("Salary")
|
||||
plt.show()
|
||||
return
|
||||
|
||||
|
||||
viz_polymonial()
|
||||
|
||||
# Predicting a new result with Polymonial Regression
|
||||
pol_reg.predict(poly_reg.fit_transform([[5.5]]))
|
||||
#output should be 132148.43750003
|
||||
# output should be 132148.43750003
|
||||
|
|
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(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__":
|
||||
|
|
|
@ -22,13 +22,13 @@ def explicit_euler(ode_func, y0, x0, stepsize, x_end):
|
|||
>>> y[-1]
|
||||
144.77277243257308
|
||||
"""
|
||||
N = int(np.ceil((x_end - x0)/stepsize))
|
||||
N = int(np.ceil((x_end - x0) / stepsize))
|
||||
y = np.zeros((N + 1,))
|
||||
y[0] = y0
|
||||
x = x0
|
||||
|
||||
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
|
||||
|
||||
return y
|
||||
|
@ -38,4 +38,3 @@ if __name__ == "__main__":
|
|||
import doctest
|
||||
|
||||
doctest.testmod()
|
||||
|
||||
|
|
|
@ -11,7 +11,7 @@ def factorial(input_number: int) -> int:
|
|||
"""
|
||||
|
||||
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:
|
||||
return 1
|
||||
else:
|
||||
|
|
|
@ -39,7 +39,9 @@ def main():
|
|||
nums = input("Enter two integers separated by comma (,): ").split(",")
|
||||
num_1 = int(nums[0])
|
||||
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)}")
|
||||
except (IndexError, UnboundLocalError, ValueError):
|
||||
print("Wrong input")
|
||||
|
|
|
@ -1,5 +1,6 @@
|
|||
""" Multiply two numbers using Karatsuba algorithm """
|
||||
|
||||
|
||||
def karatsuba(a, b):
|
||||
"""
|
||||
>>> karatsuba(15463, 23489) == 15463 * 23489
|
||||
|
@ -8,19 +9,19 @@ def karatsuba(a, b):
|
|||
True
|
||||
"""
|
||||
if len(str(a)) == 1 or len(str(b)) == 1:
|
||||
return (a * b)
|
||||
return a * b
|
||||
else:
|
||||
m1 = max(len(str(a)), len(str(b)))
|
||||
m2 = m1 // 2
|
||||
|
||||
a1, a2 = divmod(a, 10**m2)
|
||||
b1, b2 = divmod(b, 10**m2)
|
||||
a1, a2 = divmod(a, 10 ** m2)
|
||||
b1, b2 = divmod(b, 10 ** m2)
|
||||
|
||||
x = karatsuba(a2, b2)
|
||||
y = karatsuba((a1 + a2), (b1 + b2))
|
||||
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():
|
||||
|
|
|
@ -1,4 +1,4 @@
|
|||
'''
|
||||
"""
|
||||
Sieve of Eratosthenes
|
||||
|
||||
Input : n =10
|
||||
|
@ -9,7 +9,8 @@ Output: 2 3 5 7 11 13 17 19
|
|||
|
||||
you can read in detail about this at
|
||||
https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes
|
||||
'''
|
||||
"""
|
||||
|
||||
|
||||
def prime_sieve_eratosthenes(num):
|
||||
"""
|
||||
|
@ -20,22 +21,22 @@ def prime_sieve_eratosthenes(num):
|
|||
>>> prime_sieve_eratosthenes(20)
|
||||
2 3 5 7 11 13 17 19
|
||||
"""
|
||||
|
||||
|
||||
|
||||
primes = [True for i in range(num + 1)]
|
||||
p = 2
|
||||
|
||||
|
||||
while p * p <= num:
|
||||
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
|
||||
p+=1
|
||||
p += 1
|
||||
|
||||
for prime in range(2, num+1):
|
||||
for prime in range(2, num + 1):
|
||||
if primes[prime]:
|
||||
print(prime, end=" ")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
num = int(input())
|
||||
|
||||
|
||||
prime_sieve_eratosthenes(num)
|
||||
|
|
|
@ -51,21 +51,21 @@ def qr_householder(A):
|
|||
# determine scaling factor
|
||||
alpha = np.linalg.norm(x)
|
||||
# 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)
|
||||
|
||||
# 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
|
||||
Q_k = np.block([[np.eye(k), np.zeros((k, m - k))],
|
||||
[np.zeros((m - k, k)), Q_k ]])
|
||||
Q_k = np.block([[np.eye(k), np.zeros((k, m - k))], [np.zeros((m - k, k)), Q_k]])
|
||||
|
||||
Q = Q@Q_k.T
|
||||
R = Q_k@R
|
||||
Q = Q @ Q_k.T
|
||||
R = Q_k @ R
|
||||
|
||||
return Q, R
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
import doctest
|
||||
|
||||
doctest.testmod()
|
||||
|
|
|
@ -22,17 +22,17 @@ def runge_kutta(f, y0, x0, h, x_end):
|
|||
>>> y[-1]
|
||||
148.41315904125113
|
||||
"""
|
||||
N = int(np.ceil((x_end - x0)/h))
|
||||
N = int(np.ceil((x_end - x0) / h))
|
||||
y = np.zeros((N + 1,))
|
||||
y[0] = y0
|
||||
x = x0
|
||||
|
||||
for k in range(N):
|
||||
k1 = f(x, y[k])
|
||||
k2 = f(x + 0.5*h, y[k] + 0.5*h*k1)
|
||||
k3 = f(x + 0.5*h, y[k] + 0.5*h*k2)
|
||||
k2 = f(x + 0.5 * h, y[k] + 0.5 * h * k1)
|
||||
k3 = f(x + 0.5 * h, y[k] + 0.5 * h * k2)
|
||||
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
|
||||
|
||||
return y
|
||||
|
|
|
@ -1,12 +1,13 @@
|
|||
"""The following implementation assumes that the activities
|
||||
are already sorted according to their finish time"""
|
||||
|
||||
|
||||
"""Prints a maximum set of activities that can be done by a
|
||||
single person, one at a time"""
|
||||
# n --> Total number of activities
|
||||
# start[]--> An array that contains start time of all activities
|
||||
# finish[] --> An array that contains finish time of all activities
|
||||
|
||||
# n --> Total number of activities
|
||||
# start[]--> An array that contains start time of all activities
|
||||
# finish[] --> An array that contains finish time of all activities
|
||||
|
||||
|
||||
def printMaxActivities(start, finish):
|
||||
"""
|
||||
>>> start = [1, 3, 0, 5, 8, 5]
|
||||
|
@ -15,27 +16,28 @@ def printMaxActivities(start, finish):
|
|||
The following activities are selected:
|
||||
0 1 3 4
|
||||
"""
|
||||
n = len(finish)
|
||||
n = len(finish)
|
||||
print("The following activities are selected:")
|
||||
|
||||
# The first activity is always selected
|
||||
|
||||
# The first activity is always selected
|
||||
i = 0
|
||||
print(i, end=" ")
|
||||
|
||||
# Consider rest of the activities
|
||||
for j in range(n):
|
||||
|
||||
# If this activity has start time greater than
|
||||
# or equal to the finish time of previously
|
||||
# selected activity, then select it
|
||||
if start[j] >= finish[i]:
|
||||
|
||||
# Consider rest of the activities
|
||||
for j in range(n):
|
||||
|
||||
# If this activity has start time greater than
|
||||
# or equal to the finish time of previously
|
||||
# selected activity, then select it
|
||||
if start[j] >= finish[i]:
|
||||
print(j, end=" ")
|
||||
i = j
|
||||
|
||||
# Driver program to test above function
|
||||
start = [1, 3, 0, 5, 8, 5]
|
||||
finish = [2, 4, 6, 7, 9, 9]
|
||||
printMaxActivities(start, finish)
|
||||
i = j
|
||||
|
||||
|
||||
# Driver program to test above function
|
||||
start = [1, 3, 0, 5, 8, 5]
|
||||
finish = [2, 4, 6, 7, 9, 9]
|
||||
printMaxActivities(start, finish)
|
||||
|
||||
"""
|
||||
The following activities are selected:
|
||||
|
|
|
@ -2,52 +2,53 @@
|
|||
|
||||
# Function to print upper half of diamond (pyramid)
|
||||
def floyd(n):
|
||||
'''
|
||||
"""
|
||||
Parameters:
|
||||
n : size of pattern
|
||||
'''
|
||||
for i in range(0, n):
|
||||
for j in range(0, n-i-1): # printing spaces
|
||||
print(" ", end = "")
|
||||
for k in range(0, i + 1): # printing stars
|
||||
print("* ", end = "")
|
||||
print()
|
||||
"""
|
||||
for i in range(0, n):
|
||||
for j in range(0, n - i - 1): # printing spaces
|
||||
print(" ", end="")
|
||||
for k in range(0, i + 1): # printing stars
|
||||
print("* ", end="")
|
||||
print()
|
||||
|
||||
|
||||
# Function to print lower half of diamond (pyramid)
|
||||
def reverse_floyd(n):
|
||||
'''
|
||||
"""
|
||||
Parameters:
|
||||
n : size of pattern
|
||||
'''
|
||||
for i in range(n, 0, -1):
|
||||
for j in range(i, 0, -1): # printing stars
|
||||
print("* ", end = "")
|
||||
print()
|
||||
for k in range(n-i+1, 0, -1): # printing spaces
|
||||
print(" ", end = "")
|
||||
"""
|
||||
for i in range(n, 0, -1):
|
||||
for j in range(i, 0, -1): # printing stars
|
||||
print("* ", end="")
|
||||
print()
|
||||
for k in range(n - i + 1, 0, -1): # printing spaces
|
||||
print(" ", end="")
|
||||
|
||||
|
||||
# Function to print complete diamond pattern of "*"
|
||||
def pretty_print(n):
|
||||
'''
|
||||
"""
|
||||
Parameters:
|
||||
n : size of pattern
|
||||
'''
|
||||
if n <= 0:
|
||||
print(" ... .... nothing printing :(")
|
||||
return
|
||||
floyd(n) # upper half
|
||||
reverse_floyd(n) # lower half
|
||||
"""
|
||||
if n <= 0:
|
||||
print(" ... .... nothing printing :(")
|
||||
return
|
||||
floyd(n) # upper half
|
||||
reverse_floyd(n) # lower half
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
print(r"| /\ | |- | |- |--| |\ /| |-")
|
||||
print(r"|/ \| |- |_ |_ |__| | \/ | |_")
|
||||
K = 1
|
||||
while(K):
|
||||
user_number = int(input("enter the number and , and see the magic : "))
|
||||
print()
|
||||
pretty_print(user_number)
|
||||
K = int(input("press 0 to exit... and 1 to continue..."))
|
||||
print(r"| /\ | |- | |- |--| |\ /| |-")
|
||||
print(r"|/ \| |- |_ |_ |__| | \/ | |_")
|
||||
K = 1
|
||||
while K:
|
||||
user_number = int(input("enter the number and , and see the magic : "))
|
||||
print()
|
||||
pretty_print(user_number)
|
||||
K = int(input("press 0 to exit... and 1 to continue..."))
|
||||
|
||||
print("Good Bye...")
|
||||
print("Good Bye...")
|
||||
|
|
|
@ -27,21 +27,27 @@ def alternative_password_generator(ctbi, i):
|
|||
# Password generator = full boot with random_number, random_letters, and
|
||||
# random_character FUNCTIONS
|
||||
# Put your code here...
|
||||
i = i - len(ctbi)
|
||||
quotient = int(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(ascii_letters, quotient + remainder) + random(digits, quotient) + random(punctuation, quotient)
|
||||
chars = list(chars)
|
||||
shuffle(chars)
|
||||
return "".join(chars)
|
||||
i = i - len(ctbi)
|
||||
quotient = int(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(ascii_letters, quotient + remainder)
|
||||
+ random(digits, quotient)
|
||||
+ random(punctuation, quotient)
|
||||
)
|
||||
chars = list(chars)
|
||||
shuffle(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):
|
||||
return "".join(choice(ctbi) for x in range(i))
|
||||
|
||||
|
||||
return "".join(choice(ctbi) for x in range(i))
|
||||
|
||||
|
||||
def random_number(ctbi, i):
|
||||
pass # Put your code here...
|
||||
|
||||
|
@ -56,9 +62,13 @@ def random_characters(ctbi, i):
|
|||
|
||||
def main():
|
||||
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("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.]")
|
||||
|
||||
|
||||
|
|
|
@ -27,11 +27,11 @@ def solution(n):
|
|||
44
|
||||
"""
|
||||
|
||||
a = [0,1]
|
||||
a = [0, 1]
|
||||
i = 0
|
||||
while a[i] <= n:
|
||||
a.append(a[i] + a[i+1])
|
||||
if a[i+2] > n:
|
||||
a.append(a[i] + a[i + 1])
|
||||
if a[i + 2] > n:
|
||||
break
|
||||
i += 1
|
||||
sum = 0
|
||||
|
|
|
@ -1,12 +1,14 @@
|
|||
#run using python fibonacci_search.py -v
|
||||
# run using python fibonacci_search.py -v
|
||||
|
||||
'''
|
||||
"""
|
||||
@params
|
||||
arr: input array
|
||||
val: the value to be searched
|
||||
output: the index of element in the array or -1 if not found
|
||||
return 0 if input array is empty
|
||||
'''
|
||||
"""
|
||||
|
||||
|
||||
def fibonacci_search(arr, val):
|
||||
|
||||
"""
|
||||
|
@ -22,29 +24,31 @@ def fibonacci_search(arr, val):
|
|||
fibNext = fib_N_1 + fib_N_2
|
||||
length = len(arr)
|
||||
if length == 0:
|
||||
return 0
|
||||
while (fibNext < len(arr)):
|
||||
return 0
|
||||
while fibNext < len(arr):
|
||||
fib_N_2 = fib_N_1
|
||||
fib_N_1 = fibNext
|
||||
fibNext = fib_N_1 + fib_N_2
|
||||
index = -1;
|
||||
while (fibNext > 1):
|
||||
i = min(index + fib_N_2, (length-1))
|
||||
if (arr[i] < val):
|
||||
index = -1
|
||||
while fibNext > 1:
|
||||
i = min(index + fib_N_2, (length - 1))
|
||||
if arr[i] < val:
|
||||
fibNext = fib_N_1
|
||||
fib_N_1 = fib_N_2
|
||||
fib_N_2 = fibNext - fib_N_1
|
||||
index = i
|
||||
elif (arr[i] > val):
|
||||
elif arr[i] > val:
|
||||
fibNext = fib_N_2
|
||||
fib_N_1 = fib_N_1 - fib_N_2
|
||||
fib_N_2 = fibNext - fib_N_1
|
||||
else :
|
||||
else:
|
||||
return i
|
||||
if (fib_N_1 and index < length-1) and (arr[index+1] == val):
|
||||
return index+1;
|
||||
if (fib_N_1 and index < length - 1) and (arr[index + 1] == val):
|
||||
return index + 1
|
||||
return -1
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
import doctest
|
||||
|
||||
doctest.testmod()
|
||||
|
|
|
@ -29,12 +29,13 @@ def bubble_sort(collection):
|
|||
swapped = True
|
||||
collection[j], collection[j + 1] = collection[j + 1], collection[j]
|
||||
if not swapped:
|
||||
break # Stop iteration if the collection is sorted.
|
||||
break # Stop iteration if the collection is sorted.
|
||||
return collection
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
import time
|
||||
|
||||
user_input = input("Enter numbers separated by a comma:").strip()
|
||||
unsorted = [int(item) for item in user_input.split(",")]
|
||||
start = time.process_time()
|
||||
|
|
|
@ -1,4 +1,4 @@
|
|||
def double_sort(lst):
|
||||
def double_sort(lst):
|
||||
"""this sorting algorithm sorts an array using the principle of bubble sort ,
|
||||
but does it both from left to right and right to left ,
|
||||
hence i decided to call it "double sort"
|
||||
|
@ -14,21 +14,29 @@ def double_sort(lst):
|
|||
>>> double_sort([-3, 10, 16, -42, 29]) == sorted([-3, 10, 16, -42, 29])
|
||||
True
|
||||
"""
|
||||
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 j in range(0,no_of_elements-1):
|
||||
if (lst[j+1]<lst[j]): # applying bubble sort algorithm from left to right (or forwards)
|
||||
temp=lst[j+1]
|
||||
lst[j+1]=lst[j]
|
||||
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
|
||||
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 j in range(0, no_of_elements - 1):
|
||||
if (
|
||||
lst[j + 1] < lst[j]
|
||||
): # applying bubble sort algorithm from left to right (or forwards)
|
||||
temp = lst[j + 1]
|
||||
lst[j + 1] = lst[j]
|
||||
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
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
print("enter the list to be sorted")
|
||||
lst = [int(x) for x in input().split()] # inputing elements of the list in one line
|
||||
sorted_lst=double_sort(lst)
|
||||
lst = [int(x) for x in input().split()] # inputing elements of the list in one line
|
||||
sorted_lst = double_sort(lst)
|
||||
print("the sorted list is")
|
||||
print(sorted_lst)
|
||||
|
|
Loading…
Reference in New Issue
Block a user