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:
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")

View File

@ -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,6 +60,7 @@ 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.
@ -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
@ -106,6 +108,7 @@ def erase(root: Node, value: int) -> Node:
_, right = split(right, value)
return merge(left, right)
def inorder(root: Node):
"""
Just recursive print of a tree
@ -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()

View File

@ -23,6 +23,7 @@ def merge(a,b,m,e):
k += 1
return a
def mergesort(a, b, e):
"""
>>> mergesort([3,2,1],0,2)
@ -40,6 +41,8 @@ def mergesort(a,b,e):
merge(a, b, m, e)
return a
if __name__ == "__main__":
import doctest
doctest.testmod()

View File

@ -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")

View File

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

View File

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

View File

@ -8,10 +8,12 @@ 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)

View File

@ -1,5 +1,6 @@
INF = float("inf")
class Dinic:
def __init__(self, n):
self.lvl = [0] * n
@ -7,11 +8,12 @@ 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])
@ -58,36 +60,35 @@ class Dinic:
return flow
# 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)
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)
'''
"""
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)
'''
"""
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)
# Now we can know that is the maximum 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")
return None
class Test_Decision_Tree:
"""Decision Tres test class
"""
@ -139,14 +140,11 @@ 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)
def main():
"""
In this demonstration we're generating a sample data set from the sin function in numpy.

View File

@ -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
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,13 +27,15 @@ 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

View File

@ -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__":

View File

@ -38,4 +38,3 @@ if __name__ == "__main__":
import doctest
doctest.testmod()

View File

@ -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:

View File

@ -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")

View File

@ -1,5 +1,6 @@
""" Multiply two numbers using Karatsuba algorithm """
def karatsuba(a, b):
"""
>>> karatsuba(15463, 23489) == 15463 * 23489
@ -8,7 +9,7 @@ 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
@ -20,7 +21,7 @@ def karatsuba(a, b):
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():

View File

@ -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):
"""
@ -21,7 +22,6 @@ def prime_sieve_eratosthenes(num):
2 3 5 7 11 13 17 19
"""
primes = [True for i in range(num + 1)]
p = 2
@ -35,6 +35,7 @@ def prime_sieve_eratosthenes(num):
if primes[prime]:
print(prime, end=" ")
if __name__ == "__main__":
num = int(input())

View File

@ -57,8 +57,7 @@ def qr_householder(A):
# construct the Householder matrix
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
@ -68,4 +67,5 @@ def qr_householder(A):
if __name__ == "__main__":
import doctest
doctest.testmod()

View File

@ -7,6 +7,7 @@ single person, one at a time"""
# 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]
@ -32,6 +33,7 @@ def printMaxActivities(start, finish):
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]

View File

@ -2,10 +2,10 @@
# 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="")
@ -16,10 +16,10 @@ def floyd(n):
# 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="")
@ -27,12 +27,13 @@ def reverse_floyd(n):
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
@ -44,7 +45,7 @@ if __name__ == "__main__":
print(r"| /\ | |- | |- |--| |\ /| |-")
print(r"|/ \| |- |_ |_ |__| | \/ | |_")
K = 1
while(K):
while K:
user_number = int(input("enter the number and , and see the magic : "))
print()
pretty_print(user_number)

View File

@ -31,13 +31,19 @@ def alternative_password_generator(ctbi, i):
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 = (
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
def random(ctbi, i):
return "".join(choice(ctbi) for x in range(i))
@ -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.]")

View File

@ -1,12 +1,14 @@
# 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):
"""
@ -23,28 +25,30 @@ def fibonacci_search(arr, val):
length = len(arr)
if length == 0:
return 0
while (fibNext < len(arr)):
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):
index = -1
while fibNext > 1:
i = min(index + fib_N_2, (length - 1))
if (arr[i] < val):
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:
return i
if (fib_N_1 and index < length - 1) and (arr[index + 1] == val):
return index+1;
return index + 1
return -1
if __name__ == "__main__":
import doctest
doctest.testmod()

View File

@ -35,6 +35,7 @@ def bubble_sort(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()

View File

@ -15,17 +15,25 @@ def double_sort(lst):
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 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)
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)
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