diff --git a/File_Transfer_Protocol/ftp_send_receive.py b/File_Transfer_Protocol/ftp_send_receive.py index ba1280048..d4919158a 100644 --- a/File_Transfer_Protocol/ftp_send_receive.py +++ b/File_Transfer_Protocol/ftp_send_receive.py @@ -1,34 +1,34 @@ - """ - File transfer protocol used to send and receive files using FTP server. - Use credentials to provide access to the FTP client +""" + File transfer protocol used to send and receive files using FTP server. + Use credentials to provide access to the FTP client - Note: Do not use root username & password for security reasons - Create a seperate user and provide access to a home directory of the user - Use login id and password of the user created - cwd here stands for current working directory - """ + Note: Do not use root username & password for security reasons + Create a seperate user and provide access to a home directory of the user + Use login id and password of the user created + cwd here stands for current working directory +""" from ftplib import FTP -ftp = FTP('xxx.xxx.x.x') """ Enter the ip address or the domain name here """ +ftp = FTP('xxx.xxx.x.x') # Enter the ip address or the domain name here ftp.login(user='username', passwd='password') ftp.cwd('/Enter the directory here/') - """ - The file which will be received via the FTP server - Enter the location of the file where the file is received - """ +""" + The file which will be received via the FTP server + Enter the location of the file where the file is received +""" def ReceiveFile(): FileName = 'example.txt' """ Enter the location of the file """ LocalFile = open(FileName, 'wb') - ftp.retrbinary('RETR ' + filename, LocalFile.write, 1024) + ftp.retrbinary('RETR ' + FileName, LocalFile.write, 1024) ftp.quit() LocalFile.close() - """ - The file which will be sent via the FTP server - The file send will be send to the current working directory - """ +""" + The file which will be sent via the FTP server + The file send will be send to the current working directory +""" def SendFile(): FileName = 'example.txt' """ Enter the name of the file """ diff --git a/Graphs/a_star.py b/Graphs/a_star.py index 2ca9476e5..584222e6f 100644 --- a/Graphs/a_star.py +++ b/Graphs/a_star.py @@ -1,3 +1,4 @@ +from __future__ import print_function grid = [[0, 1, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0],#0 are free path whereas 1's are obstacles @@ -80,7 +81,7 @@ def search(grid,init,goal,cost,heuristic): y = goal[1] invpath.append([x, y])#we get the reverse path from here while x != init[0] or y != init[1]: - x2 = x - delta[action[x][y]][0] + x2 = x - delta[action[x][y]][0] y2 = y - delta[action[x][y]][1] x = x2 y = y2 @@ -89,13 +90,13 @@ def search(grid,init,goal,cost,heuristic): path = [] for i in range(len(invpath)): path.append(invpath[len(invpath) - 1 - i]) - print "ACTION MAP" + print("ACTION MAP") for i in range(len(action)): - print action[i] + print(action[i]) return path a = search(grid,init,goal,cost,heuristic) for i in range(len(a)): - print a[i] + print(a[i]) diff --git a/Graphs/basic-graphs.py b/Graphs/basic-graphs.py index fc78e5652..c18574fa9 100644 --- a/Graphs/basic-graphs.py +++ b/Graphs/basic-graphs.py @@ -1,3 +1,15 @@ +from __future__ import print_function + +try: + raw_input # Python 2 +except NameError: + raw_input = input # Python 3 + +try: + xrange # Python 2 +except NameError: + xrange = range # Python 3 + # Accept No. of Nodes and edges n, m = map(int, raw_input().split(" ")) @@ -48,7 +60,7 @@ for _ in xrange(m): def dfs(G, s): vis, S = set([s]), [s] - print s + print(s) while S: flag = 0 for i in G[S[-1]]: @@ -56,7 +68,7 @@ def dfs(G, s): S.append(i) vis.add(i) flag = 1 - print i + print(i) break if not flag: S.pop() @@ -76,14 +88,14 @@ from collections import deque def bfs(G, s): vis, Q = set([s]), deque([s]) - print s + print(s) while Q: u = Q.popleft() for v in G[u]: if v not in vis: vis.add(v) Q.append(v) - print v + print(v) """ @@ -116,7 +128,7 @@ def dijk(G, s): path[v[0]] = u for i in dist: if i != s: - print dist[i] + print(dist[i]) """ @@ -140,7 +152,7 @@ def topo(G, ind=None, Q=[1]): if len(Q) == 0: return v = Q.popleft() - print v + print(v) for w in G[v]: ind[w] -= 1 if ind[w] == 0: @@ -175,7 +187,8 @@ def adjm(): """ -def floy((A, n)): +def floy(xxx_todo_changeme): + (A, n) = xxx_todo_changeme dist = list(A) path = [[0] * n for i in xrange(n)] for k in xrange(n): @@ -184,7 +197,7 @@ def floy((A, n)): if dist[i][j] > dist[i][k] + dist[k][j]: dist[i][j] = dist[i][k] + dist[k][j] path[i][k] = k - print dist + print(dist) """ @@ -246,14 +259,15 @@ def edglist(): """ -def krusk((E, n)): +def krusk(xxx_todo_changeme1): # Sort edges on the basis of distance + (E, n) = xxx_todo_changeme1 E.sort(reverse=True, key=lambda x: x[2]) s = [set([i]) for i in range(1, n + 1)] while True: if len(s) == 1: break - print s + print(s) x = E.pop() for i in xrange(len(s)): if x[0] in s[i]: diff --git a/Graphs/minimum_spanning_tree_kruskal.py b/Graphs/minimum_spanning_tree_kruskal.py index d26eb70b2..81d64f421 100644 --- a/Graphs/minimum_spanning_tree_kruskal.py +++ b/Graphs/minimum_spanning_tree_kruskal.py @@ -1,3 +1,4 @@ +from __future__ import print_function num_nodes, num_edges = list(map(int,input().split())) edges = [] diff --git a/Graphs/scc_kosaraju.py b/Graphs/scc_kosaraju.py index 09a05e981..1f13ebaba 100644 --- a/Graphs/scc_kosaraju.py +++ b/Graphs/scc_kosaraju.py @@ -1,3 +1,4 @@ +from __future__ import print_function # n - no of nodes, m - no of edges n, m = list(map(int,input().split())) diff --git a/Multi_Hueristic_Astar.py b/Multi_Hueristic_Astar.py index 03652d35a..7fbd2ff04 100644 --- a/Multi_Hueristic_Astar.py +++ b/Multi_Hueristic_Astar.py @@ -1,8 +1,14 @@ +from __future__ import print_function import heapq import numpy as np import math import copy +try: + xrange # Python 2 +except NameError: + xrange = range # Python 3 + class PriorityQueue: def __init__(self): @@ -95,22 +101,22 @@ def do_something(back_pointer, goal, start): for i in xrange(n): for j in range(n): if (i, j) == (0, n-1): - print grid[i][j], - print "<-- End position", + print(grid[i][j], end=' ') + print("<-- End position", end=' ') else: - print grid[i][j], - print + print(grid[i][j], end=' ') + print() print("^") print("Start position") - print + print() print("# is an obstacle") print("- is the path taken by algorithm") print("PATH TAKEN BY THE ALGORITHM IS:-") x = back_pointer[goal] while x != start: - print x, + print(x, end=' ') x = back_pointer[x] - print x + print(x) quit() def valid(p): @@ -239,24 +245,24 @@ def multi_a_star(start, goal, n_hueristic): expand_state(get_s, 0, visited, g_function, close_list_anchor, close_list_inad, open_list, back_pointer) close_list_anchor.append(get_s) print("No path found to goal") - print + print() for i in range(n-1,-1, -1): for j in range(n): if (j, i) in blocks: - print '#', + print('#', end=' ') elif (j, i) in back_pointer: if (j, i) == (n-1, n-1): - print '*', + print('*', end=' ') else: - print '-', + print('-', end=' ') else: - print '*', + print('*', end=' ') if (j, i) == (n-1, n-1): - print '<-- End position', - print + print('<-- End position', end=' ') + print() print("^") print("Start position") - print + print() print("# is an obstacle") print("- is the path taken by algorithm") -multi_a_star(start, goal, n_hueristic) \ No newline at end of file +multi_a_star(start, goal, n_hueristic) diff --git a/Neural_Network/convolution_neural_network.py b/Neural_Network/convolution_neural_network.py index d8ab0d2e5..0dca2bc48 100644 --- a/Neural_Network/convolution_neural_network.py +++ b/Neural_Network/convolution_neural_network.py @@ -15,6 +15,7 @@ Date: 2017.9.20 - - - - - -- - - - - - - - - - - - - - - - - - - - - - - ''' +from __future__ import print_function import numpy as np import matplotlib.pyplot as plt @@ -192,8 +193,8 @@ class CNN(): def trian(self,patterns,datas_train, datas_teach, n_repeat, error_accuracy,draw_e = bool): #model traning print('----------------------Start Training-------------------------') - print(' - - Shape: Train_Data ',np.shape(datas_train)) - print(' - - Shape: Teach_Data ',np.shape(datas_teach)) + print((' - - Shape: Train_Data ',np.shape(datas_train))) + print((' - - Shape: Teach_Data ',np.shape(datas_teach))) rp = 0 all_mse = [] mse = 10000 @@ -262,7 +263,7 @@ class CNN(): plt.grid(True, alpha=0.5) plt.show() print('------------------Training Complished---------------------') - print(' - - Training epoch: ', rp, ' - - Mse: %.6f' % mse) + print((' - - Training epoch: ', rp, ' - - Mse: %.6f' % mse)) if draw_e: draw_error() return mse @@ -271,7 +272,7 @@ class CNN(): #model predict produce_out = [] print('-------------------Start Testing-------------------------') - print(' - - Shape: Test_Data ',np.shape(datas_test)) + print((' - - Shape: Test_Data ',np.shape(datas_test))) for p in range(len(datas_test)): data_test = np.asmatrix(datas_test[p]) data_focus1, data_conved1 = self.convolute(data_test, self.conv1, self.w_conv1, diff --git a/Neural_Network/perceptron.py b/Neural_Network/perceptron.py index 0cd89df16..8ac3e8fc6 100644 --- a/Neural_Network/perceptron.py +++ b/Neural_Network/perceptron.py @@ -9,6 +9,7 @@ p2 = 1 ''' +from __future__ import print_function import random @@ -52,7 +53,7 @@ class Perceptron: epoch_count = epoch_count + 1 # if you want controle the epoch or just by erro if erro == False: - print('\nEpoch:\n',epoch_count) + print(('\nEpoch:\n',epoch_count)) print('------------------------\n') #if epoch_count > self.epoch_number or not erro: break @@ -66,10 +67,10 @@ class Perceptron: y = self.sign(u) if y == -1: - print('Sample: ', sample) + print(('Sample: ', sample)) print('classification: P1') else: - print('Sample: ', sample) + print(('Sample: ', sample)) print('classification: P2') def sign(self, u): diff --git a/Project Euler/Problem 01/sol1.py b/Project Euler/Problem 01/sol1.py index 512154e29..27031c3cf 100644 --- a/Project Euler/Problem 01/sol1.py +++ b/Project Euler/Problem 01/sol1.py @@ -4,9 +4,14 @@ If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3,5,6 and 9. The sum of these multiples is 23. Find the sum of all the multiples of 3 or 5 below N. ''' +from __future__ import print_function +try: + raw_input # Python 2 +except NameError: + raw_input = input # Python 3 n = int(raw_input().strip()) -sum=0; +sum=0 for a in range(3,n): if(a%3==0 or a%5==0): sum+=a -print sum; \ No newline at end of file +print(sum) diff --git a/Project Euler/Problem 01/sol2.py b/Project Euler/Problem 01/sol2.py index 5e368c220..d330387e9 100644 --- a/Project Euler/Problem 01/sol2.py +++ b/Project Euler/Problem 01/sol2.py @@ -4,6 +4,11 @@ If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3,5,6 and 9. The sum of these multiples is 23. Find the sum of all the multiples of 3 or 5 below N. ''' +from __future__ import print_function +try: + raw_input # Python 2 +except NameError: + raw_input = input # Python 3 n = int(raw_input().strip()) sum = 0 terms = (n-1)/3 @@ -12,4 +17,4 @@ terms = (n-1)/5 sum+= ((terms)*(10+(terms-1)*5))/2 terms = (n-1)/15 sum-= ((terms)*(30+(terms-1)*15))/2 -print sum \ No newline at end of file +print(sum) diff --git a/Project Euler/Problem 01/sol3.py b/Project Euler/Problem 01/sol3.py index 0caa30a53..d3d9256b7 100644 --- a/Project Euler/Problem 01/sol3.py +++ b/Project Euler/Problem 01/sol3.py @@ -7,6 +7,11 @@ Find the sum of all the multiples of 3 or 5 below N. ''' This solution is based on the pattern that the successive numbers in the series follow: 0+3,+2,+1,+3,+1,+2,+3. ''' +from __future__ import print_function +try: + raw_input # Python 2 +except NameError: + raw_input = input # Python 3 n = int(raw_input().strip()) sum=0; num=0; @@ -39,4 +44,4 @@ while(1): if(num>=n): break sum+=num -print sum; \ No newline at end of file +print(sum); diff --git a/Project Euler/Problem 02/sol1.py b/Project Euler/Problem 02/sol1.py index 6cf520767..0b9eb8ea4 100644 --- a/Project Euler/Problem 02/sol1.py +++ b/Project Euler/Problem 02/sol1.py @@ -6,6 +6,12 @@ the first 10 terms will be: By considering the terms in the Fibonacci sequence whose values do not exceed n, find the sum of the even-valued terms. e.g. for n=10, we have {2,8}, sum is 10. ''' +from __future__ import print_function + +try: + raw_input # Python 2 +except NameError: + raw_input = input # Python 3 n = int(raw_input().strip()) i=1; j=2; sum=0 @@ -15,4 +21,4 @@ while(j<=n): temp=i i=j j=temp+i -print sum \ No newline at end of file +print(sum) diff --git a/Project Euler/Problem 03/sol1.py b/Project Euler/Problem 03/sol1.py index bd3e237e7..dfc90982f 100644 --- a/Project Euler/Problem 03/sol1.py +++ b/Project Euler/Problem 03/sol1.py @@ -3,6 +3,7 @@ Problem: The prime factors of 13195 are 5,7,13 and 29. What is the largest prime factor of a given number N? e.g. for 10, largest prime factor = 5. For 17, largest prime factor = 17. ''' +from __future__ import print_function import math @@ -20,12 +21,12 @@ def isprime(no): max=0 n=int(input()) if(isprime(n)): - print n + print(n) else: while (n%2==0): n=n/2 if(isprime(n)): - print n + print(n) else: n1 = int(math.sqrt(n))+1 for i in range(3,n1,2): @@ -35,4 +36,4 @@ else: break elif(isprime(i)): max=i - print max + print(max) diff --git a/Project Euler/Problem 03/sol2.py b/Project Euler/Problem 03/sol2.py index 2577892c4..af4365b7b 100644 --- a/Project Euler/Problem 03/sol2.py +++ b/Project Euler/Problem 03/sol2.py @@ -3,6 +3,7 @@ Problem: The prime factors of 13195 are 5,7,13 and 29. What is the largest prime factor of a given number N? e.g. for 10, largest prime factor = 5. For 17, largest prime factor = 17. ''' +from __future__ import print_function n=int(input()) prime=1 i=2 @@ -13,4 +14,4 @@ while(i*i<=n): i+=1 if(n>1): prime=n -print prime +print(prime) diff --git a/Project Euler/Problem 04/sol1.py b/Project Euler/Problem 04/sol1.py index f8ed832d8..17e16fd53 100644 --- a/Project Euler/Problem 04/sol1.py +++ b/Project Euler/Problem 04/sol1.py @@ -3,6 +3,7 @@ Problem: A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 x 99. Find the largest palindrome made from the product of two 3-digit numbers which is less than N. ''' +from __future__ import print_function n=int(input()) for i in range(n-1,10000,-1): temp=str(i) @@ -10,6 +11,6 @@ for i in range(n-1,10000,-1): j=999 while(j!=99): if((i%j==0) and (len(str(i/j))==3)): - print i + print(i) exit(0) j-=1 diff --git a/Project Euler/Problem 04/sol2.py b/Project Euler/Problem 04/sol2.py index 4d2006242..e27e7d304 100644 --- a/Project Euler/Problem 04/sol2.py +++ b/Project Euler/Problem 04/sol2.py @@ -3,6 +3,7 @@ Problem: A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 x 99. Find the largest palindrome made from the product of two 3-digit numbers which is less than N. ''' +from __future__ import print_function arr = [] for i in range(999,100,-1): for j in range(999,100,-1): @@ -14,5 +15,5 @@ arr.sort() n=int(input()) for i in arr[::-1]: if(i',pre_counter,'digits') +print(('Largest Number:',largest_number,'->',pre_counter,'digits')) diff --git a/Project Euler/Problem 9/sol1.py b/Project Euler/Problem 9/sol1.py index ed8a2ab36..e54c543b4 100644 --- a/Project Euler/Problem 9/sol1.py +++ b/Project Euler/Problem 9/sol1.py @@ -1,3 +1,4 @@ +from __future__ import print_function # Program to find the product of a,b,c which are Pythagorean Triplet that satisfice the following: # 1. a < b < c # 2. a**2 + b**2 = c**2 @@ -10,5 +11,5 @@ for a in range(300): if(a < b < c): if((a**2) + (b**2) == (c**2)): if((a+b+c) == 1000): - print("Product of",a,"*",b,"*",c,"=",(a*b*c)) + print(("Product of",a,"*",b,"*",c,"=",(a*b*c))) break diff --git a/ciphers/affine_cipher.py b/ciphers/affine_cipher.py index b74ec6f4e..6c1ba06f6 100644 --- a/ciphers/affine_cipher.py +++ b/ciphers/affine_cipher.py @@ -1,3 +1,4 @@ +from __future__ import print_function import sys, random, cryptomath_module as cryptoMath SYMBOLS = """ !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~""" diff --git a/ciphers/brute-force_caesar_cipher.py b/ciphers/brute-force_caesar_cipher.py index 3e6e975c8..3b0716442 100644 --- a/ciphers/brute-force_caesar_cipher.py +++ b/ciphers/brute-force_caesar_cipher.py @@ -1,3 +1,4 @@ +from __future__ import print_function def decrypt(message): """ >>> decrypt('TMDETUX PMDVU') diff --git a/ciphers/caesar_cipher.py b/ciphers/caesar_cipher.py index b590f81f9..a53dc5857 100644 --- a/ciphers/caesar_cipher.py +++ b/ciphers/caesar_cipher.py @@ -1,3 +1,4 @@ +from __future__ import print_function # The Caesar Cipher Algorithm def main(): @@ -12,9 +13,9 @@ def main(): translated = encdec(message, key, mode) if mode == "encrypt": - print("Encryption:", translated) + print(("Encryption:", translated)) elif mode == "decrypt": - print("Decryption:", translated) + print(("Decryption:", translated)) def encdec(message, key, mode): message = message.upper() diff --git a/ciphers/rabin_miller.py b/ciphers/rabin_miller.py index d6e5cbe8f..f71fb03c0 100644 --- a/ciphers/rabin_miller.py +++ b/ciphers/rabin_miller.py @@ -1,3 +1,4 @@ +from __future__ import print_function # Primality Testing with the Rabin-Miller Algorithm import random @@ -59,5 +60,5 @@ def generateLargePrime(keysize = 1024): if __name__ == '__main__': num = generateLargePrime() - print('Prime number:', num) - print('isPrime:', isPrime(num)) + print(('Prime number:', num)) + print(('isPrime:', isPrime(num))) diff --git a/ciphers/rot13.py b/ciphers/rot13.py index 208de4890..2abf981e9 100644 --- a/ciphers/rot13.py +++ b/ciphers/rot13.py @@ -1,3 +1,4 @@ +from __future__ import print_function def dencrypt(s, n): out = '' for c in s: diff --git a/ciphers/rsa_cipher.py b/ciphers/rsa_cipher.py index 7e2dc5fd1..94f69ddc2 100644 --- a/ciphers/rsa_cipher.py +++ b/ciphers/rsa_cipher.py @@ -1,3 +1,4 @@ +from __future__ import print_function import sys, rsa_key_generator as rkg, os DEFAULT_BLOCK_SIZE = 128 diff --git a/ciphers/rsa_key_generator.py b/ciphers/rsa_key_generator.py index 7cd7163b6..541e90d6e 100644 --- a/ciphers/rsa_key_generator.py +++ b/ciphers/rsa_key_generator.py @@ -1,3 +1,4 @@ +from __future__ import print_function import random, sys, os import rabin_miller as rabinMiller, cryptomath_module as cryptoMath diff --git a/ciphers/simple_substitution_cipher.py b/ciphers/simple_substitution_cipher.py index 41ac4a6a7..1bdd7dc04 100644 --- a/ciphers/simple_substitution_cipher.py +++ b/ciphers/simple_substitution_cipher.py @@ -1,3 +1,4 @@ +from __future__ import print_function import sys, random LETTERS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' diff --git a/ciphers/transposition_cipher.py b/ciphers/transposition_cipher.py index 1c2ed0aa0..dbb358315 100644 --- a/ciphers/transposition_cipher.py +++ b/ciphers/transposition_cipher.py @@ -1,3 +1,4 @@ +from __future__ import print_function import math def main(): diff --git a/ciphers/transposition_cipher_encrypt-decrypt_file.py b/ciphers/transposition_cipher_encrypt-decrypt_file.py index f2252de8a..57620d839 100644 --- a/ciphers/transposition_cipher_encrypt-decrypt_file.py +++ b/ciphers/transposition_cipher_encrypt-decrypt_file.py @@ -1,3 +1,4 @@ +from __future__ import print_function import time, os, sys import transposition_cipher as transCipher @@ -29,7 +30,7 @@ def main(): outputObj.close() totalTime = round(time.time() - startTime, 2) - print('Done (', totalTime, 'seconds )') + print(('Done (', totalTime, 'seconds )')) if __name__ == '__main__': main() diff --git a/ciphers/vigenere_cipher.py b/ciphers/vigenere_cipher.py index 95eeb4311..5d5be0792 100644 --- a/ciphers/vigenere_cipher.py +++ b/ciphers/vigenere_cipher.py @@ -1,3 +1,4 @@ +from __future__ import print_function LETTERS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' def main(): diff --git a/data_structures/Binary Tree/FenwickTree.py b/data_structures/Binary Tree/FenwickTree.py index 02e2d6151..f429161c8 100644 --- a/data_structures/Binary Tree/FenwickTree.py +++ b/data_structures/Binary Tree/FenwickTree.py @@ -1,28 +1,29 @@ -class FenwickTree: - - def __init__(self, SIZE): # create fenwick tree with size SIZE - self.Size = SIZE - self.ft = [0 for i in range (0,SIZE)] - - def update(self, i, val): # update data (adding) in index i in O(lg N) - while (i < self.Size): - self.ft[i] += val - i += i & (-i) - - def query(self, i): # query cumulative data from index 0 to i in O(lg N) - ret = 0 - while (i > 0): - 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)) - f.update(2,-5) - print (f.query(1)) - print (f.query(3)) +from __future__ import print_function +class FenwickTree: + + def __init__(self, SIZE): # create fenwick tree with size SIZE + self.Size = SIZE + self.ft = [0 for i in range (0,SIZE)] + + def update(self, i, val): # update data (adding) in index i in O(lg N) + while (i < self.Size): + self.ft[i] += val + i += i & (-i) + + def query(self, i): # query cumulative data from index 0 to i in O(lg N) + ret = 0 + while (i > 0): + 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)) + f.update(2,-5) + print (f.query(1)) + print (f.query(3)) diff --git a/data_structures/Binary Tree/LazySegmentTree.py b/data_structures/Binary Tree/LazySegmentTree.py index bbd880a06..9b14b24e8 100644 --- a/data_structures/Binary Tree/LazySegmentTree.py +++ b/data_structures/Binary Tree/LazySegmentTree.py @@ -1,90 +1,91 @@ -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 - - def right(self, idx): - return idx*2 + 1 - - def build(self, idx, l, r, A): - if l==r: - self.st[idx] = A[l-1] - else : - mid = (l+r)//2 - self.build(self.left(idx),l,mid, A) - self.build(self.right(idx),mid+1,r, A) - self.st[idx] = max(self.st[self.left(idx)] , self.st[self.right(idx)]) - - # update with O(lg N) (Normal segment tree without lazy update will take O(Nlg N) for each update) - def update(self, idx, l, r, a, b, val): # update(1, 1, N, a, b, v) for update val v to [a,b] - if self.flag[idx] == True: - self.st[idx] = self.lazy[idx] - self.flag[idx] = False - if l!=r: - self.lazy[self.left(idx)] = self.lazy[idx] - 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 : - self.st[idx] = val - if l!=r: - self.lazy[self.left(idx)] = val - self.lazy[self.right(idx)] = val - self.flag[self.left(idx)] = True - self.flag[self.right(idx)] = True - return True - mid = (l+r)//2 - self.update(self.left(idx),l,mid,a,b,val) - self.update(self.right(idx),mid+1,r,a,b,val) - self.st[idx] = max(self.st[self.left(idx)] , self.st[self.right(idx)]) - return True - - # query with O(lg N) - def query(self, idx, l, r, a, b): #query(1, 1, N, a, b) for query max of [a,b] - if self.flag[idx] == True: - self.st[idx] = self.lazy[idx] - self.flag[idx] = False - if l != r: - self.lazy[self.left(idx)] = self.lazy[idx] - 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 -math.inf - if l >= a and r <= b: - return self.st[idx] - mid = (l+r)//2 - q1 = self.query(self.left(idx),l,mid,a,b) - q2 = self.query(self.right(idx),mid+1,r,a,b) - return max(q1,q2) - - def showData(self): - showList = [] - for i in range(1,N+1): - showList += [self.query(1, 1, self.N, i, i)] - 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)) - segt.update(1,1,N,1,3,111) - print (segt.query(1,1,N,1,15)) - segt.update(1,1,N,7,8,235) - segt.showData() +from __future__ import print_function +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 + + def right(self, idx): + return idx*2 + 1 + + def build(self, idx, l, r, A): + if l==r: + self.st[idx] = A[l-1] + else : + mid = (l+r)//2 + self.build(self.left(idx),l,mid, A) + self.build(self.right(idx),mid+1,r, A) + self.st[idx] = max(self.st[self.left(idx)] , self.st[self.right(idx)]) + + # update with O(lg N) (Normal segment tree without lazy update will take O(Nlg N) for each update) + def update(self, idx, l, r, a, b, val): # update(1, 1, N, a, b, v) for update val v to [a,b] + if self.flag[idx] == True: + self.st[idx] = self.lazy[idx] + self.flag[idx] = False + if l!=r: + self.lazy[self.left(idx)] = self.lazy[idx] + 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 : + self.st[idx] = val + if l!=r: + self.lazy[self.left(idx)] = val + self.lazy[self.right(idx)] = val + self.flag[self.left(idx)] = True + self.flag[self.right(idx)] = True + return True + mid = (l+r)//2 + self.update(self.left(idx),l,mid,a,b,val) + self.update(self.right(idx),mid+1,r,a,b,val) + self.st[idx] = max(self.st[self.left(idx)] , self.st[self.right(idx)]) + return True + + # query with O(lg N) + def query(self, idx, l, r, a, b): #query(1, 1, N, a, b) for query max of [a,b] + if self.flag[idx] == True: + self.st[idx] = self.lazy[idx] + self.flag[idx] = False + if l != r: + self.lazy[self.left(idx)] = self.lazy[idx] + 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 -math.inf + if l >= a and r <= b: + return self.st[idx] + mid = (l+r)//2 + q1 = self.query(self.left(idx),l,mid,a,b) + q2 = self.query(self.right(idx),mid+1,r,a,b) + return max(q1,q2) + + def showData(self): + showList = [] + for i in range(1,N+1): + showList += [self.query(1, 1, self.N, i, i)] + 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)) + segt.update(1,1,N,1,3,111) + 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/SegmentTree.py b/data_structures/Binary Tree/SegmentTree.py index cf47ca7d7..a3b128c9d 100644 --- a/data_structures/Binary Tree/SegmentTree.py +++ b/data_structures/Binary Tree/SegmentTree.py @@ -1,64 +1,65 @@ -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 - - def left(self, idx): - return idx*2 - - def right(self, idx): - return idx*2 + 1 - - def build(self, idx, l, r, A): - if l==r: - self.st[idx] = A[l-1] - else : - mid = (l+r)//2 - self.build(self.left(idx),l,mid, A) - self.build(self.right(idx),mid+1,r, A) - self.st[idx] = max(self.st[self.left(idx)] , self.st[self.right(idx)]) - - def update(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 - if l == r : - self.st[idx] = val - return True - mid = (l+r)//2 - self.update(self.left(idx),l,mid,a,b,val) - self.update(self.right(idx),mid+1,r,a,b,val) - self.st[idx] = max(self.st[self.left(idx)] , self.st[self.right(idx)]) - return True - - def query(self, idx, l, r, a, b): #query(1, 1, N, a, b) for query max of [a,b] - if r < a or l > b: - return -math.inf - if l >= a and r <= b: - return self.st[idx] - mid = (l+r)//2 - q1 = self.query(self.left(idx),l,mid,a,b) - q2 = self.query(self.right(idx),mid+1,r,a,b) - return max(q1,q2) - - def showData(self): - showList = [] - for i in range(1,N+1): - showList += [self.query(1, 1, self.N, i, i)] - 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)) - segt.update(1,1,N,1,3,111) - print (segt.query(1,1,N,1,15)) - segt.update(1,1,N,7,8,235) - segt.showData() +from __future__ import print_function +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 + + def left(self, idx): + return idx*2 + + def right(self, idx): + return idx*2 + 1 + + def build(self, idx, l, r, A): + if l==r: + self.st[idx] = A[l-1] + else : + mid = (l+r)//2 + self.build(self.left(idx),l,mid, A) + self.build(self.right(idx),mid+1,r, A) + self.st[idx] = max(self.st[self.left(idx)] , self.st[self.right(idx)]) + + def update(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 + if l == r : + self.st[idx] = val + return True + mid = (l+r)//2 + self.update(self.left(idx),l,mid,a,b,val) + self.update(self.right(idx),mid+1,r,a,b,val) + self.st[idx] = max(self.st[self.left(idx)] , self.st[self.right(idx)]) + return True + + def query(self, idx, l, r, a, b): #query(1, 1, N, a, b) for query max of [a,b] + if r < a or l > b: + return -math.inf + if l >= a and r <= b: + return self.st[idx] + mid = (l+r)//2 + q1 = self.query(self.left(idx),l,mid,a,b) + q2 = self.query(self.right(idx),mid+1,r,a,b) + return max(q1,q2) + + def showData(self): + showList = [] + for i in range(1,N+1): + showList += [self.query(1, 1, self.N, i, i)] + 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)) + segt.update(1,1,N,1,3,111) + 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/binary_search_tree.py b/data_structures/Binary Tree/binary_search_tree.py index 5290f685b..b4021e4f8 100644 --- a/data_structures/Binary Tree/binary_search_tree.py +++ b/data_structures/Binary Tree/binary_search_tree.py @@ -1,6 +1,7 @@ ''' A binary search Tree ''' +from __future__ import print_function class Node: def __init__(self, label, parent): @@ -237,8 +238,8 @@ def testBinarySearchTree(): print("The label -1 doesn't exist") if(not t.empty()): - print("Max Value: ", t.getMax().getLabel()) - print("Min Value: ", t.getMin().getLabel()) + print(("Max Value: ", t.getMax().getLabel())) + print(("Min Value: ", t.getMin().getLabel())) t.delete(13) t.delete(10) diff --git a/data_structures/Graph/Graph.py b/data_structures/Graph/Graph.py index 0fa3f5593..d091f713b 100644 --- a/data_structures/Graph/Graph.py +++ b/data_structures/Graph/Graph.py @@ -1,3 +1,4 @@ +from __future__ import print_function # Author: OMKAR PATHAK # We can use Python's dictionary for constructing the graph @@ -15,7 +16,7 @@ class AdjacencyList(object): def printList(self): for i in self.List: - print(i,'->',' -> '.join([str(j) for j in self.List[i]])) + print((i,'->',' -> '.join([str(j) for j in self.List[i]]))) if __name__ == '__main__': al = AdjacencyList() diff --git a/data_structures/Graph/even_tree.py b/data_structures/Graph/even_tree.py index f77cb316e..9383ea9a1 100644 --- a/data_structures/Graph/even_tree.py +++ b/data_structures/Graph/even_tree.py @@ -12,6 +12,7 @@ Constraints Note: The tree input will be such that it can always be decomposed into components containing an even number of nodes. """ +from __future__ import print_function # pylint: disable=invalid-name from collections import defaultdict @@ -66,4 +67,4 @@ if __name__ == '__main__': tree[u].append(v) tree[v].append(u) even_tree() - print len(cuts) - 1 + print(len(cuts) - 1) diff --git a/data_structures/Heap/heap.py b/data_structures/Heap/heap.py index d43cc4baa..e66d02b6d 100644 --- a/data_structures/Heap/heap.py +++ b/data_structures/Heap/heap.py @@ -1,5 +1,12 @@ #!/usr/bin/python +from __future__ import print_function + +try: + raw_input # Python 2 +except NameError: + raw_input = input # Python 3 + class Heap: def __init__(self): self.h = [] @@ -68,10 +75,10 @@ class Heap: curr = curr/2 def display(self): - print (self.h) + print(self.h) def main(): - l = list(map(int,raw_input().split())) + l = list(map(int, raw_input().split())) h = Heap() h.buildHeap(l) h.heapSort() diff --git a/data_structures/LinkedList/singly_LinkedList.py b/data_structures/LinkedList/singly_LinkedList.py index 8828ce6cc..7358b3c07 100644 --- a/data_structures/LinkedList/singly_LinkedList.py +++ b/data_structures/LinkedList/singly_LinkedList.py @@ -1,3 +1,4 @@ +from __future__ import print_function class Node:#create a Node def __int__(self,data): self.data=data#given data diff --git a/data_structures/Queue/DeQueue.py b/data_structures/Queue/DeQueue.py index 175c88163..fdee64eb6 100644 --- a/data_structures/Queue/DeQueue.py +++ b/data_structures/Queue/DeQueue.py @@ -1,3 +1,4 @@ +from __future__ import print_function # Python code to demonstrate working of # extend(), extendleft(), rotate(), reverse() diff --git a/data_structures/Stacks/balanced_parentheses.py b/data_structures/Stacks/balanced_parentheses.py index 1c9a84843..8d99358be 100644 --- a/data_structures/Stacks/balanced_parentheses.py +++ b/data_structures/Stacks/balanced_parentheses.py @@ -1,4 +1,6 @@ -from Stack import Stack +from __future__ import print_function +from __future__ import absolute_import +from .Stack import Stack __author__ = 'Omkar Pathak' diff --git a/data_structures/Stacks/infix_to_postfix_conversion.py b/data_structures/Stacks/infix_to_postfix_conversion.py index f0a8fd072..75211fed2 100644 --- a/data_structures/Stacks/infix_to_postfix_conversion.py +++ b/data_structures/Stacks/infix_to_postfix_conversion.py @@ -1,6 +1,8 @@ +from __future__ import print_function +from __future__ import absolute_import import string -from Stack import Stack +from .Stack import Stack __author__ = 'Omkar Pathak' diff --git a/data_structures/Stacks/next.py b/data_structures/Stacks/next.py index 9765900c0..bca833395 100644 --- a/data_structures/Stacks/next.py +++ b/data_structures/Stacks/next.py @@ -1,3 +1,4 @@ +from __future__ import print_function # Function to print element and NGE pair for all elements of list def printNGE(arr): diff --git a/data_structures/Stacks/stack.py b/data_structures/Stacks/stack.py index 0b100abf3..66af8c025 100644 --- a/data_structures/Stacks/stack.py +++ b/data_structures/Stacks/stack.py @@ -1,3 +1,4 @@ +from __future__ import print_function __author__ = 'Omkar Pathak' diff --git a/data_structures/UnionFind/tests_union_find.py b/data_structures/UnionFind/tests_union_find.py index bdcc01033..b0708778d 100644 --- a/data_structures/UnionFind/tests_union_find.py +++ b/data_structures/UnionFind/tests_union_find.py @@ -1,4 +1,5 @@ -from union_find import UnionFind +from __future__ import absolute_import +from .union_find import UnionFind import unittest diff --git a/dynamic_programming/coin_change.py b/dynamic_programming/coin_change.py index dca016359..0116df0c0 100644 --- a/dynamic_programming/coin_change.py +++ b/dynamic_programming/coin_change.py @@ -5,6 +5,7 @@ Can you determine number of ways of making change for n units using the given types of coins? https://www.hackerrank.com/challenges/coin-change/problem """ +from __future__ import print_function def dp_count(S, m, n): table = [0] * (n + 1) @@ -21,5 +22,5 @@ def dp_count(S, m, n): return table[n] if __name__ == '__main__': - print dp_count([1, 2, 3], 3, 4) # answer 4 - print dp_count([2, 5, 3, 6], 4, 10) # answer 5 + print(dp_count([1, 2, 3], 3, 4)) # answer 4 + print(dp_count([2, 5, 3, 6], 4, 10)) # answer 5 diff --git a/dynamic_programming/edit_distance.py b/dynamic_programming/edit_distance.py index 05682d2c6..4a6e4cecf 100644 --- a/dynamic_programming/edit_distance.py +++ b/dynamic_programming/edit_distance.py @@ -51,11 +51,10 @@ class EditDistance: return self.__solveDP(len(A)-1, len(B)-1) if __name__ == '__main__': - import sys - if sys.version_info.major < 3: - input_function = raw_input - else: - input_function = input + try: + raw_input # Python 2 + except NameError: + raw_input = input # Python 3 solver = EditDistance() @@ -63,10 +62,10 @@ if __name__ == '__main__': print() print("Enter the first string: ", end="") - S1 = input_function() + S1 = raw_input().strip() print("Enter the second string: ", end="") - S2 = input_function() + S2 = raw_input().strip() print() print("The minimum Edit Distance is: %d" % (solver.solve(S1, S2))) diff --git a/dynamic_programming/fastfibonacci.py b/dynamic_programming/fastfibonacci.py index 5957fbe0d..cdfa2dd08 100644 --- a/dynamic_programming/fastfibonacci.py +++ b/dynamic_programming/fastfibonacci.py @@ -2,6 +2,7 @@ This program calculates the nth Fibonacci number in O(log(n)). It's possible to calculate F(1000000) in less than a second. """ +from __future__ import print_function import sys diff --git a/dynamic_programming/fibonacci.py b/dynamic_programming/fibonacci.py index 5eaa81b3e..abe628d03 100644 --- a/dynamic_programming/fibonacci.py +++ b/dynamic_programming/fibonacci.py @@ -27,26 +27,22 @@ class Fibonacci: if __name__ == '__main__': - import sys - print("\n********* Fibonacci Series Using Dynamic Programming ************\n") - # For python 2.x and 3.x compatibility: 3.x has no raw_input builtin - # otherwise 2.x's input builtin function is too "smart" - if sys.version_info.major < 3: - input_function = raw_input - else: - input_function = input + try: + raw_input # Python 2 + except NameError: + raw_input = input # Python 3 print("\n Enter the upper limit for the fibonacci sequence: ", end="") try: - N = eval(input()) + N = eval(raw_input().strip()) fib = Fibonacci(N) print( "\n********* Enter different values to get the corresponding fibonacci sequence, enter any negative number to exit. ************\n") while True: print("Enter value: ", end=" ") try: - i = eval(input()) + i = eval(raw_input().strip()) if i < 0: print("\n********* Good Bye!! ************\n") break diff --git a/dynamic_programming/longest_common_subsequence.py b/dynamic_programming/longest_common_subsequence.py index bf4e5860c..0a4771cb2 100644 --- a/dynamic_programming/longest_common_subsequence.py +++ b/dynamic_programming/longest_common_subsequence.py @@ -3,6 +3,13 @@ LCS Problem Statement: Given two sequences, find the length of longest subsequen A subsequence is a sequence that appears in the same relative order, but not necessarily continious. Example:"abc", "abg" are subsequences of "abcdefgh". """ +from __future__ import print_function + +try: + xrange # Python 2 +except NameError: + xrange = range # Python 3 + def lcs_dp(x, y): # find the length of strings m = len(x) @@ -27,4 +34,4 @@ def lcs_dp(x, y): if __name__=='__main__': x = 'AGGTAB' y = 'GXTXAYB' - print lcs_dp(x, y) + print(lcs_dp(x, y)) diff --git a/dynamic_programming/longest_increasing_subsequence.py b/dynamic_programming/longest_increasing_subsequence.py index c04f6673f..b6d165909 100644 --- a/dynamic_programming/longest_increasing_subsequence.py +++ b/dynamic_programming/longest_increasing_subsequence.py @@ -7,6 +7,7 @@ The problem is : Given an ARRAY, to find the longest and increasing sub ARRAY in that given ARRAY and return it. Example: [10, 22, 9, 33, 21, 50, 41, 60, 80] as input will return [10, 22, 33, 41, 60, 80] as output ''' +from __future__ import print_function def longestSub(ARRAY): #This function is recursive diff --git a/dynamic_programming/longest_increasing_subsequence_O(nlogn).py b/dynamic_programming/longest_increasing_subsequence_O(nlogn).py index 3ebb4a137..21122a04d 100644 --- a/dynamic_programming/longest_increasing_subsequence_O(nlogn).py +++ b/dynamic_programming/longest_increasing_subsequence_O(nlogn).py @@ -1,3 +1,4 @@ +from __future__ import print_function ############################# # Author: Aravind Kashyap # File: lis.py @@ -37,4 +38,4 @@ def LongestIncreasingSubsequenceLength(v): v = [2, 5, 3, 7, 11, 8, 10, 13, 6] -print LongestIncreasingSubsequenceLength(v) +print(LongestIncreasingSubsequenceLength(v)) diff --git a/dynamic_programming/longest_sub_array.py b/dynamic_programming/longest_sub_array.py index 988041ed0..de2c88a8b 100644 --- a/dynamic_programming/longest_sub_array.py +++ b/dynamic_programming/longest_sub_array.py @@ -6,6 +6,7 @@ This is a pure Python implementation of Dynamic Programming solution to the long The problem is : Given an array, to find the longest and continuous sub array and get the max sum of the sub array in the given array. ''' +from __future__ import print_function class SubArray: @@ -13,7 +14,7 @@ class SubArray: def __init__(self, arr): # we need a list not a string, so do something to change the type self.array = arr.split(',') - print("the input array is:", self.array) + print(("the input array is:", self.array)) def solve_sub_array(self): rear = [int(self.array[0])]*len(self.array) @@ -28,5 +29,5 @@ if __name__ == '__main__': whole_array = input("please input some numbers:") array = SubArray(whole_array) re = array.solve_sub_array() - print("the results is:", re) + print(("the results is:", re)) diff --git a/dynamic_programming/max_sub_array.py b/dynamic_programming/max_sub_array.py index 653bb66e0..58711f22c 100644 --- a/dynamic_programming/max_sub_array.py +++ b/dynamic_programming/max_sub_array.py @@ -1,59 +1,60 @@ -""" -author : Mayank Kumar Jha (mk9440) -""" - -import time -import matplotlib.pyplot as plt -from random import randint -def find_max_sub_array(A,low,high): - if low==high: - return low,high,A[low] - else : - mid=(low+high)//2 - left_low,left_high,left_sum=find_max_sub_array(A,low,mid) - right_low,right_high,right_sum=find_max_sub_array(A,mid+1,high) - cross_left,cross_right,cross_sum=find_max_cross_sum(A,low,mid,high) - if left_sum>=right_sum and left_sum>=cross_sum: - return left_low,left_high,left_sum - elif right_sum>=left_sum and right_sum>=cross_sum : - return right_low,right_high,right_sum - else: - return cross_left,cross_right,cross_sum - -def find_max_cross_sum(A,low,mid,high): - left_sum,max_left=-999999999,-1 - right_sum,max_right=-999999999,-1 - summ=0 - for i in range(mid,low-1,-1): - summ+=A[i] - if summ > left_sum: - left_sum=summ - max_left=i - summ=0 - for i in range(mid+1,high+1): - summ+=A[i] - if summ > right_sum: - right_sum=summ - max_right=i - return max_left,max_right,(left_sum+right_sum) - - -if __name__=='__main__': - inputs=[10,100,1000,10000,50000,100000,200000,300000,400000,500000] - tim=[] - for i in inputs: - li=[randint(1,i) for j in range(i)] - strt=time.time() - (find_max_sub_array(li,0,len(li)-1)) - end=time.time() - tim.append(end-strt) - print("No of Inputs Time Taken") - for i in range(len(inputs)): - print(inputs[i],'\t\t',tim[i]) - plt.plot(inputs,tim) - plt.xlabel("Number of Inputs");plt.ylabel("Time taken in seconds ") - plt.show() - - - - +""" +author : Mayank Kumar Jha (mk9440) +""" +from __future__ import print_function + +import time +import matplotlib.pyplot as plt +from random import randint +def find_max_sub_array(A,low,high): + if low==high: + return low,high,A[low] + else : + mid=(low+high)//2 + left_low,left_high,left_sum=find_max_sub_array(A,low,mid) + right_low,right_high,right_sum=find_max_sub_array(A,mid+1,high) + cross_left,cross_right,cross_sum=find_max_cross_sum(A,low,mid,high) + if left_sum>=right_sum and left_sum>=cross_sum: + return left_low,left_high,left_sum + elif right_sum>=left_sum and right_sum>=cross_sum : + return right_low,right_high,right_sum + else: + return cross_left,cross_right,cross_sum + +def find_max_cross_sum(A,low,mid,high): + left_sum,max_left=-999999999,-1 + right_sum,max_right=-999999999,-1 + summ=0 + for i in range(mid,low-1,-1): + summ+=A[i] + if summ > left_sum: + left_sum=summ + max_left=i + summ=0 + for i in range(mid+1,high+1): + summ+=A[i] + if summ > right_sum: + right_sum=summ + max_right=i + return max_left,max_right,(left_sum+right_sum) + + +if __name__=='__main__': + inputs=[10,100,1000,10000,50000,100000,200000,300000,400000,500000] + tim=[] + for i in inputs: + li=[randint(1,i) for j in range(i)] + strt=time.time() + (find_max_sub_array(li,0,len(li)-1)) + end=time.time() + tim.append(end-strt) + print("No of Inputs Time Taken") + for i in range(len(inputs)): + print((inputs[i],'\t\t',tim[i])) + plt.plot(inputs,tim) + plt.xlabel("Number of Inputs");plt.ylabel("Time taken in seconds ") + plt.show() + + + + diff --git a/hashes/chaos_machine.py b/hashes/chaos_machine.py index b9d8dd750..8b6c00438 100644 --- a/hashes/chaos_machine.py +++ b/hashes/chaos_machine.py @@ -1,4 +1,5 @@ """example of simple chaos machine""" +from __future__ import print_function # Chaos Machine (K, t, m) K = [0.33, 0.44, 0.55, 0.44, 0.33]; t = 3; m = 5 diff --git a/hashes/md5.py b/hashes/md5.py index ff32f4c2e..c336b5fe4 100644 --- a/hashes/md5.py +++ b/hashes/md5.py @@ -1,3 +1,4 @@ +from __future__ import print_function import math def rearrange(bitString32): diff --git a/machine_learning/decision_tree.py b/machine_learning/decision_tree.py index 51f600cac..71849904c 100644 --- a/machine_learning/decision_tree.py +++ b/machine_learning/decision_tree.py @@ -3,6 +3,7 @@ Implementation of a basic regression decision tree. Input data set: The input data set must be 1-dimensional with continuous labels. Output: The decision tree maps a real number input to a real number output. """ +from __future__ import print_function import numpy as np diff --git a/machine_learning/gradient_descent.py b/machine_learning/gradient_descent.py index 1e771b072..db6415999 100644 --- a/machine_learning/gradient_descent.py +++ b/machine_learning/gradient_descent.py @@ -1,6 +1,7 @@ """ Implementation of gradient descent algorithm for minimizing cost of a linear hypothesis function. """ +from __future__ import print_function import numpy # List of input, output pairs @@ -106,13 +107,13 @@ def run_gradient_descent(): atol=absolute_error_limit, rtol=relative_error_limit): break parameter_vector = temp_parameter_vector - print("Number of iterations:", j) + print(("Number of iterations:", j)) def test_gradient_descent(): for i in range(len(test_data)): - print("Actual output value:", output(i, 'test')) - print("Hypothesis output:", calculate_hypothesis_value(i, 'test')) + print(("Actual output value:", output(i, 'test'))) + print(("Hypothesis output:", calculate_hypothesis_value(i, 'test'))) if __name__ == '__main__': diff --git a/machine_learning/linear_regression.py b/machine_learning/linear_regression.py index fd33c3580..eb1f019c5 100644 --- a/machine_learning/linear_regression.py +++ b/machine_learning/linear_regression.py @@ -7,6 +7,7 @@ We try to set these Feature weights, over many iterations, so that they best fits our dataset. In this particular code, i had used a CSGO dataset (ADR vs Rating). We try to best fit a line through dataset and estimate the parameters. """ +from __future__ import print_function import requests import numpy as np diff --git a/machine_learning/perceptron.py b/machine_learning/perceptron.py index 0cd89df16..8ac3e8fc6 100644 --- a/machine_learning/perceptron.py +++ b/machine_learning/perceptron.py @@ -9,6 +9,7 @@ p2 = 1 ''' +from __future__ import print_function import random @@ -52,7 +53,7 @@ class Perceptron: epoch_count = epoch_count + 1 # if you want controle the epoch or just by erro if erro == False: - print('\nEpoch:\n',epoch_count) + print(('\nEpoch:\n',epoch_count)) print('------------------------\n') #if epoch_count > self.epoch_number or not erro: break @@ -66,10 +67,10 @@ class Perceptron: y = self.sign(u) if y == -1: - print('Sample: ', sample) + print(('Sample: ', sample)) print('classification: P1') else: - print('Sample: ', sample) + print(('Sample: ', sample)) print('classification: P2') def sign(self, u): diff --git a/machine_learning/scoring_functions.py b/machine_learning/scoring_functions.py index 4204716cd..64806a096 100644 --- a/machine_learning/scoring_functions.py +++ b/machine_learning/scoring_functions.py @@ -1,4 +1,4 @@ -import numpy +import numpy as np """ Here I implemented the scoring functions. MAE, MSE, RMSE, RMSLE are included. diff --git a/other/LinearCongruentialGenerator.py b/other/LinearCongruentialGenerator.py index b1eaa6119..34abdf34e 100644 --- a/other/LinearCongruentialGenerator.py +++ b/other/LinearCongruentialGenerator.py @@ -1,3 +1,4 @@ +from __future__ import print_function __author__ = "Tobias Carryer" from time import time @@ -31,4 +32,4 @@ if __name__ == "__main__": # Show the LCG in action. lcg = LinearCongruentialGenerator(1664525, 1013904223, 2<<31) while True : - print lcg.next_number() \ No newline at end of file + print(lcg.next_number()) \ No newline at end of file diff --git a/other/anagrams.py b/other/anagrams.py index 6150ea8e6..44cd96b75 100644 --- a/other/anagrams.py +++ b/other/anagrams.py @@ -1,3 +1,4 @@ +from __future__ import print_function import collections, pprint, time, os start_time = time.time() @@ -25,4 +26,4 @@ with open('anagrams.txt', 'w') as file: file.write(pprint.pformat(all_anagrams)) total_time = round(time.time() - start_time, 2) -print('Done [', total_time, 'seconds ]') +print(('Done [', total_time, 'seconds ]')) diff --git a/other/euclidean_gcd.py b/other/euclidean_gcd.py index 13378379f..30853e172 100644 --- a/other/euclidean_gcd.py +++ b/other/euclidean_gcd.py @@ -1,3 +1,4 @@ +from __future__ import print_function # https://en.wikipedia.org/wiki/Euclidean_algorithm def euclidean_gcd(a, b): diff --git a/other/nested_brackets.py b/other/nested_brackets.py index f486190f4..76677d564 100644 --- a/other/nested_brackets.py +++ b/other/nested_brackets.py @@ -13,6 +13,7 @@ The function called is_balanced takes as input a string S which is a sequence of returns true if S is nested and false otherwise. ''' +from __future__ import print_function def is_balanced(S): @@ -39,10 +40,10 @@ def main(): S = input("Enter sequence of brackets: ") if is_balanced(S): - print(S, "is balanced") + print((S, "is balanced")) else: - print(S, "is not balanced") + print((S, "is not balanced")) if __name__ == "__main__": diff --git a/other/password_generator.py b/other/password_generator.py index 10ba77088..863474906 100644 --- a/other/password_generator.py +++ b/other/password_generator.py @@ -1,3 +1,4 @@ +from __future__ import print_function import string import random diff --git a/other/tower_of_hanoi.py b/other/tower_of_hanoi.py index de0cb6218..dc15b2ce8 100644 --- a/other/tower_of_hanoi.py +++ b/other/tower_of_hanoi.py @@ -1,3 +1,4 @@ +from __future__ import print_function def moveTower(height, fromPole, toPole, withPole): ''' >>> moveTower(3, 'A', 'B', 'C') @@ -15,7 +16,7 @@ def moveTower(height, fromPole, toPole, withPole): moveTower(height-1, withPole, toPole, fromPole) def moveDisk(fp,tp): - print('moving disk from', fp, 'to', tp) + print(('moving disk from', fp, 'to', tp)) def main(): height = int(input('Height of hanoi: ')) diff --git a/other/two-sum.py b/other/two-sum.py index 4a522b6d4..d4484aa85 100644 --- a/other/two-sum.py +++ b/other/two-sum.py @@ -9,6 +9,7 @@ Given nums = [2, 7, 11, 15], target = 9, Because nums[0] + nums[1] = 2 + 7 = 9, return [0, 1]. """ +from __future__ import print_function def twoSum(nums, target): """ diff --git a/other/word_patterns.py b/other/word_patterns.py index 827c9fa8b..c33d52008 100644 --- a/other/word_patterns.py +++ b/other/word_patterns.py @@ -1,3 +1,4 @@ +from __future__ import print_function import pprint, time def getWordPattern(word): @@ -32,7 +33,7 @@ def main(): fo.write(pprint.pformat(allPatterns)) totalTime = round(time.time() - startTime, 2) - print('Done! [', totalTime, 'seconds ]') + print(('Done! [', totalTime, 'seconds ]')) if __name__ == '__main__': main() diff --git a/searches/binary_search.py b/searches/binary_search.py index c54aa96a1..93bf189cc 100644 --- a/searches/binary_search.py +++ b/searches/binary_search.py @@ -12,6 +12,11 @@ python binary_search.py from __future__ import print_function import bisect +try: + raw_input # Python 2 +except NameError: + raw_input = input # Python 3 + def binary_search(sorted_collection, item): """Pure implementation of binary search algorithm in Python @@ -137,23 +142,14 @@ def __assert_sorted(collection): if __name__ == '__main__': import sys - # For python 2.x and 3.x compatibility: 3.x has no raw_input builtin - # otherwise 2.x's input builtin function is too "smart" - if sys.version_info.major < 3: - input_function = raw_input - else: - input_function = input - - user_input = input_function('Enter numbers separated by comma:\n') + user_input = raw_input('Enter numbers separated by comma:\n').strip() collection = [int(item) for item in user_input.split(',')] try: __assert_sorted(collection) except ValueError: sys.exit('Sequence must be sorted to apply binary search') - target_input = input_function( - 'Enter a single number to be found in the list:\n' - ) + target_input = raw_input('Enter a single number to be found in the list:\n') target = int(target_input) result = binary_search(collection, target) if result is not None: diff --git a/searches/interpolation_search.py b/searches/interpolation_search.py index 068d9c554..7b765c454 100644 --- a/searches/interpolation_search.py +++ b/searches/interpolation_search.py @@ -4,6 +4,11 @@ This is pure python implementation of interpolation search algorithm from __future__ import print_function import bisect +try: + raw_input # Python 2 +except NameError: + raw_input = input # Python 3 + def interpolation_search(sorted_collection, item): """Pure implementation of interpolation search algorithm in Python @@ -77,26 +82,18 @@ def __assert_sorted(collection): if __name__ == '__main__': import sys - # For python 2.x and 3.x compatibility: 3.x has no raw_input builtin - # otherwise 2.x's input builtin function is too "smart" - if sys.version_info.major < 3: - input_function = raw_input - else: - input_function = input - user_input = input_function('Enter numbers separated by comma:\n') + user_input = raw_input('Enter numbers separated by comma:\n').strip() collection = [int(item) for item in user_input.split(',')] try: __assert_sorted(collection) except ValueError: sys.exit('Sequence must be sorted to apply interpolation search') - target_input = input_function( - 'Enter a single number to be found in the list:\n' - ) + target_input = raw_input('Enter a single number to be found in the list:\n') target = int(target_input) result = interpolation_search(collection, target) if result is not None: print('{} found at positions: {}'.format(target, result)) else: - print('Not found') \ No newline at end of file + print('Not found') diff --git a/searches/jump_search.py b/searches/jump_search.py index e2b4008a4..4cff92bb5 100644 --- a/searches/jump_search.py +++ b/searches/jump_search.py @@ -1,3 +1,4 @@ +from __future__ import print_function import math def jump_search(arr, x): n = len(arr) diff --git a/searches/linear_search.py b/searches/linear_search.py index ce8098b1a..50c6eaad5 100644 --- a/searches/linear_search.py +++ b/searches/linear_search.py @@ -11,6 +11,10 @@ python linear_search.py """ from __future__ import print_function +try: + raw_input # Python 2 +except NameError: + raw_input = input # Python 3 def linear_search(sequence, target): """Pure implementation of linear search algorithm in Python @@ -39,21 +43,10 @@ def linear_search(sequence, target): if __name__ == '__main__': - import sys - - # For python 2.x and 3.x compatibility: 3.x has no raw_input builtin - # otherwise 2.x's input builtin function is too "smart" - if sys.version_info.major < 3: - input_function = raw_input - else: - input_function = input - - user_input = input_function('Enter numbers separated by coma:\n') + user_input = raw_input('Enter numbers separated by coma:\n').strip() sequence = [int(item) for item in user_input.split(',')] - target_input = input_function( - 'Enter a single number to be found in the list:\n' - ) + target_input = raw_input('Enter a single number to be found in the list:\n') target = int(target_input) result = linear_search(sequence, target) if result is not None: diff --git a/searches/ternary_search.py b/searches/ternary_search.py index 3b1c75314..c610f9b3c 100644 --- a/searches/ternary_search.py +++ b/searches/ternary_search.py @@ -6,9 +6,15 @@ This is a type of divide and conquer algorithm which divides the search space in Time Complexity : O(log3 N) Space Complexity : O(1) ''' +from __future__ import print_function import sys +try: + raw_input # Python 2 +except NameError: + raw_input = input # Python 3 + # This is the precision for this function which can be altered. # It is recommended for users to keep this number greater than or equal to 10. precision = 10 @@ -81,16 +87,7 @@ def __assert_sorted(collection): if __name__ == '__main__': - - # For python 2.x and 3.x compatibility: 3.x has not raw_input builtin - # otherwise 2.x's input builtin function is too "smart" - - if sys.version_info.major < 3: - input_function = raw_input - else: - input_function = input - - user_input = input_function('Enter numbers separated by coma:\n') + user_input = raw_input('Enter numbers separated by coma:\n').strip() collection = [int(item) for item in user_input.split(',')] try: @@ -98,9 +95,7 @@ if __name__ == '__main__': except ValueError: sys.exit('Sequence must be sorted to apply the ternary search') - target_input = input_function( - 'Enter a single number to be found in the list:\n' - ) + target_input = raw_input('Enter a single number to be found in the list:\n') target = int(target_input) result1 = ite_ternary_search(collection, target) result2 = rec_ternary_search(0, len(collection)-1, collection, target) diff --git a/sorts/bogosort.py b/sorts/bogosort.py index ce1982c53..2a3d320b0 100644 --- a/sorts/bogosort.py +++ b/sorts/bogosort.py @@ -39,15 +39,11 @@ def bogosort(collection): return collection if __name__ == '__main__': - import sys + try: + raw_input # Python 2 + except NameError: + raw_input = input # Python 3 - # For python 2.x and 3.x compatibility: 3.x has no raw_input builtin - # otherwise 2.x's input builtin function is too "smart" - if sys.version_info.major < 3: - input_function = raw_input - else: - input_function = input - - user_input = input_function('Enter numbers separated by a comma:\n') + user_input = raw_input('Enter numbers separated by a comma:\n').stript() unsorted = [int(item) for item in user_input.split(',')] print(bogosort(unsorted)) diff --git a/sorts/bubble_sort.py b/sorts/bubble_sort.py index d26adc89c..b7f1b3c05 100644 --- a/sorts/bubble_sort.py +++ b/sorts/bubble_sort.py @@ -40,14 +40,11 @@ def bubble_sort(collection): if __name__ == '__main__': - import sys - # For python 2.x and 3.x compatibility: 3.x has no raw_input builtin - # otherwise 2.x's input builtin function is too "smart" - if sys.version_info.major < 3: - input_function = raw_input - else: - input_function = input + try: + raw_input # Python 2 + except NameError: + raw_input = input # Python 3 - user_input = input_function('Enter numbers separated by a comma:\n') + user_input = raw_input('Enter numbers separated by a comma:\n').strip() unsorted = [int(item) for item in user_input.split(',')] print(bubble_sort(unsorted)) diff --git a/sorts/bucket_sort.py b/sorts/bucket_sort.py index e378d65f4..1c4b4577a 100644 --- a/sorts/bucket_sort.py +++ b/sorts/bucket_sort.py @@ -13,6 +13,7 @@ # Time Complexity of Solution: # Best Case O(n); Average Case O(n); Worst Case O(n) +from __future__ import print_function from P26_InsertionSort import insertionSort import math diff --git a/sorts/cocktail_shaker_sort.py b/sorts/cocktail_shaker_sort.py index c09d64408..8ad3383bb 100644 --- a/sorts/cocktail_shaker_sort.py +++ b/sorts/cocktail_shaker_sort.py @@ -21,16 +21,12 @@ def cocktail_shaker_sort(unsorted): return unsorted if __name__ == '__main__': - import sys - - # For python 2.x and 3.x compatibility: 3.x has no raw_input builtin - # otherwise 2.x's input builtin function is too "smart" - if sys.version_info.major < 3: - input_function = raw_input - else: - input_function = input + try: + raw_input # Python 2 + except NameError: + raw_input = input # Python 3 - user_input = input_function('Enter numbers separated by a comma:\n') + user_input = raw_input('Enter numbers separated by a comma:\n').strip() unsorted = [int(item) for item in user_input.split(',')] cocktail_shaker_sort(unsorted) - print(unsorted) \ No newline at end of file + print(unsorted) diff --git a/sorts/counting_sort.py b/sorts/counting_sort.py index 13e4554ae..4ca682b13 100644 --- a/sorts/counting_sort.py +++ b/sorts/counting_sort.py @@ -59,14 +59,11 @@ def counting_sort(collection): if __name__ == '__main__': - import sys - # For python 2.x and 3.x compatibility: 3.x has not raw_input builtin - # otherwise 2.x's input builtin function is too "smart" - if sys.version_info.major < 3: - input_function = raw_input - else: - input_function = input + try: + raw_input # Python 2 + except NameError: + raw_input = input # Python 3 - user_input = input_function('Enter numbers separated by a comma:\n') + user_input = raw_input('Enter numbers separated by a comma:\n').strip() unsorted = [int(item) for item in user_input.split(',')] print(counting_sort(unsorted)) diff --git a/sorts/countingsort.py b/sorts/countingsort.py index c7b502d8f..18ee8b851 100644 --- a/sorts/countingsort.py +++ b/sorts/countingsort.py @@ -1,3 +1,4 @@ +from __future__ import print_function # Python program for counting sort # This is the main function that sort the given string arr[] in diff --git a/sorts/external-sort.py b/sorts/external-sort.py index eca26012d..6c4adc94c 100644 --- a/sorts/external-sort.py +++ b/sorts/external-sort.py @@ -158,4 +158,4 @@ def main(): if __name__ == '__main__': -main() \ No newline at end of file + main() diff --git a/sorts/gnome_sort.py b/sorts/gnome_sort.py index 4f04ff384..2927b097f 100644 --- a/sorts/gnome_sort.py +++ b/sorts/gnome_sort.py @@ -19,16 +19,12 @@ def gnome_sort(unsorted): i = 1 if __name__ == '__main__': - import sys - - # For python 2.x and 3.x compatibility: 3.x has no raw_input builtin - # otherwise 2.x's input builtin function is too "smart" - if sys.version_info.major < 3: - input_function = raw_input - else: - input_function = input + try: + raw_input # Python 2 + except NameError: + raw_input = input # Python 3 - user_input = input_function('Enter numbers separated by a comma:\n') + user_input = raw_input('Enter numbers separated by a comma:\n').strip() unsorted = [int(item) for item in user_input.split(',')] gnome_sort(unsorted) - print(unsorted) \ No newline at end of file + print(unsorted) diff --git a/sorts/heap_sort.py b/sorts/heap_sort.py index 2d9dd844d..3c72abca8 100644 --- a/sorts/heap_sort.py +++ b/sorts/heap_sort.py @@ -54,12 +54,11 @@ def heap_sort(unsorted): return unsorted if __name__ == '__main__': - import sys - if sys.version_info.major < 3: - input_function = raw_input - else: - input_function = input + try: + raw_input # Python 2 + except NameError: + raw_input = input # Python 3 - user_input = input_function('Enter numbers separated by a comma:\n') + user_input = raw_input('Enter numbers separated by a comma:\n').strip() unsorted = [int(item) for item in user_input.split(',')] print(heap_sort(unsorted)) diff --git a/sorts/insertion_sort.py b/sorts/insertion_sort.py index 33bd27c8f..b7a4aa7a3 100644 --- a/sorts/insertion_sort.py +++ b/sorts/insertion_sort.py @@ -39,15 +39,11 @@ def insertion_sort(collection): if __name__ == '__main__': - import sys + try: + raw_input # Python 2 + except NameError: + raw_input = input # Python 3 - # For python 2.x and 3.x compatibility: 3.x has no raw_input builtin - # otherwise 2.x's input builtin function is too "smart" - if sys.version_info.major < 3: - input_function = raw_input - else: - input_function = input - - user_input = input_function('Enter numbers separated by a comma:\n') + user_input = raw_input('Enter numbers separated by a comma:\n').strip() unsorted = [int(item) for item in user_input.split(',')] print(insertion_sort(unsorted)) diff --git a/sorts/merge_sort.py b/sorts/merge_sort.py index ca8dbc33c..ca4d319fa 100644 --- a/sorts/merge_sort.py +++ b/sorts/merge_sort.py @@ -62,15 +62,11 @@ def merge_sort(collection): if __name__ == '__main__': - import sys + try: + raw_input # Python 2 + except NameError: + raw_input = input # Python 3 - # For python 2.x and 3.x compatibility: 3.x has no raw_input builtin - # otherwise 2.x's input builtin function is too "smart" - if sys.version_info.major < 3: - input_function = raw_input - else: - input_function = input - - user_input = input_function('Enter numbers separated by a comma:\n') + user_input = raw_input('Enter numbers separated by a comma:\n').strip() unsorted = [int(item) for item in user_input.split(',')] print(merge_sort(unsorted)) diff --git a/sorts/quick_sort.py b/sorts/quick_sort.py index 52e37b587..136cbc021 100644 --- a/sorts/quick_sort.py +++ b/sorts/quick_sort.py @@ -40,15 +40,11 @@ def quick_sort(ARRAY): if __name__ == '__main__': - import sys + try: + raw_input # Python 2 + except NameError: + raw_input = input # Python 3 - # For python 2.x and 3.x compatibility: 3.x has no raw_input builtin - # otherwise 2.x's input builtin function is too "smart" - if sys.version_info.major < 3: - input_function = raw_input - else: - input_function = input - - user_input = input_function('Enter numbers separated by a comma:\n') + user_input = raw_input('Enter numbers separated by a comma:\n').strip() unsorted = [ int(item) for item in user_input.split(',') ] print( quick_sort(unsorted) ) diff --git a/sorts/random_normaldistribution_quicksort.py b/sorts/random_normaldistribution_quicksort.py index 19b180578..bd730b3b1 100644 --- a/sorts/random_normaldistribution_quicksort.py +++ b/sorts/random_normaldistribution_quicksort.py @@ -1,3 +1,4 @@ +from __future__ import print_function from random import randint from tempfile import TemporaryFile import numpy as np diff --git a/sorts/selection_sort.py b/sorts/selection_sort.py index 752496e98..432d14090 100644 --- a/sorts/selection_sort.py +++ b/sorts/selection_sort.py @@ -43,14 +43,11 @@ def selection_sort(collection): if __name__ == '__main__': - import sys - # For python 2.x and 3.x compatibility: 3.x has no raw_input builtin - # otherwise 2.x's input builtin function is too "smart" - if sys.version_info.major < 3: - input_function = raw_input - else: - input_function = input + try: + raw_input # Python 2 + except NameError: + raw_input = input # Python 3 - user_input = input_function('Enter numbers separated by a comma:\n') + user_input = raw_input('Enter numbers separated by a comma:\n').strip() unsorted = [int(item) for item in user_input.split(',')] print(selection_sort(unsorted)) diff --git a/sorts/shell_sort.py b/sorts/shell_sort.py index de3d84f72..dc1846758 100644 --- a/sorts/shell_sort.py +++ b/sorts/shell_sort.py @@ -44,14 +44,11 @@ def shell_sort(collection): return collection if __name__ == '__main__': - import sys - # For python 2.x and 3.x compatibility: 3.x has no raw_input builtin - # otherwise 2.x's input builtin function is too "smart" - if sys.version_info.major < 3: - input_function = raw_input - else: - input_function = input + try: + raw_input # Python 2 + except NameError: + raw_input = input # Python 3 - user_input = input_function('Enter numbers separated by a comma:\n') + user_input = raw_input('Enter numbers separated by a comma:\n').strip() unsorted = [int(item) for item in user_input.split(',')] print(shell_sort(unsorted)) diff --git a/sorts/timsort.py b/sorts/timsort.py index 8c75b5191..80c5cd1e8 100644 --- a/sorts/timsort.py +++ b/sorts/timsort.py @@ -1,3 +1,4 @@ +from __future__ import print_function def binary_search(lst, item, start, end): if start == end: if lst[start] > item: diff --git a/sorts/topological_sort.py b/sorts/topological_sort.py index 5de1cc2b7..52dc34f4f 100644 --- a/sorts/topological_sort.py +++ b/sorts/topological_sort.py @@ -1,3 +1,4 @@ +from __future__ import print_function # a # / \ # b c diff --git a/traversals/binary_tree_traversals.py b/traversals/binary_tree_traversals.py index 9d14a1e7e..cbcaf08b7 100644 --- a/traversals/binary_tree_traversals.py +++ b/traversals/binary_tree_traversals.py @@ -4,6 +4,11 @@ This is pure python implementation of tree traversal algorithms from __future__ import print_function import queue +try: + raw_input # Python 2 +except NameError: + raw_input = input # Python 3 + class TreeNode: def __init__(self, data): @@ -15,26 +20,26 @@ class TreeNode: def build_tree(): print("\n********Press N to stop entering at any point of time********\n") print("Enter the value of the root node: ", end="") - check=input() - if check=='N' or check=='n': + check = raw_input().strip().lower() + if check == 'n': return None - data=int(check) + data = int(check) q = queue.Queue() tree_node = TreeNode(data) q.put(tree_node) while not q.empty(): node_found = q.get() print("Enter the left node of %s: " % node_found.data, end="") - check=input() - if check=='N' or check =='n': + check = raw_input().strip().lower() + if check == 'n': return tree_node left_data = int(check) left_node = TreeNode(left_data) node_found.left = left_node q.put(left_node) print("Enter the right node of %s: " % node_found.data, end="") - check = input() - if check == 'N' or check == 'n': + check = raw_input().strip().lower() + if check == 'n': return tree_node right_data = int(check) right_node = TreeNode(right_data) @@ -81,15 +86,7 @@ def level_order(node): if __name__ == '__main__': - import sys - print("\n********* Binary Tree Traversals ************\n") - # For python 2.x and 3.x compatibility: 3.x has no raw_input builtin - # otherwise 2.x's input builtin function is too "smart" - if sys.version_info.major < 3: - input_function = raw_input - else: - input_function = input node = build_tree() print("\n********* Pre Order Traversal ************")