From de777f55e54a8bc410aaee85e2b470169e9f5ae7 Mon Sep 17 00:00:00 2001 From: cclauss Date: Tue, 6 Aug 2019 09:32:38 +0200 Subject: [PATCH 1/2] print() is a function just like every other function --- arithmetic_analysis/newton_raphson_method.py | 16 ++-- ciphers/caesar_cipher.py | 6 +- ciphers/morse_code_implementation.py | 4 +- ciphers/trafid_cipher.py | 14 +-- ciphers/xor_cipher.py | 18 ++-- data_structures/binary_tree/fenwick_tree.py | 12 +-- .../binary_tree/lazy_segment_tree.py | 18 ++-- data_structures/binary_tree/segment_tree.py | 20 ++-- data_structures/queue/double_ended_queue.py | 42 ++++----- data_structures/stacks/stock_span_problem.py | 92 +++++++++---------- machine_learning/logistic_regression.py | 10 +- maths/Quadratic Equations(Complexes Numbers) | 8 +- other/fischer_yates_shuffle.py | 6 +- 13 files changed, 133 insertions(+), 133 deletions(-) diff --git a/arithmetic_analysis/newton_raphson_method.py b/arithmetic_analysis/newton_raphson_method.py index 569f96476afc..bb6fdd2193ec 100644 --- a/arithmetic_analysis/newton_raphson_method.py +++ b/arithmetic_analysis/newton_raphson_method.py @@ -8,25 +8,25 @@ def NewtonRaphson(func, a): ''' Finds root from the point 'a' onwards by Newton-Raphson method ''' while True: c = Decimal(a) - ( Decimal(eval(func)) / Decimal(eval(str(diff(func)))) ) - + a = c # This number dictates the accuracy of the answer if abs(eval(func)) < 10**-15: return c - + # Let's Execute if __name__ == '__main__': # Find root of trigonometric function # Find value of pi - print ('sin(x) = 0', NewtonRaphson('sin(x)', 2)) - + print('sin(x) = 0', NewtonRaphson('sin(x)', 2)) + # Find root of polynomial - print ('x**2 - 5*x +2 = 0', NewtonRaphson('x**2 - 5*x +2', 0.4)) - + print('x**2 - 5*x +2 = 0', NewtonRaphson('x**2 - 5*x +2', 0.4)) + # Find Square Root of 5 - print ('x**2 - 5 = 0', NewtonRaphson('x**2 - 5', 0.1)) + print('x**2 - 5 = 0', NewtonRaphson('x**2 - 5', 0.1)) # Exponential Roots - print ('exp(x) - 1 = 0', NewtonRaphson('exp(x) - 1', 0)) + print('exp(x) - 1 = 0', NewtonRaphson('exp(x) - 1', 0)) diff --git a/ciphers/caesar_cipher.py b/ciphers/caesar_cipher.py index 872b5d8195c1..95d65d404266 100644 --- a/ciphers/caesar_cipher.py +++ b/ciphers/caesar_cipher.py @@ -41,12 +41,12 @@ def main(): print("4.Quit") choice = input("What would you like to do?: ") if choice not in ['1', '2', '3', '4']: - print ("Invalid choice, please enter a valid choice") + print("Invalid choice, please enter a valid choice") elif choice == '1': strng = input("Please enter the string to be encrypted: ") key = int(input("Please enter off-set between 1-94: ")) if key in range(1, 95): - print (encrypt(strng.lower(), key)) + print(encrypt(strng.lower(), key)) elif choice == '2': strng = input("Please enter the string to be decrypted: ") key = int(input("Please enter off-set between 1-94: ")) @@ -57,7 +57,7 @@ def main(): brute_force(strng) main() elif choice == '4': - print ("Goodbye.") + print("Goodbye.") break diff --git a/ciphers/morse_code_implementation.py b/ciphers/morse_code_implementation.py index 7b2d0a94b24b..5d0e7b2779b1 100644 --- a/ciphers/morse_code_implementation.py +++ b/ciphers/morse_code_implementation.py @@ -71,11 +71,11 @@ def decrypt(message): def main(): message = "Morse code here" result = encrypt(message.upper()) - print (result) + print(result) message = result result = decrypt(message) - print (result) + print(result) if __name__ == '__main__': diff --git a/ciphers/trafid_cipher.py b/ciphers/trafid_cipher.py index 0453272f26a0..53f4d288bfe2 100644 --- a/ciphers/trafid_cipher.py +++ b/ciphers/trafid_cipher.py @@ -3,7 +3,7 @@ def __encryptPart(messagePart, character2Number): one, two, three = "", "", "" tmp = [] - + for character in messagePart: tmp.append(character2Number[character]) @@ -11,7 +11,7 @@ def __encryptPart(messagePart, character2Number): one += each[0] two += each[1] three += each[2] - + return one+two+three def __decryptPart(messagePart, character2Number): @@ -25,7 +25,7 @@ def __decryptPart(messagePart, character2Number): tmp += digit if len(tmp) == len(messagePart): result.append(tmp) - tmp = "" + tmp = "" return result[0], result[1], result[2] @@ -48,7 +48,7 @@ def __prepare(message, alphabet): for letter, number in zip(alphabet, numbers): character2Number[letter] = number number2Character[number] = letter - + return message, alphabet, character2Number, number2Character def encryptMessage(message, alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ.", period=5): @@ -57,7 +57,7 @@ def encryptMessage(message, alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ.", period=5): for i in range(0, len(message)+1, period): encrypted_numeric += __encryptPart(message[i:i+period], character2Number) - + for i in range(0, len(encrypted_numeric), 3): encrypted += number2Character[encrypted_numeric[i:i+3]] @@ -70,7 +70,7 @@ def decryptMessage(message, alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ.", period=5): for i in range(0, len(message)+1, period): a,b,c = __decryptPart(message[i:i+period], character2Number) - + for j in range(0, len(a)): decrypted_numeric.append(a[j]+b[j]+c[j]) @@ -83,4 +83,4 @@ def decryptMessage(message, alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ.", period=5): msg = "DEFEND THE EAST WALL OF THE CASTLE." encrypted = encryptMessage(msg,"EPSDUCVWYM.ZLKXNBTFGORIJHAQ") decrypted = decryptMessage(encrypted, "EPSDUCVWYM.ZLKXNBTFGORIJHAQ") - print ("Encrypted: {}\nDecrypted: {}".format(encrypted, decrypted)) \ No newline at end of file + print("Encrypted: {}\nDecrypted: {}".format(encrypted, decrypted)) diff --git a/ciphers/xor_cipher.py b/ciphers/xor_cipher.py index 727fac3b0703..8bb94212c15a 100644 --- a/ciphers/xor_cipher.py +++ b/ciphers/xor_cipher.py @@ -122,7 +122,7 @@ def decrypt_string(self,content,key = 0): # This will be returned ans = "" - + for ch in content: ans += chr(ord(ch) ^ key) @@ -188,22 +188,22 @@ def decrypt_file(self,file, key): # key = 67 # # test enrcypt -# print crypt.encrypt("hallo welt",key) +# print(crypt.encrypt("hallo welt",key)) # # test decrypt -# print crypt.decrypt(crypt.encrypt("hallo welt",key), key) +# print(crypt.decrypt(crypt.encrypt("hallo welt",key), key)) # # test encrypt_string -# print crypt.encrypt_string("hallo welt",key) +# print(crypt.encrypt_string("hallo welt",key)) # # test decrypt_string -# print crypt.decrypt_string(crypt.encrypt_string("hallo welt",key),key) +# print(crypt.decrypt_string(crypt.encrypt_string("hallo welt",key),key)) # if (crypt.encrypt_file("test.txt",key)): -# print "encrypt successful" +# print("encrypt successful") # else: -# print "encrypt unsuccessful" +# print("encrypt unsuccessful") # if (crypt.decrypt_file("encrypt.out",key)): -# print "decrypt successful" +# print("decrypt successful") # else: -# print "decrypt unsuccessful" \ No newline at end of file +# print("decrypt unsuccessful") diff --git a/data_structures/binary_tree/fenwick_tree.py b/data_structures/binary_tree/fenwick_tree.py index f429161c8c36..ef984082d9e8 100644 --- a/data_structures/binary_tree/fenwick_tree.py +++ b/data_structures/binary_tree/fenwick_tree.py @@ -16,14 +16,14 @@ def query(self, i): # query cumulative data from index 0 to i in O(lg N) ret += self.ft[i] i -= i & (-i) return ret - + if __name__ == '__main__': f = FenwickTree(100) f.update(1,20) f.update(4,4) - print (f.query(1)) - print (f.query(3)) - print (f.query(4)) + print(f.query(1)) + print(f.query(3)) + print(f.query(4)) f.update(2,-5) - print (f.query(1)) - print (f.query(3)) + print(f.query(1)) + print(f.query(3)) diff --git a/data_structures/binary_tree/lazy_segment_tree.py b/data_structures/binary_tree/lazy_segment_tree.py index 9b14b24e81fa..215399976dd3 100644 --- a/data_structures/binary_tree/lazy_segment_tree.py +++ b/data_structures/binary_tree/lazy_segment_tree.py @@ -2,13 +2,13 @@ import math class SegmentTree: - + def __init__(self, N): self.N = N self.st = [0 for i in range(0,4*N)] # approximate the overall size of segment tree with array N self.lazy = [0 for i in range(0,4*N)] # create array to store lazy update self.flag = [0 for i in range(0,4*N)] # flag for lazy update - + def left(self, idx): return idx*2 @@ -34,7 +34,7 @@ def update(self, idx, l, r, a, b, val): # update(1, 1, N, a, b, v) for update va self.lazy[self.right(idx)] = self.lazy[idx] self.flag[self.left(idx)] = True self.flag[self.right(idx)] = True - + if r < a or l > b: return True if l >= a and r <= b : @@ -74,18 +74,18 @@ def showData(self): showList = [] for i in range(1,N+1): showList += [self.query(1, 1, self.N, i, i)] - print (showList) - + print(showList) + if __name__ == '__main__': A = [1,2,-4,7,3,-5,6,11,-20,9,14,15,5,2,-8] N = 15 segt = SegmentTree(N) segt.build(1,1,N,A) - print (segt.query(1,1,N,4,6)) - print (segt.query(1,1,N,7,11)) - print (segt.query(1,1,N,7,12)) + print(segt.query(1,1,N,4,6)) + print(segt.query(1,1,N,7,11)) + print(segt.query(1,1,N,7,12)) segt.update(1,1,N,1,3,111) - print (segt.query(1,1,N,1,15)) + print(segt.query(1,1,N,1,15)) segt.update(1,1,N,7,8,235) segt.showData() diff --git a/data_structures/binary_tree/segment_tree.py b/data_structures/binary_tree/segment_tree.py index 001bf999f391..7e61198ca59c 100644 --- a/data_structures/binary_tree/segment_tree.py +++ b/data_structures/binary_tree/segment_tree.py @@ -2,12 +2,12 @@ import math class SegmentTree: - + def __init__(self, A): self.N = len(A) self.st = [0] * (4 * self.N) # approximate the overall size of segment tree with array N self.build(1, 0, self.N - 1) - + def left(self, idx): return idx * 2 @@ -22,10 +22,10 @@ def build(self, idx, l, r): self.build(self.left(idx), l, mid) self.build(self.right(idx), mid + 1, r) self.st[idx] = max(self.st[self.left(idx)] , self.st[self.right(idx)]) - + def update(self, a, b, val): return self.update_recursive(1, 0, self.N - 1, a - 1, b - 1, val) - + def update_recursive(self, idx, l, r, a, b, val): # update(1, 1, N, a, b, v) for update val v to [a,b] if r < a or l > b: return True @@ -55,17 +55,17 @@ def showData(self): showList = [] for i in range(1,N+1): showList += [self.query(i, i)] - print (showList) - + print(showList) + if __name__ == '__main__': A = [1,2,-4,7,3,-5,6,11,-20,9,14,15,5,2,-8] N = 15 segt = SegmentTree(A) - print (segt.query(4, 6)) - print (segt.query(7, 11)) - print (segt.query(7, 12)) + print(segt.query(4, 6)) + print(segt.query(7, 11)) + print(segt.query(7, 12)) segt.update(1,3,111) - print (segt.query(1, 15)) + print(segt.query(1, 15)) segt.update(7,8,235) segt.showData() diff --git a/data_structures/queue/double_ended_queue.py b/data_structures/queue/double_ended_queue.py index fdee64eb6ae0..838bf2f4bc36 100644 --- a/data_structures/queue/double_ended_queue.py +++ b/data_structures/queue/double_ended_queue.py @@ -1,40 +1,40 @@ from __future__ import print_function -# Python code to demonstrate working of +# Python code to demonstrate working of # extend(), extendleft(), rotate(), reverse() - + # importing "collections" for deque operations import collections - + # initializing deque de = collections.deque([1, 2, 3,]) - -# using extend() to add numbers to right end + +# using extend() to add numbers to right end # adds 4,5,6 to right end de.extend([4,5,6]) - + # printing modified deque -print ("The deque after extending deque at end is : ") -print (de) - -# using extendleft() to add numbers to left end +print("The deque after extending deque at end is : ") +print(de) + +# using extendleft() to add numbers to left end # adds 7,8,9 to right end de.extendleft([7,8,9]) - + # printing modified deque -print ("The deque after extending deque at beginning is : ") -print (de) - +print("The deque after extending deque at beginning is : ") +print(de) + # using rotate() to rotate the deque # rotates by 3 to left de.rotate(-3) - + # printing modified deque -print ("The deque after rotating deque is : ") -print (de) - +print("The deque after rotating deque is : ") +print(de) + # using reverse() to reverse the deque de.reverse() - + # printing modified deque -print ("The deque after reversing deque is : ") -print (de) +print("The deque after reversing deque is : ") +print(de) diff --git a/data_structures/stacks/stock_span_problem.py b/data_structures/stacks/stock_span_problem.py index 9628864edd10..e9afebc193b6 100644 --- a/data_structures/stacks/stock_span_problem.py +++ b/data_structures/stacks/stock_span_problem.py @@ -1,52 +1,52 @@ ''' -The stock span problem is a financial problem where we have a series of n daily +The stock span problem is a financial problem where we have a series of n daily price quotes for a stock and we need to calculate span of stock's price for all n days. -The span Si of the stock's price on a given day i is defined as the maximum -number of consecutive days just before the given day, for which the price of the stock +The span Si of the stock's price on a given day i is defined as the maximum +number of consecutive days just before the given day, for which the price of the stock on the current day is less than or equal to its price on the given day. ''' from __future__ import print_function -def calculateSpan(price, S): - - n = len(price) - # Create a stack and push index of fist element to it - st = [] - st.append(0) - - # Span value of first element is always 1 - S[0] = 1 - - # Calculate span values for rest of the elements - for i in range(1, n): - - # Pop elements from stack whlie stack is not - # empty and top of stack is smaller than price[i] - while( len(st) > 0 and price[st[0]] <= price[i]): - st.pop() - - # If stack becomes empty, then price[i] is greater - # than all elements on left of it, i.e. price[0], - # price[1], ..price[i-1]. Else the price[i] is - # greater than elements after top of stack - S[i] = i+1 if len(st) <= 0 else (i - st[0]) - - # Push this element to stack - st.append(i) - - -# A utility function to print elements of array -def printArray(arr, n): - for i in range(0,n): - print (arr[i],end =" ") - - -# Driver program to test above function -price = [10, 4, 5, 90, 120, 80] -S = [0 for i in range(len(price)+1)] - -# Fill the span values in array S[] -calculateSpan(price, S) - -# Print the calculated span values -printArray(S, len(price)) +def calculateSpan(price, S): + + n = len(price) + # Create a stack and push index of fist element to it + st = [] + st.append(0) + + # Span value of first element is always 1 + S[0] = 1 + + # Calculate span values for rest of the elements + for i in range(1, n): + + # Pop elements from stack whlie stack is not + # empty and top of stack is smaller than price[i] + while( len(st) > 0 and price[st[0]] <= price[i]): + st.pop() + + # If stack becomes empty, then price[i] is greater + # than all elements on left of it, i.e. price[0], + # price[1], ..price[i-1]. Else the price[i] is + # greater than elements after top of stack + S[i] = i+1 if len(st) <= 0 else (i - st[0]) + + # Push this element to stack + st.append(i) + + +# A utility function to print elements of array +def printArray(arr, n): + for i in range(0,n): + print(arr[i],end =" ") + + +# Driver program to test above function +price = [10, 4, 5, 90, 120, 80] +S = [0 for i in range(len(price)+1)] + +# Fill the span values in array S[] +calculateSpan(price, S) + +# Print the calculated span values +printArray(S, len(price)) diff --git a/machine_learning/logistic_regression.py b/machine_learning/logistic_regression.py index 9a60831862da..853de7896af1 100644 --- a/machine_learning/logistic_regression.py +++ b/machine_learning/logistic_regression.py @@ -9,7 +9,7 @@ # importing all the required libraries -''' Implementing logistic regression for classification problem +''' Implementing logistic regression for classification problem Helpful resources : 1.Coursera ML course 2.https://medium.com/@martinpella/logistic-regression-from-scratch-in-python-124c5636b8ac''' import numpy as np @@ -63,10 +63,10 @@ def logistic_reg( if step % 10000 == 0: print(log_likelihood(X,y,weights)) # Print log-likelihood every so often return weights - + if iterations == max_iterations: - print ('Maximum iterations exceeded!') - print ('Minimal cost function J=', J) + print('Maximum iterations exceeded!') + print('Minimal cost function J=', J) converged = True return theta @@ -79,7 +79,7 @@ def logistic_reg( alpha = 0.1 theta = logistic_reg(alpha,X,y,max_iterations=70000,num_steps=30000) - print (theta) + print(theta) def predict_prob(X): diff --git a/maths/Quadratic Equations(Complexes Numbers) b/maths/Quadratic Equations(Complexes Numbers) index 8e8e78fec68f..2063a59c4aab 100644 --- a/maths/Quadratic Equations(Complexes Numbers) +++ b/maths/Quadratic Equations(Complexes Numbers) @@ -13,7 +13,7 @@ def QuadraticEquation(a,b,c): if Delta >= 0: Solution1 = (-b + math.sqrt(Delta))/(2*a) Solution2 = (-b - math.sqrt(Delta))/(2*a) - print ("The equation solutions are: ", Solution1," and ", Solution2) + print("The equation solutions are: ", Solution1," and ", Solution2) else: """ Treats cases of Complexes Solutions(i = imaginary unit) @@ -26,7 +26,7 @@ def QuadraticEquation(a,b,c): print("The equation solutions are: (",b,"+",math.sqrt(-Delta),"*i)/2 and (",b,"+",math.sqrt(-Delta),"*i/",2*a) if b == 0: print("The equation solutions are: (",math.sqrt(-Delta),"*i)/2 and ",math.sqrt(-Delta),"*i)/", 2*a) - else: + else: print("Error. Please, coeficient 'a' must not be zero for quadratic equations.") def main(): a = 5 @@ -34,7 +34,7 @@ def main(): c = 1 QuadraticEquation(a,b,c) # The equation solutions are: -0.2 and -1.0 - - + + if __name__ == '__main__': main() diff --git a/other/fischer_yates_shuffle.py b/other/fischer_yates_shuffle.py index d87792f45558..bc2b136344c7 100644 --- a/other/fischer_yates_shuffle.py +++ b/other/fischer_yates_shuffle.py @@ -17,6 +17,6 @@ def FYshuffle(LIST): if __name__ == '__main__': integers = [0,1,2,3,4,5,6,7] strings = ['python', 'says', 'hello', '!'] - print ('Fisher-Yates Shuffle:') - print ('List',integers, strings) - print ('FY Shuffle',FYshuffle(integers), FYshuffle(strings)) + print('Fisher-Yates Shuffle:') + print('List',integers, strings) + print('FY Shuffle',FYshuffle(integers), FYshuffle(strings)) From 313183d19d09e6a8464d01b7f0f51828829f7a7f Mon Sep 17 00:00:00 2001 From: Harshil Date: Tue, 6 Aug 2019 12:12:48 +0200 Subject: [PATCH 2/2] Update and rename Quadratic Equations(Complexes Numbers) to quadratic_equations_complex_numbers.py --- ...Complexes Numbers) => quadratic_equations_complex_numbers.py} | 1 - 1 file changed, 1 deletion(-) rename maths/{Quadratic Equations(Complexes Numbers) => quadratic_equations_complex_numbers.py} (97%) diff --git a/maths/Quadratic Equations(Complexes Numbers) b/maths/quadratic_equations_complex_numbers.py similarity index 97% rename from maths/Quadratic Equations(Complexes Numbers) rename to maths/quadratic_equations_complex_numbers.py index 2063a59c4aab..c3842fee5f96 100644 --- a/maths/Quadratic Equations(Complexes Numbers) +++ b/maths/quadratic_equations_complex_numbers.py @@ -1,4 +1,3 @@ -from __future__ import print_function import math def QuadraticEquation(a,b,c):