diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 3202b817f1c5..8c0f54ad528d 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -56,7 +56,7 @@ We want your work to be readable by others; therefore, we encourage you to note ```python """ - This function sums a and b + This function sums a and b """ def sum(a, b): return a + b @@ -82,13 +82,13 @@ We want your work to be readable by others; therefore, we encourage you to note The following "testing" approaches are **not** encouraged: ```python - input('Enter your input:') + input('Enter your input:') # Or even worse... - input = eval(raw_input("Enter your input: ")) + input = eval(input("Enter your input: ")) ``` - + However, if your code uses __input()__ then we encourage you to gracefully deal with leading and trailing whitespace in user input by adding __.strip()__ to the end as in: - + ```python starting_value = int(input("Please enter a starting value: ").strip()) ``` @@ -99,13 +99,13 @@ We want your work to be readable by others; therefore, we encourage you to note def sumab(a, b): return a + b # Write tests this way: - print(sumab(1,2)) # 1+2 = 3 - print(sumab(6,4)) # 6+4 = 10 + print(sumab(1, 2)) # 1+2 = 3 + print(sumab(6, 4)) # 6+4 = 10 # Or this way: - print("1 + 2 = ", sumab(1,2)) # 1+2 = 3 - print("6 + 4 = ", sumab(6,4)) # 6+4 = 10 + print("1 + 2 = ", sumab(1, 2)) # 1+2 = 3 + print("6 + 4 = ", sumab(6, 4)) # 6+4 = 10 ``` - + Better yet, if you know how to write [__doctests__](https://docs.python.org/3/library/doctest.html), please consider adding them. - Avoid importing external libraries for basic algorithms. Only use those libraries for complicated algorithms. diff --git a/ciphers/affine_cipher.py b/ciphers/affine_cipher.py index af5f4e0ff4c6..a5d94f087dbf 100644 --- a/ciphers/affine_cipher.py +++ b/ciphers/affine_cipher.py @@ -1,4 +1,3 @@ -from __future__ import print_function import sys, random, cryptomath_module as cryptoMath SYMBOLS = r""" !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~""" diff --git a/ciphers/atbash.py b/ciphers/atbash.py index 5653f0213745..9ed47e0874f8 100644 --- a/ciphers/atbash.py +++ b/ciphers/atbash.py @@ -1,23 +1,15 @@ -try: # Python 2 - raw_input - unichr -except NameError: # Python 3 - raw_input = input - unichr = chr - - -def Atbash(): +def atbash(): output="" - for i in raw_input("Enter the sentence to be encrypted ").strip(): + for i in input("Enter the sentence to be encrypted ").strip(): extract = ord(i) if 65 <= extract <= 90: - output += unichr(155-extract) + output += chr(155-extract) elif 97 <= extract <= 122: - output += unichr(219-extract) + output += chr(219-extract) else: - output+=i + output += i print(output) if __name__ == '__main__': - Atbash() + atbash() diff --git a/ciphers/brute_force_caesar_cipher.py b/ciphers/brute_force_caesar_cipher.py index 3b0716442fc5..3e6e975c8297 100644 --- a/ciphers/brute_force_caesar_cipher.py +++ b/ciphers/brute_force_caesar_cipher.py @@ -1,4 +1,3 @@ -from __future__ import print_function def decrypt(message): """ >>> decrypt('TMDETUX PMDVU') diff --git a/ciphers/onepad_cipher.py b/ciphers/onepad_cipher.py index 6afbd45249ec..1dac270bda1f 100644 --- a/ciphers/onepad_cipher.py +++ b/ciphers/onepad_cipher.py @@ -1,5 +1,3 @@ -from __future__ import print_function - import random @@ -15,7 +13,7 @@ def encrypt(self, text): cipher.append(c) key.append(k) return cipher, key - + def decrypt(self, cipher, key): '''Function to decrypt text using psedo-random numbers.''' plain = [] diff --git a/ciphers/rabin_miller.py b/ciphers/rabin_miller.py index f71fb03c0051..21378cff6885 100644 --- a/ciphers/rabin_miller.py +++ b/ciphers/rabin_miller.py @@ -1,4 +1,3 @@ -from __future__ import print_function # Primality Testing with the Rabin-Miller Algorithm import random diff --git a/ciphers/rot13.py b/ciphers/rot13.py index 2abf981e9d7d..208de4890e67 100644 --- a/ciphers/rot13.py +++ b/ciphers/rot13.py @@ -1,4 +1,3 @@ -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 d81f1ffc1a1e..02e5d95d1e95 100644 --- a/ciphers/rsa_cipher.py +++ b/ciphers/rsa_cipher.py @@ -1,4 +1,3 @@ -from __future__ import print_function import sys, rsa_key_generator as rkg, os DEFAULT_BLOCK_SIZE = 128 @@ -16,7 +15,7 @@ def main(): if mode == 'encrypt': if not os.path.exists('rsa_pubkey.txt'): rkg.makeKeyFiles('rsa', 1024) - + message = input('\nEnter message: ') pubKeyFilename = 'rsa_pubkey.txt' print('Encrypting and writing to %s...' % (filename)) diff --git a/ciphers/rsa_key_generator.py b/ciphers/rsa_key_generator.py index 541e90d6e884..7cd7163b68d5 100644 --- a/ciphers/rsa_key_generator.py +++ b/ciphers/rsa_key_generator.py @@ -1,4 +1,3 @@ -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 1bdd7dc04a57..5da07f8526b9 100644 --- a/ciphers/simple_substitution_cipher.py +++ b/ciphers/simple_substitution_cipher.py @@ -1,4 +1,3 @@ -from __future__ import print_function import sys, random LETTERS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' @@ -18,7 +17,7 @@ def main(): translated = decryptMessage(key, message) print('\n%sion: \n%s' % (mode.title(), translated)) - + def checkValidKey(key): keyList = list(key) lettersList = list(LETTERS) @@ -49,7 +48,7 @@ def translateMessage(key, message, mode): if mode == 'decrypt': charsA, charsB = charsB, charsA - + for symbol in message: if symbol.upper() in charsA: symIndex = charsA.find(symbol.upper()) diff --git a/ciphers/transposition_cipher.py b/ciphers/transposition_cipher.py index dbb358315d22..1c2ed0aa0452 100644 --- a/ciphers/transposition_cipher.py +++ b/ciphers/transposition_cipher.py @@ -1,4 +1,3 @@ -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 a186cf81cde7..8ebfc1ea7e0c 100644 --- a/ciphers/transposition_cipher_encrypt_decrypt_file.py +++ b/ciphers/transposition_cipher_encrypt_decrypt_file.py @@ -1,4 +1,3 @@ -from __future__ import print_function import time, os, sys import transposition_cipher as transCipher @@ -16,7 +15,7 @@ def main(): response = input('> ') if not response.lower().startswith('y'): sys.exit() - + startTime = time.time() if mode.lower().startswith('e'): with open(inputFile) as f: @@ -29,9 +28,9 @@ def main(): with open(outputFile, 'w') as outputObj: outputObj.write(translated) - + totalTime = round(time.time() - startTime, 2) print(('Done (', totalTime, 'seconds )')) - + if __name__ == '__main__': main() diff --git a/ciphers/vigenere_cipher.py b/ciphers/vigenere_cipher.py index 5d5be0792835..95eeb431109f 100644 --- a/ciphers/vigenere_cipher.py +++ b/ciphers/vigenere_cipher.py @@ -1,4 +1,3 @@ -from __future__ import print_function LETTERS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' def main(): diff --git a/data_structures/binary_tree/binary_search_tree.py b/data_structures/binary_tree/binary_search_tree.py index cef5b55f245d..634b6cbcc231 100644 --- a/data_structures/binary_tree/binary_search_tree.py +++ b/data_structures/binary_tree/binary_search_tree.py @@ -1,7 +1,6 @@ ''' A binary search Tree ''' -from __future__ import print_function class Node: def __init__(self, label, parent): @@ -66,8 +65,8 @@ def insert(self, label): else: parent_node.setRight(new_node) #Set parent to the new node - new_node.setParent(parent_node) - + new_node.setParent(parent_node) + def delete(self, label): if (not self.empty()): #Look for the node with that label @@ -92,7 +91,7 @@ def delete(self, label): self.delete(tmpNode.getLabel()) #Assigns the value to the node to delete and keesp tree structure node.setLabel(tmpNode.getLabel()) - + def getNode(self, label): curr_node = None #If the tree is not empty @@ -177,7 +176,7 @@ def traversalTree(self, traversalFunction = None, root = None): #Returns a list of nodes in the order that the users wants to return traversalFunction(self.root) - #Returns an string of all the nodes labels in the list + #Returns an string of all the nodes labels in the list #In Order Traversal def __str__(self): list = self.__InOrderTraversal(self.root) @@ -203,7 +202,7 @@ def testBinarySearchTree(): / \ \ 1 6 14 / \ / - 4 7 13 + 4 7 13 ''' r''' @@ -236,11 +235,11 @@ def testBinarySearchTree(): print("The label -1 exists") else: print("The label -1 doesn't exist") - + if(not t.empty()): print(("Max Value: ", t.getMax().getLabel())) print(("Min Value: ", t.getMin().getLabel())) - + t.delete(13) t.delete(10) t.delete(8) diff --git a/data_structures/binary_tree/fenwick_tree.py b/data_structures/binary_tree/fenwick_tree.py index ef984082d9e8..30a87fbd7fcf 100644 --- a/data_structures/binary_tree/fenwick_tree.py +++ b/data_structures/binary_tree/fenwick_tree.py @@ -1,4 +1,3 @@ -from __future__ import print_function class FenwickTree: def __init__(self, SIZE): # create fenwick tree with size SIZE diff --git a/data_structures/binary_tree/lazy_segment_tree.py b/data_structures/binary_tree/lazy_segment_tree.py index 215399976dd3..bbe37a6eb97f 100644 --- a/data_structures/binary_tree/lazy_segment_tree.py +++ b/data_structures/binary_tree/lazy_segment_tree.py @@ -1,4 +1,3 @@ -from __future__ import print_function import math class SegmentTree: diff --git a/data_structures/binary_tree/segment_tree.py b/data_structures/binary_tree/segment_tree.py index 7e61198ca59c..da3d15f26b6a 100644 --- a/data_structures/binary_tree/segment_tree.py +++ b/data_structures/binary_tree/segment_tree.py @@ -1,4 +1,3 @@ -from __future__ import print_function import math class SegmentTree: diff --git a/data_structures/heap/heap.py b/data_structures/heap/heap.py index 39778f725c3a..2373d71bb897 100644 --- a/data_structures/heap/heap.py +++ b/data_structures/heap/heap.py @@ -1,15 +1,8 @@ #!/usr/bin/python -from __future__ import print_function, division - -try: - raw_input # Python 2 -except NameError: - raw_input = input # Python 3 - -#This heap class start from here. +# This heap class start from here. class Heap: - def __init__(self): #Default constructor of heap class. + def __init__(self): # Default constructor of heap class. self.h = [] self.currsize = 0 @@ -79,7 +72,7 @@ def display(self): #This function is used to print the heap. print(self.h) def main(): - l = list(map(int, raw_input().split())) + l = list(map(int, input().split())) h = Heap() h.buildHeap(l) h.heapSort() diff --git a/data_structures/linked_list/doubly_linked_list.py b/data_structures/linked_list/doubly_linked_list.py index 75b1f889dfc2..23d91383fa0e 100644 --- a/data_structures/linked_list/doubly_linked_list.py +++ b/data_structures/linked_list/doubly_linked_list.py @@ -4,14 +4,13 @@ - Each link references the next link and the previous one. - A Doubly Linked List (DLL) contains an extra pointer, typically called previous pointer, together with next pointer and data which are there in singly linked list. - Advantages over SLL - IT can be traversed in both forward and backward direction.,Delete operation is more efficent''' -from __future__ import print_function class LinkedList: #making main class named linked list def __init__(self): self.head = None self.tail = None - + def insertHead(self, x): newLink = Link(x) #Create a new link with a value attached to it if(self.isEmpty() == True): #Set the first element added to be the tail @@ -20,52 +19,52 @@ def insertHead(self, x): self.head.previous = newLink # newLink <-- currenthead(head) newLink.next = self.head # newLink <--> currenthead(head) self.head = newLink # newLink(head) <--> oldhead - + def deleteHead(self): temp = self.head - self.head = self.head.next # oldHead <--> 2ndElement(head) + self.head = self.head.next # oldHead <--> 2ndElement(head) self.head.previous = None # oldHead --> 2ndElement(head) nothing pointing at it so the old head will be removed if(self.head is None): self.tail = None #if empty linked list return temp - + def insertTail(self, x): newLink = Link(x) newLink.next = None # currentTail(tail) newLink --> self.tail.next = newLink # currentTail(tail) --> newLink --> newLink.previous = self.tail #currentTail(tail) <--> newLink --> self.tail = newLink # oldTail <--> newLink(tail) --> - + def deleteTail(self): temp = self.tail self.tail = self.tail.previous # 2ndLast(tail) <--> oldTail --> None self.tail.next = None # 2ndlast(tail) --> None return temp - + def delete(self, x): current = self.head - + while(current.value != x): # Find the position to delete current = current.next - + if(current == self.head): self.deleteHead() - + elif(current == self.tail): self.deleteTail() - + else: #Before: 1 <--> 2(current) <--> 3 current.previous.next = current.next # 1 --> 3 current.next.previous = current.previous # 1 <--> 3 - + def isEmpty(self): #Will return True if the list is empty return(self.head is None) - + def display(self): #Prints contents of the list current = self.head while(current != None): current.displayLink() - current = current.next + current = current.next print() class Link: diff --git a/data_structures/linked_list/singly_linked_list.py b/data_structures/linked_list/singly_linked_list.py index 5ae97523b9a1..5943b88d5964 100644 --- a/data_structures/linked_list/singly_linked_list.py +++ b/data_structures/linked_list/singly_linked_list.py @@ -1,6 +1,3 @@ -from __future__ import print_function - - class Node: # create a Node def __init__(self, data): self.data = data # given data @@ -10,7 +7,7 @@ def __init__(self, data): class Linked_List: def __init__(self): self.Head = None # Initialize Head to None - + def insert_tail(self, data): if(self.Head is None): self.insert_head(data) #If this is first node, call insert_head else: @@ -37,7 +34,7 @@ def delete_head(self): # delete from head self.Head = self.Head.next temp.next = None return temp - + def delete_tail(self): # delete from tail tamp = self.Head if self.Head != None: @@ -46,7 +43,7 @@ def delete_tail(self): # delete from tail else: while tamp.next.next is not None: # find the 2nd last element tamp = tamp.next - tamp.next, tamp = None, tamp.next #(2nd last element).next = None and tamp = last element + tamp.next, tamp = None, tamp.next #(2nd last element).next = None and tamp = last element return tamp def isEmpty(self): @@ -79,7 +76,7 @@ def main(): print("\nPrint List : ") A.printList() print("\nInserting 1st at Tail") - a3=input() + a3=input() A.insert_tail(a3) print("Inserting 2nd at Tail") a4=input() @@ -96,6 +93,6 @@ def main(): A.reverse() print("\nPrint List : ") A.printList() - + if __name__ == '__main__': main() diff --git a/data_structures/queue/double_ended_queue.py b/data_structures/queue/double_ended_queue.py index 838bf2f4bc36..a2fc8f66ec22 100644 --- a/data_structures/queue/double_ended_queue.py +++ b/data_structures/queue/double_ended_queue.py @@ -1,4 +1,3 @@ -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 36a4e07a97a3..3f43ccbf5760 100644 --- a/data_structures/stacks/balanced_parentheses.py +++ b/data_structures/stacks/balanced_parentheses.py @@ -1,6 +1,3 @@ -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 9376b55b8b23..84a5d1480a24 100644 --- a/data_structures/stacks/infix_to_postfix_conversion.py +++ b/data_structures/stacks/infix_to_postfix_conversion.py @@ -1,5 +1,3 @@ -from __future__ import print_function -from __future__ import absolute_import import string from .stack import Stack diff --git a/data_structures/stacks/next_greater_element.py b/data_structures/stacks/next_greater_element.py index bca83339592c..2e67f1764a5a 100644 --- a/data_structures/stacks/next_greater_element.py +++ b/data_structures/stacks/next_greater_element.py @@ -1,17 +1,16 @@ -from __future__ import print_function # Function to print element and NGE pair for all elements of list def printNGE(arr): - + for i in range(0, len(arr), 1): - + next = -1 for j in range(i+1, len(arr), 1): if arr[i] < arr[j]: next = arr[j] break - + print(str(arr[i]) + " -- " + str(next)) - + # Driver program to test above function arr = [11,13,21,3] printNGE(arr) diff --git a/data_structures/stacks/stack.py b/data_structures/stacks/stack.py index 7f979d927d08..387367db2fcc 100644 --- a/data_structures/stacks/stack.py +++ b/data_structures/stacks/stack.py @@ -1,4 +1,3 @@ -from __future__ import print_function __author__ = 'Omkar Pathak' diff --git a/data_structures/stacks/stock_span_problem.py b/data_structures/stacks/stock_span_problem.py index e9afebc193b6..47d916fde9ed 100644 --- a/data_structures/stacks/stock_span_problem.py +++ b/data_structures/stacks/stock_span_problem.py @@ -6,7 +6,6 @@ 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) diff --git a/divide_and_conquer/convex_hull.py b/divide_and_conquer/convex_hull.py index f15d74ddea68..42219794aed1 100644 --- a/divide_and_conquer/convex_hull.py +++ b/divide_and_conquer/convex_hull.py @@ -1,18 +1,16 @@ -from __future__ import print_function, absolute_import, division - from numbers import Number """ -The convex hull problem is problem of finding all the vertices of convex polygon, P of +The convex hull problem is problem of finding all the vertices of convex polygon, P of a set of points in a plane such that all the points are either on the vertices of P or -inside P. TH convex hull problem has several applications in geometrical problems, -computer graphics and game development. +inside P. TH convex hull problem has several applications in geometrical problems, +computer graphics and game development. -Two algorithms have been implemented for the convex hull problem here. +Two algorithms have been implemented for the convex hull problem here. 1. A brute-force algorithm which runs in O(n^3) 2. A divide-and-conquer algorithm which runs in O(n^3) There are other several other algorithms for the convex hull problem -which have not been implemented here, yet. +which have not been implemented here, yet. """ diff --git a/divide_and_conquer/inversions.py b/divide_and_conquer/inversions.py index 527741cad3b7..e4d50b7d4729 100644 --- a/divide_and_conquer/inversions.py +++ b/divide_and_conquer/inversions.py @@ -1,15 +1,13 @@ -from __future__ import print_function, absolute_import, division - """ Given an array-like data structure A[1..n], how many pairs -(i, j) for all 1 <= i < j <= n such that A[i] > A[j]? These pairs are -called inversions. Counting the number of such inversions in an array-like -object is the important. Among other things, counting inversions can help +(i, j) for all 1 <= i < j <= n such that A[i] > A[j]? These pairs are +called inversions. Counting the number of such inversions in an array-like +object is the important. Among other things, counting inversions can help us determine how close a given array is to being sorted - + In this implementation, I provide two algorithms, a divide-and-conquer -algorithm which runs in nlogn and the brute-force n^2 algorithm. - +algorithm which runs in nlogn and the brute-force n^2 algorithm. + """ diff --git a/dynamic_programming/bitmask.py b/dynamic_programming/bitmask.py index 213b22fe9051..6685e1c68ee6 100644 --- a/dynamic_programming/bitmask.py +++ b/dynamic_programming/bitmask.py @@ -9,27 +9,26 @@ """ -from __future__ import print_function from collections import defaultdict class AssignmentUsingBitmask: def __init__(self,task_performed,total): - + self.total_tasks = total #total no of tasks (N) - + # DP table will have a dimension of (2^M)*N # initially all values are set to -1 self.dp = [[-1 for i in range(total+1)] for j in range(2**len(task_performed))] - + self.task = defaultdict(list) #stores the list of persons for each task - + #finalmask is used to check if all persons are included by setting all bits to 1 self.finalmask = (1< int: dp = [[0 for _ in range(n+1) ] for _ in range(m+1)] for i in range(m+1): for j in range(n+1): - + if i == 0: #first string is empty dp[i][j] = j - elif j == 0: #second string is empty - dp[i][j] = i + elif j == 0: #second string is empty + dp[i][j] = i elif word1[i-1] == word2[j-1]: #last character of both substing is equal dp[i][j] = dp[i-1][j-1] - else: + else: insert = dp[i][j-1] delete = dp[i-1][j] replace = dp[i-1][j-1] @@ -82,21 +81,13 @@ def min_distance_bottom_up(word1: str, word2: str) -> int: return dp[m][n] if __name__ == '__main__': - try: - raw_input # Python 2 - except NameError: - raw_input = input # Python 3 - solver = EditDistance() print("****************** Testing Edit Distance DP Algorithm ******************") print() - print("Enter the first string: ", end="") - S1 = raw_input().strip() - - print("Enter the second string: ", end="") - S2 = raw_input().strip() + S1 = input("Enter the first string: ").strip() + S2 = input("Enter the second string: ").strip() print() print("The minimum Edit Distance is: %d" % (solver.solve(S1, S2))) @@ -106,4 +97,4 @@ def min_distance_bottom_up(word1: str, word2: str) -> int: - + diff --git a/dynamic_programming/fast_fibonacci.py b/dynamic_programming/fast_fibonacci.py index cbc118467b3c..47248078bd81 100644 --- a/dynamic_programming/fast_fibonacci.py +++ b/dynamic_programming/fast_fibonacci.py @@ -5,7 +5,6 @@ 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 b453ce255853..90fe6386044a 100644 --- a/dynamic_programming/fibonacci.py +++ b/dynamic_programming/fibonacci.py @@ -1,7 +1,6 @@ """ This is a pure Python implementation of Dynamic Programming solution to the fibonacci sequence problem. """ -from __future__ import print_function class Fibonacci: @@ -29,21 +28,16 @@ def get(self, sequence_no=None): if __name__ == '__main__': print("\n********* Fibonacci Series Using Dynamic Programming ************\n") - 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(raw_input().strip()) + N = int(input().strip()) fib = Fibonacci(N) print( - "\n********* Enter different values to get the corresponding fibonacci sequence, enter any negative number to exit. ************\n") + "\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(raw_input().strip()) + i = int(input("Enter value: ").strip()) if i < 0: print("\n********* Good Bye!! ************\n") break diff --git a/dynamic_programming/integer_partition.py b/dynamic_programming/integer_partition.py index 7b27afebaa6c..f17561fc135b 100644 --- a/dynamic_programming/integer_partition.py +++ b/dynamic_programming/integer_partition.py @@ -1,27 +1,15 @@ -from __future__ import print_function - -try: - xrange #Python 2 -except NameError: - xrange = range #Python 3 - -try: - raw_input #Python 2 -except NameError: - raw_input = input #Python 3 - ''' The number of partitions of a number n into at least k parts equals the number of partitions into exactly k parts plus the number of partitions into at least k-1 parts. Subtracting 1 from each part of a partition of n into k parts gives a partition of n-k into k parts. These two facts together are used for this algorithm. ''' def partition(m): - memo = [[0 for _ in xrange(m)] for _ in xrange(m+1)] - for i in xrange(m+1): + memo = [[0 for _ in range(m)] for _ in range(m+1)] + for i in range(m+1): memo[i][0] = 1 - for n in xrange(m+1): - for k in xrange(1, m): + for n in range(m+1): + for k in range(1, m): memo[n][k] += memo[n][k-1] if n-k > 0: memo[n][k] += memo[n-k-1][k] @@ -33,7 +21,7 @@ def partition(m): if len(sys.argv) == 1: try: - n = int(raw_input('Enter a number: ')) + n = int(input('Enter a number: ').strip()) print(partition(n)) except ValueError: print('Please enter a number.') diff --git a/dynamic_programming/longest_common_subsequence.py b/dynamic_programming/longest_common_subsequence.py index 7836fe303688..7447a0cc7810 100644 --- a/dynamic_programming/longest_common_subsequence.py +++ b/dynamic_programming/longest_common_subsequence.py @@ -3,7 +3,6 @@ A subsequence is a sequence that appears in the same relative order, but not necessarily continuous. Example:"abc", "abg" are subsequences of "abcdefgh". """ -from __future__ import print_function def longest_common_subsequence(x: str, y: str): @@ -80,4 +79,3 @@ def longest_common_subsequence(x: str, y: str): assert expected_ln == ln assert expected_subseq == subseq print("len =", ln, ", sub-sequence =", subseq) - diff --git a/dynamic_programming/longest_increasing_subsequence.py b/dynamic_programming/longest_increasing_subsequence.py index b6d165909e70..151a5e0b7c80 100644 --- a/dynamic_programming/longest_increasing_subsequence.py +++ b/dynamic_programming/longest_increasing_subsequence.py @@ -7,10 +7,8 @@ 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 - + ARRAY_LENGTH = len(ARRAY) if(ARRAY_LENGTH <= 1): #If the array contains only one element, we return it (it's the stop condition of recursion) return ARRAY diff --git a/dynamic_programming/longest_increasing_subsequence_o(nlogn).py b/dynamic_programming/longest_increasing_subsequence_o(nlogn).py index 86bec089adc7..9b27ed6be303 100644 --- a/dynamic_programming/longest_increasing_subsequence_o(nlogn).py +++ b/dynamic_programming/longest_increasing_subsequence_o(nlogn).py @@ -1,9 +1,8 @@ -from __future__ import print_function ############################# # Author: Aravind Kashyap # File: lis.py # comments: This programme outputs the Longest Strictly Increasing Subsequence in O(NLogN) -# Where N is the Number of elements in the list +# Where N is the Number of elements in the list ############################# def CeilIndex(v,l,r,key): while r-l > 1: @@ -12,30 +11,30 @@ def CeilIndex(v,l,r,key): r = m else: l = m - + return r - + def LongestIncreasingSubsequenceLength(v): if(len(v) == 0): - return 0 - + return 0 + tail = [0]*len(v) length = 1 - + tail[0] = v[0] - + for i in range(1,len(v)): if v[i] < tail[0]: tail[0] = v[i] elif v[i] > tail[length-1]: tail[length] = v[i] - length += 1 + length += 1 else: tail[CeilIndex(tail,-1,length-1,v[i])] = v[i] - + return length - + if __name__ == "__main__": v = [2, 5, 3, 7, 11, 8, 10, 13, 6] diff --git a/dynamic_programming/longest_sub_array.py b/dynamic_programming/longest_sub_array.py index de2c88a8b525..856b31f03982 100644 --- a/dynamic_programming/longest_sub_array.py +++ b/dynamic_programming/longest_sub_array.py @@ -6,7 +6,6 @@ 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: diff --git a/dynamic_programming/matrix_chain_order.py b/dynamic_programming/matrix_chain_order.py index b8234a65acbe..cb4aec345437 100644 --- a/dynamic_programming/matrix_chain_order.py +++ b/dynamic_programming/matrix_chain_order.py @@ -1,5 +1,3 @@ -from __future__ import print_function - import sys ''' Dynamic Programming diff --git a/dynamic_programming/max_sub_array.py b/dynamic_programming/max_sub_array.py index 56983b7d22c2..d6084ecfd6d9 100644 --- a/dynamic_programming/max_sub_array.py +++ b/dynamic_programming/max_sub_array.py @@ -1,7 +1,6 @@ """ author : Mayank Kumar Jha (mk9440) """ -from __future__ import print_function from typing import List import time import matplotlib.pyplot as plt @@ -10,7 +9,7 @@ def find_max_sub_array(A,low,high): if low==high: return low,high,A[low] else : - mid=(low+high)//2 + 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) @@ -30,7 +29,7 @@ def find_max_cross_sum(A,low,mid,high): if summ > left_sum: left_sum=summ max_left=i - summ=0 + summ=0 for i in range(mid+1,high+1): summ+=A[i] if summ > right_sum: @@ -40,7 +39,7 @@ def find_max_cross_sum(A,low,mid,high): def max_sub_array(nums: List[int]) -> int: """ - Finds the contiguous subarray (can be empty array) + Finds the contiguous subarray (can be empty array) which has the largest sum and return its sum. >>> max_sub_array([-2,1,-3,4,-1,2,1,-5,4]) @@ -50,14 +49,14 @@ def max_sub_array(nums: List[int]) -> int: >>> max_sub_array([-1,-2,-3]) 0 """ - best = 0 - current = 0 - for i in nums: - current += i + best = 0 + current = 0 + for i in nums: + current += i if current < 0: current = 0 best = max(best, current) - return best + return best if __name__=='__main__': inputs=[10,100,1000,10000,50000,100000,200000,300000,400000,500000] @@ -68,8 +67,8 @@ def max_sub_array(nums: List[int]) -> int: (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("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 ") @@ -77,4 +76,4 @@ def max_sub_array(nums: List[int]) -> int: - + diff --git a/graphs/a_star.py b/graphs/a_star.py index 584222e6f62b..09a7a0e579d8 100644 --- a/graphs/a_star.py +++ b/graphs/a_star.py @@ -1,5 +1,3 @@ -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 [0, 1, 0, 0, 0, 0], @@ -14,13 +12,13 @@ [5, 4, 3, 2, 1, 0]]''' init = [0, 0] -goal = [len(grid)-1, len(grid[0])-1] #all coordinates are given in format [y,x] +goal = [len(grid)-1, len(grid[0])-1] #all coordinates are given in format [y,x] cost = 1 #the cost map which pushes the path closer to the goal heuristic = [[0 for row in range(len(grid[0]))] for col in range(len(grid))] -for i in range(len(grid)): - for j in range(len(grid[0])): +for i in range(len(grid)): + for j in range(len(grid[0])): heuristic[i][j] = abs(i - goal[0]) + abs(j - goal[1]) if grid[i][j] == 1: heuristic[i][j] = 99 #added extra penalty in the heuristic map @@ -62,7 +60,7 @@ def search(grid,init,goal,cost,heuristic): g = next[1] f = next[0] - + if x == goal[0] and y == goal[1]: found = True else: @@ -93,10 +91,10 @@ def search(grid,init,goal,cost,heuristic): print("ACTION MAP") for i in range(len(action)): 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 ee63ca995de6..64c51e139cca 100644 --- a/graphs/basic_graphs.py +++ b/graphs/basic_graphs.py @@ -1,23 +1,10 @@ -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 - - if __name__ == "__main__": # Accept No. of Nodes and edges - n, m = map(int, raw_input().split(" ")) + n, m = map(int, input().split(" ")) # Initialising Dictionary of edges g = {} - for i in xrange(n): + for i in range(n): g[i + 1] = [] """ @@ -25,8 +12,8 @@ Accepting edges of Unweighted Directed Graphs ---------------------------------------------------------------------------- """ - for _ in xrange(m): - x, y = map(int, raw_input().strip().split(" ")) + for _ in range(m): + x, y = map(int, input().strip().split(" ")) g[x].append(y) """ @@ -34,8 +21,8 @@ Accepting edges of Unweighted Undirected Graphs ---------------------------------------------------------------------------- """ - for _ in xrange(m): - x, y = map(int, raw_input().strip().split(" ")) + for _ in range(m): + x, y = map(int, input().strip().split(" ")) g[x].append(y) g[y].append(x) @@ -44,8 +31,8 @@ Accepting edges of Weighted Undirected Graphs ---------------------------------------------------------------------------- """ - for _ in xrange(m): - x, y, r = map(int, raw_input().strip().split(" ")) + for _ in range(m): + x, y, r = map(int, input().strip().split(" ")) g[x].append([y, r]) g[y].append([x, r]) @@ -170,10 +157,10 @@ def topo(G, ind=None, Q=[1]): def adjm(): - n = raw_input().strip() + n = input().strip() a = [] - for i in xrange(n): - a.append(map(int, raw_input().strip().split())) + for i in range(n): + a.append(map(int, input().strip().split())) return a, n @@ -193,10 +180,10 @@ def adjm(): def floy(A_and_n): (A, n) = A_and_n dist = list(A) - path = [[0] * n for i in xrange(n)] - for k in xrange(n): - for i in xrange(n): - for j in xrange(n): + path = [[0] * n for i in range(n)] + for k in range(n): + for i in range(n): + for j in range(n): if dist[i][j] > dist[i][k] + dist[k][j]: dist[i][j] = dist[i][k] + dist[k][j] path[i][k] = k @@ -245,10 +232,10 @@ def prim(G, s): def edglist(): - n, m = map(int, raw_input().split(" ")) + n, m = map(int, input().split(" ")) l = [] - for i in xrange(m): - l.append(map(int, raw_input().split(' '))) + for i in range(m): + l.append(map(int, input().split(' '))) return l, n @@ -272,10 +259,10 @@ def krusk(E_and_n): break print(s) x = E.pop() - for i in xrange(len(s)): + for i in range(len(s)): if x[0] in s[i]: break - for j in xrange(len(s)): + for j in range(len(s)): if x[1] in s[j]: if i == j: break diff --git a/graphs/bellman_ford.py b/graphs/bellman_ford.py index f49157230054..bebe8f354b26 100644 --- a/graphs/bellman_ford.py +++ b/graphs/bellman_ford.py @@ -1,5 +1,3 @@ -from __future__ import print_function - def printDist(dist, V): print("\nVertex Distance") for i in range(V): diff --git a/graphs/breadth_first_search.py b/graphs/breadth_first_search.py index 3992e2d4d892..205f49a6172b 100644 --- a/graphs/breadth_first_search.py +++ b/graphs/breadth_first_search.py @@ -3,8 +3,6 @@ """ Author: OMKAR PATHAK """ -from __future__ import print_function - class Graph(): def __init__(self): diff --git a/graphs/depth_first_search.py b/graphs/depth_first_search.py index 98faf61354f9..2b03683c0047 100644 --- a/graphs/depth_first_search.py +++ b/graphs/depth_first_search.py @@ -2,7 +2,6 @@ # encoding=utf8 """ Author: OMKAR PATHAK """ -from __future__ import print_function class Graph(): diff --git a/graphs/dijkstra_2.py b/graphs/dijkstra_2.py index 8f39aec41906..f6118830c9c0 100644 --- a/graphs/dijkstra_2.py +++ b/graphs/dijkstra_2.py @@ -1,5 +1,3 @@ -from __future__ import print_function - def printDist(dist, V): print("\nVertex Distance") for i in range(V): diff --git a/graphs/dijkstra_algorithm.py b/graphs/dijkstra_algorithm.py index 985c7f6c1301..c43ff37f5336 100644 --- a/graphs/dijkstra_algorithm.py +++ b/graphs/dijkstra_algorithm.py @@ -2,7 +2,6 @@ # Author: Shubham Malik # References: https://en.wikipedia.org/wiki/Dijkstra%27s_algorithm -from __future__ import print_function import math import sys # For storing the vertex set to retreive node with the lowest distance diff --git a/graphs/even_tree.py b/graphs/even_tree.py index 9383ea9a13c1..45d55eecff8a 100644 --- a/graphs/even_tree.py +++ b/graphs/even_tree.py @@ -12,7 +12,6 @@ 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 diff --git a/graphs/graph_list.py b/graphs/graph_list.py index 0c981c39d320..2ca363b1d746 100644 --- a/graphs/graph_list.py +++ b/graphs/graph_list.py @@ -1,7 +1,6 @@ #!/usr/bin/python # encoding=utf8 -from __future__ import print_function # Author: OMKAR PATHAK # We can use Python's dictionary for constructing the graph. diff --git a/graphs/graph_matrix.py b/graphs/graph_matrix.py index de25301d6dd1..1998fec8d6fe 100644 --- a/graphs/graph_matrix.py +++ b/graphs/graph_matrix.py @@ -1,6 +1,3 @@ -from __future__ import print_function - - class Graph: def __init__(self, vertex): diff --git a/graphs/graphs_floyd_warshall.py b/graphs/graphs_floyd_warshall.py index a1d12aac02b4..5f159683733f 100644 --- a/graphs/graphs_floyd_warshall.py +++ b/graphs/graphs_floyd_warshall.py @@ -4,8 +4,6 @@ have negative edge weights. """ -from __future__ import print_function - def _print_dist(dist, v): print("\nThe shortest path matrix using Floyd Warshall algorithm\n") @@ -34,9 +32,9 @@ def floyd_warshall(graph, v): 4. The above is repeated for each vertex k in the graph. 5. Whenever distance[i][j] is given a new minimum value, next vertex[i][j] is updated to the next vertex[i][k]. """ - + dist=[[float('inf') for _ in range(v)] for _ in range(v)] - + for i in range(v): for j in range(v): dist[i][j] = graph[i][j] @@ -53,7 +51,7 @@ def floyd_warshall(graph, v): _print_dist(dist, v) return dist, v - + if __name__== '__main__': v = int(input("Enter number of vertices: ")) diff --git a/graphs/minimum_spanning_tree_kruskal.py b/graphs/minimum_spanning_tree_kruskal.py index 975151c90ede..a2211582ec40 100644 --- a/graphs/minimum_spanning_tree_kruskal.py +++ b/graphs/minimum_spanning_tree_kruskal.py @@ -1,5 +1,3 @@ -from __future__ import print_function - if __name__ == "__main__": num_nodes, num_edges = list(map(int, input().strip().split())) diff --git a/graphs/multi_hueristic_astar.py b/graphs/multi_hueristic_astar.py index 1c01fe9aa6d3..3021c4162b8e 100644 --- a/graphs/multi_hueristic_astar.py +++ b/graphs/multi_hueristic_astar.py @@ -1,12 +1,6 @@ -from __future__ import print_function import heapq import numpy as np -try: - xrange # Python 2 -except NameError: - xrange = range # Python 3 - class PriorityQueue: def __init__(self): @@ -96,7 +90,7 @@ def do_something(back_pointer, goal, start): grid[(n-1)][0] = "-" - for i in xrange(n): + for i in range(n): for j in range(n): if (i, j) == (0, n-1): print(grid[i][j], end=' ') diff --git a/graphs/scc_kosaraju.py b/graphs/scc_kosaraju.py index 0d0375203b6d..99564a7cfa35 100644 --- a/graphs/scc_kosaraju.py +++ b/graphs/scc_kosaraju.py @@ -1,6 +1,3 @@ -from __future__ import print_function - - def dfs(u): global g, r, scc, component, visit, stack if visit[u]: return diff --git a/hashes/chaos_machine.py b/hashes/chaos_machine.py index f0a305bfeade..3a7c3950bb29 100644 --- a/hashes/chaos_machine.py +++ b/hashes/chaos_machine.py @@ -1,10 +1,4 @@ """example of simple chaos machine""" -from __future__ import print_function - -try: - input = raw_input # Python 2 -except NameError: - pass # Python 3 # Chaos Machine (K, t, m) K = [0.33, 0.44, 0.55, 0.44, 0.33]; t = 3; m = 5 @@ -96,7 +90,7 @@ def reset(): for chunk in message: push(chunk) -# for controlling +# for controlling inp = "" # Pulling Data (Output) diff --git a/hashes/enigma_machine.py b/hashes/enigma_machine.py index bd410c5cb21d..06215785765f 100644 --- a/hashes/enigma_machine.py +++ b/hashes/enigma_machine.py @@ -1,5 +1,3 @@ -from __future__ import print_function - alphabets = [chr(i) for i in range(32, 126)] gear_one = [i for i in range(len(alphabets))] gear_two = [i for i in range(len(alphabets))] diff --git a/hashes/md5.py b/hashes/md5.py index 7891f2077986..1ad43013363f 100644 --- a/hashes/md5.py +++ b/hashes/md5.py @@ -1,4 +1,3 @@ -from __future__ import print_function import math @@ -66,7 +65,7 @@ def getBlock(bitString): """[summary] Iterator: Returns by each call a list of length 16 with the 32 bit - integer blocks. + integer blocks. Arguments: bitString {[string]} -- [binary string >= 512] @@ -95,7 +94,7 @@ def not32(i): def sum32(a, b): ''' - + ''' return (a + b) % 2**32 diff --git a/machine_learning/decision_tree.py b/machine_learning/decision_tree.py index 71849904ccf2..acdf646875ac 100644 --- a/machine_learning/decision_tree.py +++ b/machine_learning/decision_tree.py @@ -1,10 +1,8 @@ """ 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. +Output: The decision tree maps a real number input to a real number output. """ -from __future__ import print_function - import numpy as np class Decision_Tree: @@ -19,7 +17,7 @@ def __init__(self, depth = 5, min_leaf_size = 5): def mean_squared_error(self, labels, prediction): """ mean_squared_error: - @param labels: a one dimensional numpy array + @param labels: a one dimensional numpy array @param prediction: a floating point value return value: mean_squared_error calculates the error if prediction is used to estimate the labels """ @@ -32,7 +30,7 @@ def train(self, X, y): """ train: @param X: a one dimensional numpy array - @param y: a one dimensional numpy array. + @param y: a one dimensional numpy array. The contents of y are the labels for the corresponding X values train does not have a return value @@ -135,6 +133,6 @@ def main(): print("Predictions: " + str(predictions)) print("Average error: " + str(avg_error)) - + if __name__ == '__main__': main() \ No newline at end of file diff --git a/machine_learning/gradient_descent.py b/machine_learning/gradient_descent.py index 6387d4939205..9a17113b7ddb 100644 --- a/machine_learning/gradient_descent.py +++ b/machine_learning/gradient_descent.py @@ -1,7 +1,6 @@ """ Implementation of gradient descent algorithm for minimizing cost of a linear hypothesis function. """ -from __future__ import print_function, division import numpy # List of input, output pairs diff --git a/machine_learning/k_means_clust.py b/machine_learning/k_means_clust.py index 368739a45fe9..d0ce0f2599e0 100644 --- a/machine_learning/k_means_clust.py +++ b/machine_learning/k_means_clust.py @@ -17,36 +17,35 @@ Usage: 1. define 'k' value, 'X' features array and 'hetrogeneity' empty list - + 2. create initial_centroids, initial_centroids = get_initial_centroids( - X, - k, + X, + k, seed=0 # seed value for initial centroid generation, None for randomness(default=None) ) 3. find centroids and clusters using kmeans function. - + centroids, cluster_assignment = kmeans( - X, - k, - initial_centroids, + X, + k, + initial_centroids, maxiter=400, - record_heterogeneity=heterogeneity, + record_heterogeneity=heterogeneity, verbose=True # whether to print logs in console or not.(default=False) ) - - + + 4. Plot the loss function, hetrogeneity values for every iteration saved in hetrogeneity list. plot_heterogeneity( - heterogeneity, + heterogeneity, k ) - + 5. Have fun.. - + ''' -from __future__ import print_function from sklearn.metrics import pairwise_distances import numpy as np @@ -57,30 +56,30 @@ def get_initial_centroids(data, k, seed=None): if seed is not None: # useful for obtaining consistent results np.random.seed(seed) n = data.shape[0] # number of data points - + # Pick K indices from range [0, N). rand_indices = np.random.randint(0, n, k) - + # Keep centroids as dense format, as many entries will be nonzero due to averaging. # As long as at least one document in a cluster contains a word, # it will carry a nonzero weight in the TF-IDF vector of the centroid. centroids = data[rand_indices,:] - + return centroids def centroid_pairwise_dist(X,centroids): return pairwise_distances(X,centroids,metric='euclidean') def assign_clusters(data, centroids): - + # Compute distances between each data point and the set of centroids: # Fill in the blank (RHS only) distances_from_centroids = centroid_pairwise_dist(data,centroids) - + # Compute cluster assignments for each data point: # Fill in the blank (RHS only) cluster_assignment = np.argmin(distances_from_centroids,axis=1) - + return cluster_assignment def revise_centroids(data, k, cluster_assignment): @@ -92,23 +91,23 @@ def revise_centroids(data, k, cluster_assignment): centroid = member_data_points.mean(axis=0) new_centroids.append(centroid) new_centroids = np.array(new_centroids) - + return new_centroids def compute_heterogeneity(data, k, centroids, cluster_assignment): - + heterogeneity = 0.0 for i in range(k): - + # Select all data points that belong to cluster i. Fill in the blank (RHS only) member_data_points = data[cluster_assignment==i, :] - + if member_data_points.shape[0] > 0: # check if i-th cluster is non-empty # Compute distances from centroid to data points (RHS only) distances = pairwise_distances(member_data_points, [centroids[i]], metric='euclidean') squared_distances = distances**2 heterogeneity += np.sum(squared_distances) - + return heterogeneity from matplotlib import pyplot as plt @@ -129,36 +128,36 @@ def kmeans(data, k, initial_centroids, maxiter=500, record_heterogeneity=None, v verbose: if True, print how many data points changed their cluster labels in each iteration''' centroids = initial_centroids[:] prev_cluster_assignment = None - - for itr in range(maxiter): + + for itr in range(maxiter): if verbose: print(itr, end='') - + # 1. Make cluster assignments using nearest centroids cluster_assignment = assign_clusters(data,centroids) - + # 2. Compute a new centroid for each of the k clusters, averaging all data points assigned to that cluster. centroids = revise_centroids(data,k, cluster_assignment) - + # Check for convergence: if none of the assignments changed, stop if prev_cluster_assignment is not None and \ (prev_cluster_assignment==cluster_assignment).all(): break - - # Print number of new assignments + + # Print number of new assignments if prev_cluster_assignment is not None: num_changed = np.sum(prev_cluster_assignment!=cluster_assignment) if verbose: - print(' {0:5d} elements changed their cluster assignment.'.format(num_changed)) - + print(' {0:5d} elements changed their cluster assignment.'.format(num_changed)) + # Record heterogeneity convergence metric if record_heterogeneity is not None: # YOUR CODE HERE score = compute_heterogeneity(data,k,centroids,cluster_assignment) record_heterogeneity.append(score) - + prev_cluster_assignment = cluster_assignment[:] - + return centroids, cluster_assignment # Mock test below diff --git a/machine_learning/linear_regression.py b/machine_learning/linear_regression.py index 03f16629e451..9d9738fced8d 100644 --- a/machine_learning/linear_regression.py +++ b/machine_learning/linear_regression.py @@ -7,8 +7,6 @@ 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/maths/simpson_rule.py b/maths/simpson_rule.py index 2b237d2e1a4e..5cf9c14b07ee 100644 --- a/maths/simpson_rule.py +++ b/maths/simpson_rule.py @@ -8,9 +8,6 @@ "Simpson Rule" """ -from __future__ import print_function - - def method_2(boundary, steps): # "Simpson Rule" # int(f) = delta_x/2 * (b-a)/3*(f1 + 4f2 + 2f_3 + ... + fn) diff --git a/maths/trapezoidal_rule.py b/maths/trapezoidal_rule.py index 789f263c6991..f5e5fbbc2662 100644 --- a/maths/trapezoidal_rule.py +++ b/maths/trapezoidal_rule.py @@ -7,8 +7,6 @@ "extended trapezoidal rule" """ -from __future__ import print_function - def method_1(boundary, steps): # "extended trapezoidal rule" # int(f) = dx/2 * (f1 + 2f2 + ... + fn) @@ -19,7 +17,7 @@ def method_1(boundary, steps): y = 0.0 y += (h/2.0)*f(a) for i in x_i: - #print(i) + #print(i) y += h*f(i) y += (h/2.0)*f(b) return y diff --git a/maths/zellers_congruence.py b/maths/zellers_congruence.py index e04425eec903..67c5550802ea 100644 --- a/maths/zellers_congruence.py +++ b/maths/zellers_congruence.py @@ -1,4 +1,3 @@ -from __future__ import annotations import datetime import argparse @@ -7,7 +6,7 @@ def zeller(date_input: str) -> str: """ Zellers Congruence Algorithm - Find the day of the week for nearly any Gregorian or Julian calendar date + Find the day of the week for nearly any Gregorian or Julian calendar date >>> zeller('01-31-2010') 'Your date 01-31-2010, is a Sunday!' @@ -108,7 +107,7 @@ def zeller(date_input: str) -> str: # Validate if not 0 < d < 32: raise ValueError("Date must be between 1 - 31") - + # Get second seperator sep_2: str = date_input[5] # Validate diff --git a/matrix/nth_fibonacci_using_matrix_exponentiation.py b/matrix/nth_fibonacci_using_matrix_exponentiation.py index 7491abcae031..57cdfacd47dd 100644 --- a/matrix/nth_fibonacci_using_matrix_exponentiation.py +++ b/matrix/nth_fibonacci_using_matrix_exponentiation.py @@ -13,9 +13,6 @@ So we just need the n times multiplication of the matrix [1,1],[1,0]]. We can decrease the n times multiplication by following the divide and conquer approach. """ -from __future__ import print_function - - def multiply(matrix_a, matrix_b): matrix_c = [] n = len(matrix_a) diff --git a/neural_network/convolution_neural_network.py b/neural_network/convolution_neural_network.py index 0e72f0c0dca2..e4dd0a11db9d 100644 --- a/neural_network/convolution_neural_network.py +++ b/neural_network/convolution_neural_network.py @@ -15,8 +15,6 @@ Date: 2017.9.20 - - - - - -- - - - - - - - - - - - - - - - - - - - - - - ''' -from __future__ import print_function - import pickle import numpy as np import matplotlib.pyplot as plt diff --git a/neural_network/perceptron.py b/neural_network/perceptron.py index 871eca20273b..fdc710597241 100644 --- a/neural_network/perceptron.py +++ b/neural_network/perceptron.py @@ -9,8 +9,6 @@ p2 = 1 ''' -from __future__ import print_function - import random diff --git a/other/anagrams.py b/other/anagrams.py index 29b34fbdc5d3..1e6e38dee139 100644 --- a/other/anagrams.py +++ b/other/anagrams.py @@ -1,4 +1,3 @@ -from __future__ import print_function import collections, pprint, time, os start_time = time.time() diff --git a/other/euclidean_gcd.py b/other/euclidean_gcd.py index 30853e172076..13378379f286 100644 --- a/other/euclidean_gcd.py +++ b/other/euclidean_gcd.py @@ -1,4 +1,3 @@ -from __future__ import print_function # https://en.wikipedia.org/wiki/Euclidean_algorithm def euclidean_gcd(a, b): diff --git a/other/linear_congruential_generator.py b/other/linear_congruential_generator.py index 34abdf34eaf3..7c592a6400b5 100644 --- a/other/linear_congruential_generator.py +++ b/other/linear_congruential_generator.py @@ -1,4 +1,3 @@ -from __future__ import print_function __author__ = "Tobias Carryer" from time import time @@ -7,11 +6,11 @@ class LinearCongruentialGenerator(object): """ A pseudorandom number generator. """ - + def __init__( self, multiplier, increment, modulo, seed=int(time()) ): """ These parameters are saved and used when nextNumber() is called. - + modulo is the largest number that can be generated (exclusive). The most efficent values are powers of 2. 2^32 is a common value. """ @@ -19,7 +18,7 @@ def __init__( self, multiplier, increment, modulo, seed=int(time()) ): self.increment = increment self.modulo = modulo self.seed = seed - + def next_number( self ): """ The smallest number that can be generated is zero. diff --git a/other/nested_brackets.py b/other/nested_brackets.py index 76677d56439a..14147eaa6456 100644 --- a/other/nested_brackets.py +++ b/other/nested_brackets.py @@ -13,9 +13,6 @@ returns true if S is nested and false otherwise. ''' -from __future__ import print_function - - def is_balanced(S): stack = [] diff --git a/other/password_generator.py b/other/password_generator.py index fd0701041240..16b7e16b22a1 100644 --- a/other/password_generator.py +++ b/other/password_generator.py @@ -1,5 +1,4 @@ """Password generator allows you to generate a random password of length N.""" -from __future__ import print_function from random import choice from string import ascii_letters, digits, punctuation diff --git a/other/tower_of_hanoi.py b/other/tower_of_hanoi.py index 9cc5b9e40543..cd6fbf4d88ac 100644 --- a/other/tower_of_hanoi.py +++ b/other/tower_of_hanoi.py @@ -1,5 +1,4 @@ -from __future__ import print_function -def moveTower(height, fromPole, toPole, withPole): +def moveTower(height, fromPole, toPole, withPole): ''' >>> moveTower(3, 'A', 'B', 'C') moving disk from A to B diff --git a/other/two_sum.py b/other/two_sum.py index d4484aa85505..b784da82767a 100644 --- a/other/two_sum.py +++ b/other/two_sum.py @@ -9,8 +9,6 @@ Because nums[0] + nums[1] = 2 + 7 = 9, return [0, 1]. """ -from __future__ import print_function - def twoSum(nums, target): """ :type nums: List[int] @@ -20,7 +18,7 @@ def twoSum(nums, target): chk_map = {} for index, val in enumerate(nums): compl = target - val - if compl in chk_map: + if compl in chk_map: indices = [chk_map[compl], index] print(indices) return [indices] diff --git a/other/word_patterns.py b/other/word_patterns.py index c33d520087f7..1364d1277255 100644 --- a/other/word_patterns.py +++ b/other/word_patterns.py @@ -1,4 +1,3 @@ -from __future__ import print_function import pprint, time def getWordPattern(word): diff --git a/project_euler/problem_01/sol1.py b/project_euler/problem_01/sol1.py index 1433129af303..76b13b852c87 100644 --- a/project_euler/problem_01/sol1.py +++ b/project_euler/problem_01/sol1.py @@ -4,17 +4,9 @@ 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 - - def solution(n): """Returns the sum of all the multiples of 3 or 5 below n. - + >>> solution(3) 0 >>> solution(4) @@ -31,4 +23,4 @@ def solution(n): if __name__ == "__main__": - print(solution(int(raw_input().strip()))) + print(solution(int(input().strip()))) diff --git a/project_euler/problem_01/sol2.py b/project_euler/problem_01/sol2.py index e58fb03a8fb0..8041c7ffa589 100644 --- a/project_euler/problem_01/sol2.py +++ b/project_euler/problem_01/sol2.py @@ -4,17 +4,11 @@ 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 def solution(n): """Returns the sum of all the multiples of 3 or 5 below n. - + >>> solution(3) 0 >>> solution(4) @@ -36,4 +30,4 @@ def solution(n): if __name__ == "__main__": - print(solution(int(raw_input().strip()))) + print(solution(int(input().strip()))) diff --git a/project_euler/problem_01/sol3.py b/project_euler/problem_01/sol3.py index 013ce5e54fdf..532203ddd95d 100644 --- a/project_euler/problem_01/sol3.py +++ b/project_euler/problem_01/sol3.py @@ -4,20 +4,12 @@ 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 - - def solution(n): """ This solution is based on the pattern that the successive numbers in the series follow: 0+3,+2,+1,+3,+1,+2,+3. Returns the sum of all the multiples of 3 or 5 below n. - + >>> solution(3) 0 >>> solution(4) @@ -63,4 +55,4 @@ def solution(n): if __name__ == "__main__": - print(solution(int(raw_input().strip()))) + print(solution(int(input().strip()))) diff --git a/project_euler/problem_01/sol4.py b/project_euler/problem_01/sol4.py index 90403c3bd6a3..3e6712618870 100644 --- a/project_euler/problem_01/sol4.py +++ b/project_euler/problem_01/sol4.py @@ -4,17 +4,9 @@ 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 - - def solution(n): """Returns the sum of all the multiples of 3 or 5 below n. - + >>> solution(3) 0 >>> solution(4) @@ -50,4 +42,4 @@ def solution(n): if __name__ == "__main__": - print(solution(int(raw_input().strip()))) + print(solution(int(input().strip()))) diff --git a/project_euler/problem_01/sol5.py b/project_euler/problem_01/sol5.py index 302fe44f8bfa..bd96d965f92d 100644 --- a/project_euler/problem_01/sol5.py +++ b/project_euler/problem_01/sol5.py @@ -4,19 +4,13 @@ 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 """A straightforward pythonic solution using list comprehension""" def solution(n): """Returns the sum of all the multiples of 3 or 5 below n. - + >>> solution(3) 0 >>> solution(4) @@ -31,4 +25,4 @@ def solution(n): if __name__ == "__main__": - print(solution(int(raw_input().strip()))) + print(solution(int(input().strip()))) diff --git a/project_euler/problem_01/sol6.py b/project_euler/problem_01/sol6.py index cf6e751d4c05..b9c3db4f8550 100644 --- a/project_euler/problem_01/sol6.py +++ b/project_euler/problem_01/sol6.py @@ -4,17 +4,9 @@ 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 - - def solution(n): """Returns the sum of all the multiples of 3 or 5 below n. - + >>> solution(3) 0 >>> solution(4) @@ -37,4 +29,4 @@ def solution(n): if __name__ == "__main__": - print(solution(int(raw_input().strip()))) + print(solution(int(input().strip()))) diff --git a/project_euler/problem_02/sol1.py b/project_euler/problem_02/sol1.py index f61d04e3dfce..d2ad67e2f424 100644 --- a/project_euler/problem_02/sol1.py +++ b/project_euler/problem_02/sol1.py @@ -9,18 +9,10 @@ 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 - - def solution(n): """Returns the sum of all fibonacci sequence even elements that are lower or equals to n. - + >>> solution(10) 10 >>> solution(15) @@ -44,4 +36,4 @@ def solution(n): if __name__ == "__main__": - print(solution(int(raw_input().strip()))) + print(solution(int(input().strip()))) diff --git a/project_euler/problem_02/sol2.py b/project_euler/problem_02/sol2.py index 3e103a6a4373..71f51b695e84 100644 --- a/project_euler/problem_02/sol2.py +++ b/project_euler/problem_02/sol2.py @@ -9,18 +9,10 @@ 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 - - def solution(n): """Returns the sum of all fibonacci sequence even elements that are lower or equals to n. - + >>> solution(10) [2, 8] >>> solution(15) @@ -42,4 +34,4 @@ def solution(n): if __name__ == "__main__": - print(solution(int(raw_input().strip()))) + print(solution(int(input().strip()))) diff --git a/project_euler/problem_02/sol3.py b/project_euler/problem_02/sol3.py index abd9d6c753b8..c698b8e38ab2 100644 --- a/project_euler/problem_02/sol3.py +++ b/project_euler/problem_02/sol3.py @@ -9,18 +9,10 @@ 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 - - def solution(n): """Returns the sum of all fibonacci sequence even elements that are lower or equals to n. - + >>> solution(10) 10 >>> solution(15) @@ -44,4 +36,4 @@ def solution(n): if __name__ == "__main__": - print(solution(int(raw_input().strip()))) + print(solution(int(input().strip()))) diff --git a/project_euler/problem_02/sol4.py b/project_euler/problem_02/sol4.py index 5e8c04899f3d..92ea0a51e026 100644 --- a/project_euler/problem_02/sol4.py +++ b/project_euler/problem_02/sol4.py @@ -9,20 +9,14 @@ 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 import math from decimal import Decimal, getcontext -try: - raw_input # Python 2 -except NameError: - raw_input = input # Python 3 - def solution(n): """Returns the sum of all fibonacci sequence even elements that are lower or equals to n. - + >>> solution(10) 10 >>> solution(15) @@ -68,4 +62,4 @@ def solution(n): if __name__ == "__main__": - print(solution(int(raw_input().strip()))) + print(solution(int(input().strip()))) diff --git a/project_euler/problem_03/sol1.py b/project_euler/problem_03/sol1.py index ab19d8b30457..9f8ecc5e6565 100644 --- a/project_euler/problem_03/sol1.py +++ b/project_euler/problem_03/sol1.py @@ -5,14 +5,8 @@ e.g. for 10, largest prime factor = 5. For 17, largest prime factor = 17. """ -from __future__ import print_function, division import math -try: - raw_input # Python 2 -except NameError: - raw_input = input # Python 3 - def isprime(no): if no == 2: @@ -81,4 +75,4 @@ def solution(n): if __name__ == "__main__": - print(solution(int(raw_input().strip()))) + print(solution(int(input().strip()))) diff --git a/project_euler/problem_03/sol2.py b/project_euler/problem_03/sol2.py index f93a0b75f4e0..b6fad079fa31 100644 --- a/project_euler/problem_03/sol2.py +++ b/project_euler/problem_03/sol2.py @@ -5,12 +5,6 @@ e.g. for 10, largest prime factor = 5. For 17, largest prime factor = 17. """ -from __future__ import print_function, division - -try: - raw_input # Python 2 -except NameError: - raw_input = input # Python 3 def solution(n): @@ -60,4 +54,4 @@ def solution(n): if __name__ == "__main__": - print(solution(int(raw_input().strip()))) + print(solution(int(input().strip()))) diff --git a/project_euler/problem_04/sol1.py b/project_euler/problem_04/sol1.py index 7a255f7308e6..51417b146bbf 100644 --- a/project_euler/problem_04/sol1.py +++ b/project_euler/problem_04/sol1.py @@ -6,18 +6,10 @@ Find the largest palindrome made from the product of two 3-digit numbers which is less than N. """ -from __future__ import print_function - -try: - raw_input # Python 2 -except NameError: - raw_input = input # Python 3 - - def solution(n): """Returns the largest palindrome made from the product of two 3-digit numbers which is less than n. - + >>> solution(20000) 19591 >>> solution(30000) @@ -47,4 +39,4 @@ def solution(n): if __name__ == "__main__": - print(solution(int(raw_input().strip()))) + print(solution(int(input().strip()))) diff --git a/project_euler/problem_04/sol2.py b/project_euler/problem_04/sol2.py index 45c6b256daf8..8740ee44a4b4 100644 --- a/project_euler/problem_04/sol2.py +++ b/project_euler/problem_04/sol2.py @@ -6,18 +6,10 @@ Find the largest palindrome made from the product of two 3-digit numbers which is less than N. """ -from __future__ import print_function - -try: - raw_input # Python 2 -except NameError: - raw_input = input # Python 3 - - def solution(n): """Returns the largest palindrome made from the product of two 3-digit numbers which is less than n. - + >>> solution(20000) 19591 >>> solution(30000) @@ -35,4 +27,4 @@ def solution(n): if __name__ == "__main__": - print(solution(int(raw_input().strip()))) + print(solution(int(input().strip()))) diff --git a/project_euler/problem_05/sol1.py b/project_euler/problem_05/sol1.py index e2deb91fb6aa..83c387e4ae6e 100644 --- a/project_euler/problem_05/sol1.py +++ b/project_euler/problem_05/sol1.py @@ -6,14 +6,6 @@ What is the smallest positive number that is evenly divisible(divisible with no remainder) by all of the numbers from 1 to N? """ -from __future__ import print_function - -try: - raw_input # Python 2 -except NameError: - raw_input = input # Python 3 - - def solution(n): """Returns the smallest positive number that is evenly divisible(divisible with no remainder) by all of the numbers from 1 to n. @@ -66,4 +58,4 @@ def solution(n): if __name__ == "__main__": - print(solution(int(raw_input().strip()))) + print(solution(int(input().strip()))) diff --git a/project_euler/problem_05/sol2.py b/project_euler/problem_05/sol2.py index 293dd96f2294..5aa84d21c8e8 100644 --- a/project_euler/problem_05/sol2.py +++ b/project_euler/problem_05/sol2.py @@ -6,13 +6,6 @@ What is the smallest positive number that is evenly divisible(divisible with no remainder) by all of the numbers from 1 to N? """ -from __future__ import print_function - -try: - raw_input # Python 2 -except NameError: - raw_input = input # Python 3 - """ Euclidean GCD Algorithm """ @@ -30,7 +23,7 @@ def lcm(x, y): def solution(n): """Returns the smallest positive number that is evenly divisible(divisible with no remainder) by all of the numbers from 1 to n. - + >>> solution(10) 2520 >>> solution(15) @@ -47,4 +40,4 @@ def solution(n): if __name__ == "__main__": - print(solution(int(raw_input().strip()))) + print(solution(int(input().strip()))) diff --git a/project_euler/problem_06/sol1.py b/project_euler/problem_06/sol1.py index 728701e167c3..0a964272e7e8 100644 --- a/project_euler/problem_06/sol1.py +++ b/project_euler/problem_06/sol1.py @@ -14,18 +14,10 @@ Find the difference between the sum of the squares of the first N natural numbers and the square of the sum. """ -from __future__ import print_function - -try: - raw_input # Python 2 -except NameError: - raw_input = input # Python 3 - - def solution(n): """Returns the difference between the sum of the squares of the first n natural numbers and the square of the sum. - + >>> solution(10) 2640 >>> solution(15) @@ -45,4 +37,4 @@ def solution(n): if __name__ == "__main__": - print(solution(int(raw_input().strip()))) + print(solution(int(input().strip()))) diff --git a/project_euler/problem_06/sol2.py b/project_euler/problem_06/sol2.py index 2c64812d56f8..45d08d244647 100644 --- a/project_euler/problem_06/sol2.py +++ b/project_euler/problem_06/sol2.py @@ -14,18 +14,10 @@ Find the difference between the sum of the squares of the first N natural numbers and the square of the sum. """ -from __future__ import print_function - -try: - raw_input # Python 2 -except NameError: - raw_input = input # Python 3 - - def solution(n): """Returns the difference between the sum of the squares of the first n natural numbers and the square of the sum. - + >>> solution(10) 2640 >>> solution(15) @@ -42,4 +34,4 @@ def solution(n): if __name__ == "__main__": - print(solution(int(raw_input().strip()))) + print(solution(int(input().strip()))) diff --git a/project_euler/problem_06/sol3.py b/project_euler/problem_06/sol3.py index 7d94b1e2254f..f9c5dacb3777 100644 --- a/project_euler/problem_06/sol3.py +++ b/project_euler/problem_06/sol3.py @@ -14,19 +14,13 @@ Find the difference between the sum of the squares of the first N natural numbers and the square of the sum. """ -from __future__ import print_function import math -try: - raw_input # Python 2 -except NameError: - raw_input = input # Python 3 - def solution(n): """Returns the difference between the sum of the squares of the first n natural numbers and the square of the sum. - + >>> solution(10) 2640 >>> solution(15) @@ -42,4 +36,4 @@ def solution(n): if __name__ == "__main__": - print(solution(int(raw_input().strip()))) + print(solution(int(input().strip()))) diff --git a/project_euler/problem_07/sol1.py b/project_euler/problem_07/sol1.py index 403ded568dda..d8d67e157860 100644 --- a/project_euler/problem_07/sol1.py +++ b/project_euler/problem_07/sol1.py @@ -6,14 +6,8 @@ We can see that the 6th prime is 13. What is the Nth prime number? """ -from __future__ import print_function from math import sqrt -try: - raw_input # Python 2 -except NameError: - raw_input = input # Python 3 - def isprime(n): if n == 2: @@ -30,7 +24,7 @@ def isprime(n): def solution(n): """Returns the n-th prime number. - + >>> solution(6) 13 >>> solution(1) @@ -58,4 +52,4 @@ def solution(n): if __name__ == "__main__": - print(solution(int(raw_input().strip()))) + print(solution(int(input().strip()))) diff --git a/project_euler/problem_07/sol2.py b/project_euler/problem_07/sol2.py index 67336f7c1c96..7d078af32176 100644 --- a/project_euler/problem_07/sol2.py +++ b/project_euler/problem_07/sol2.py @@ -6,14 +6,6 @@ We can see that the 6th prime is 13. What is the Nth prime number? """ -from __future__ import print_function - -try: - raw_input # Python 2 -except NameError: - raw_input = input # Python 3 - - def isprime(number): for i in range(2, int(number ** 0.5) + 1): if number % i == 0: @@ -23,7 +15,7 @@ def isprime(number): def solution(n): """Returns the n-th prime number. - + >>> solution(6) 13 >>> solution(1) @@ -73,4 +65,4 @@ def solution(n): if __name__ == "__main__": - print(solution(int(raw_input().strip()))) + print(solution(int(input().strip()))) diff --git a/project_euler/problem_07/sol3.py b/project_euler/problem_07/sol3.py index bc94762604b3..3c28ecf7fb34 100644 --- a/project_euler/problem_07/sol3.py +++ b/project_euler/problem_07/sol3.py @@ -6,15 +6,9 @@ We can see that the 6th prime is 13. What is the Nth prime number? """ -from __future__ import print_function import math import itertools -try: - raw_input # Python 2 -except NameError: - raw_input = input # Python 3 - def primeCheck(number): if number % 2 == 0 and number > 2: @@ -32,7 +26,7 @@ def prime_generator(): def solution(n): """Returns the n-th prime number. - + >>> solution(6) 13 >>> solution(1) @@ -50,4 +44,4 @@ def solution(n): if __name__ == "__main__": - print(solution(int(raw_input().strip()))) + print(solution(int(input().strip()))) diff --git a/project_euler/problem_09/sol1.py b/project_euler/problem_09/sol1.py index d9ebe8760861..3bb5c968115d 100644 --- a/project_euler/problem_09/sol1.py +++ b/project_euler/problem_09/sol1.py @@ -7,7 +7,6 @@ There exists exactly one Pythagorean triplet for which a + b + c = 1000. Find the product abc. """ -from __future__ import print_function def solution(): @@ -17,7 +16,7 @@ def solution(): 1. a < b < c 2. a**2 + b**2 = c**2 3. a + b + c = 1000 - + # The code below has been commented due to slow execution affecting Travis. # >>> solution() # 31875000 diff --git a/project_euler/problem_09/sol2.py b/project_euler/problem_09/sol2.py index 674daae9ec8e..502f334417c8 100644 --- a/project_euler/problem_09/sol2.py +++ b/project_euler/problem_09/sol2.py @@ -7,14 +7,6 @@ There exists exactly one Pythagorean triplet for which a + b + c = 1000. Find the product abc. """ -from __future__ import print_function - -try: - raw_input # Python 2 -except NameError: - raw_input = input # Python 3 - - def solution(n): """ Return the product of a,b,c which are Pythagorean Triplet that satisfies @@ -22,7 +14,7 @@ def solution(n): 1. a < b < c 2. a**2 + b**2 = c**2 3. a + b + c = 1000 - + >>> solution(1000) 31875000 """ @@ -41,4 +33,4 @@ def solution(n): if __name__ == "__main__": - print(solution(int(raw_input().strip()))) + print(solution(int(input().strip()))) diff --git a/project_euler/problem_09/sol3.py b/project_euler/problem_09/sol3.py index 006029c8a30d..bbe7dcf743e7 100644 --- a/project_euler/problem_09/sol3.py +++ b/project_euler/problem_09/sol3.py @@ -10,9 +10,6 @@ There exists exactly one Pythagorean triplet for which a + b + c = 1000. Find the product abc. """ -from __future__ import print_function - - def solution(): """ Returns the product of a,b,c which are Pythagorean Triplet that satisfies diff --git a/project_euler/problem_10/sol1.py b/project_euler/problem_10/sol1.py index 49384d7c78f0..c81085951ecf 100644 --- a/project_euler/problem_10/sol1.py +++ b/project_euler/problem_10/sol1.py @@ -4,22 +4,11 @@ Find the sum of all the primes below two million. """ -from __future__ import print_function from math import sqrt -try: - raw_input # Python 2 -except NameError: - raw_input = input # Python 3 - -try: - xrange # Python 2 -except NameError: - xrange = range # Python 3 - def is_prime(n): - for i in xrange(2, int(sqrt(n)) + 1): + for i in range(2, int(sqrt(n)) + 1): if n % i == 0: return False @@ -32,7 +21,7 @@ def sum_of_primes(n): else: return 0 - for i in xrange(3, n, 2): + for i in range(3, n, 2): if is_prime(i): sumOfPrimes += i @@ -41,7 +30,7 @@ def sum_of_primes(n): def solution(n): """Returns the sum of all the primes below n. - + # The code below has been commented due to slow execution affecting Travis. # >>> solution(2000000) # 142913828922 @@ -58,4 +47,4 @@ def solution(n): if __name__ == "__main__": - print(solution(int(raw_input().strip()))) + print(solution(int(input().strip()))) diff --git a/project_euler/problem_10/sol2.py b/project_euler/problem_10/sol2.py index 451a4ae5e8f3..b2e2b6e1adf3 100644 --- a/project_euler/problem_10/sol2.py +++ b/project_euler/problem_10/sol2.py @@ -4,15 +4,9 @@ Find the sum of all the primes below two million. """ -from __future__ import print_function import math from itertools import takewhile -try: - raw_input # Python 2 -except NameError: - raw_input = input # Python 3 - def primeCheck(number): if number % 2 == 0 and number > 2: @@ -30,7 +24,7 @@ def prime_generator(): def solution(n): """Returns the sum of all the primes below n. - + # The code below has been commented due to slow execution affecting Travis. # >>> solution(2000000) # 142913828922 @@ -47,4 +41,4 @@ def solution(n): if __name__ == "__main__": - print(solution(int(raw_input().strip()))) + print(solution(int(input().strip()))) diff --git a/project_euler/problem_11/sol1.py b/project_euler/problem_11/sol1.py index 3bdddc89d917..1473439ae00d 100644 --- a/project_euler/problem_11/sol1.py +++ b/project_euler/problem_11/sol1.py @@ -24,14 +24,8 @@ 01 70 54 71 83 51 54 69 16 92 33 48 61 43 52 01 89 19 67 48 """ -from __future__ import print_function import os -try: - xrange # Python 2 -except NameError: - xrange = range # Python 2 - def largest_product(grid): nColumns = len(grid[0]) @@ -43,8 +37,8 @@ def largest_product(grid): # Check vertically, horizontally, diagonally at the same time (only works # for nxn grid) - for i in xrange(nColumns): - for j in xrange(nRows - 3): + for i in range(nColumns): + for j in range(nRows - 3): vertProduct = ( grid[j][i] * grid[j + 1][i] * grid[j + 2][i] * grid[j + 3][i] ) @@ -81,7 +75,7 @@ def largest_product(grid): def solution(): """Returns the sum of all the multiples of 3 or 5 below n. - + >>> solution() 70600674 """ @@ -90,7 +84,7 @@ def solution(): for line in file: grid.append(line.strip("\n").split(" ")) - grid = [[int(i) for i in grid[j]] for j in xrange(len(grid))] + grid = [[int(i) for i in grid[j]] for j in range(len(grid))] return largest_product(grid) diff --git a/project_euler/problem_11/sol2.py b/project_euler/problem_11/sol2.py index 0a5785b42b2c..be6c11a378ad 100644 --- a/project_euler/problem_11/sol2.py +++ b/project_euler/problem_11/sol2.py @@ -24,45 +24,39 @@ 01 70 54 71 83 51 54 69 16 92 33 48 61 43 52 01 89 19 67 48 """ -from __future__ import print_function import os -try: - xrange # Python 2 -except NameError: - xrange = range # Python 2 - def solution(): """Returns the sum of all the multiples of 3 or 5 below n. - + >>> solution() 70600674 """ with open(os.path.dirname(__file__) + "/grid.txt") as f: l = [] - for i in xrange(20): + for i in range(20): l.append([int(x) for x in f.readline().split()]) maximum = 0 # right - for i in xrange(20): - for j in xrange(17): + for i in range(20): + for j in range(17): temp = l[i][j] * l[i][j + 1] * l[i][j + 2] * l[i][j + 3] if temp > maximum: maximum = temp # down - for i in xrange(17): - for j in xrange(20): + for i in range(17): + for j in range(20): temp = l[i][j] * l[i + 1][j] * l[i + 2][j] * l[i + 3][j] if temp > maximum: maximum = temp # diagonal 1 - for i in xrange(17): - for j in xrange(17): + for i in range(17): + for j in range(17): temp = ( l[i][j] * l[i + 1][j + 1] @@ -73,8 +67,8 @@ def solution(): maximum = temp # diagonal 2 - for i in xrange(17): - for j in xrange(3, 20): + for i in range(17): + for j in range(3, 20): temp = ( l[i][j] * l[i + 1][j - 1] diff --git a/project_euler/problem_12/sol1.py b/project_euler/problem_12/sol1.py index 54476110b503..7e080c4e45a1 100644 --- a/project_euler/problem_12/sol1.py +++ b/project_euler/problem_12/sol1.py @@ -21,18 +21,12 @@ What is the value of the first triangle number to have over five hundred divisors? """ -from __future__ import print_function from math import sqrt -try: - xrange # Python 2 -except NameError: - xrange = range # Python 3 - def count_divisors(n): nDivisors = 0 - for i in xrange(1, int(sqrt(n)) + 1): + for i in range(1, int(sqrt(n)) + 1): if n % i == 0: nDivisors += 2 # check if n is perfect square @@ -44,7 +38,7 @@ def count_divisors(n): def solution(): """Returns the value of the first triangle number to have over five hundred divisors. - + # The code below has been commented due to slow execution affecting Travis. # >>> solution() # 76576500 diff --git a/project_euler/problem_12/sol2.py b/project_euler/problem_12/sol2.py index 0d1502830bee..97a4910723ac 100644 --- a/project_euler/problem_12/sol2.py +++ b/project_euler/problem_12/sol2.py @@ -21,9 +21,6 @@ What is the value of the first triangle number to have over five hundred divisors? """ -from __future__ import print_function - - def triangle_number_generator(): for n in range(1, 1000000): yield n * (n + 1) // 2 @@ -38,7 +35,7 @@ def count_divisors(n): def solution(): """Returns the value of the first triangle number to have over five hundred divisors. - + # The code below has been commented due to slow execution affecting Travis. # >>> solution() # 76576500 diff --git a/project_euler/problem_14/sol1.py b/project_euler/problem_14/sol1.py index 8d3efbc59eb5..156322b7d507 100644 --- a/project_euler/problem_14/sol1.py +++ b/project_euler/problem_14/sol1.py @@ -16,20 +16,12 @@ Which starting number, under one million, produces the longest chain? """ -from __future__ import print_function - -try: - raw_input # Python 2 -except NameError: - raw_input = input # Python 3 - - def solution(n): """Returns the number under n that generates the longest sequence using the formula: n → n/2 (n is even) n → 3n + 1 (n is odd) - + # The code below has been commented due to slow execution affecting Travis. # >>> solution(1000000) # {'counter': 525, 'largest_number': 837799} @@ -62,7 +54,7 @@ def solution(n): if __name__ == "__main__": - result = solution(int(raw_input().strip())) + result = solution(int(input().strip())) print( ( "Largest Number:", diff --git a/project_euler/problem_14/sol2.py b/project_euler/problem_14/sol2.py index 0ec80e221f09..25ebd41571c2 100644 --- a/project_euler/problem_14/sol2.py +++ b/project_euler/problem_14/sol2.py @@ -24,14 +24,6 @@ Which starting number, under one million, produces the longest chain? """ -from __future__ import print_function - -try: - raw_input # Python 2 -except NameError: - raw_input = input # Python 3 - - def collatz_sequence(n): """Returns the Collatz sequence for n.""" sequence = [n] @@ -63,7 +55,7 @@ def solution(n): if __name__ == "__main__": - result = solution(int(raw_input().strip())) + result = solution(int(input().strip())) print( "Longest Collatz sequence under one million is %d with length %d" % (result["largest_number"], result["counter"]) diff --git a/project_euler/problem_21/sol1.py b/project_euler/problem_21/sol1.py index 9cf2a64cf2a9..a890e6a98611 100644 --- a/project_euler/problem_21/sol1.py +++ b/project_euler/problem_21/sol1.py @@ -16,15 +16,9 @@ Evaluate the sum of all the amicable numbers under 10000. """ -try: - xrange # Python 2 -except NameError: - xrange = range # Python 3 - - def sum_of_divisors(n): total = 0 - for i in xrange(1, int(sqrt(n) + 1)): + for i in range(1, int(sqrt(n) + 1)): if n % i == 0 and i != sqrt(n): total += i + n // i elif i == sqrt(n): diff --git a/project_euler/problem_22/sol1.py b/project_euler/problem_22/sol1.py index aa779f222eaa..f6275e2138bb 100644 --- a/project_euler/problem_22/sol1.py +++ b/project_euler/problem_22/sol1.py @@ -18,12 +18,6 @@ import os -try: - xrange # Python 2 -except NameError: - xrange = range # Python 3 - - def solution(): """Returns the total of all the name scores in the file. diff --git a/project_euler/problem_25/sol1.py b/project_euler/problem_25/sol1.py index be3b4d9b2d7d..4371c533ce16 100644 --- a/project_euler/problem_25/sol1.py +++ b/project_euler/problem_25/sol1.py @@ -25,12 +25,6 @@ digits? """ -try: - xrange # Python 2 -except NameError: - xrange = range # Python 3 - - def fibonacci(n): if n == 1 or type(n) is not int: return 0 @@ -38,7 +32,7 @@ def fibonacci(n): return 1 else: sequence = [0, 1] - for i in xrange(2, n + 1): + for i in range(2, n + 1): sequence.append(sequence[i - 1] + sequence[i - 2]) return sequence[n] diff --git a/project_euler/problem_28/sol1.py b/project_euler/problem_28/sol1.py index 63386ce3058c..11b48fea9adf 100644 --- a/project_euler/problem_28/sol1.py +++ b/project_euler/problem_28/sol1.py @@ -16,11 +16,6 @@ from math import ceil -try: - xrange # Python 2 -except NameError: - xrange = range # Python 3 - def diagonal_sum(n): """Returns the sum of the numbers on the diagonals in a n by n spiral @@ -39,7 +34,7 @@ def diagonal_sum(n): """ total = 1 - for i in xrange(1, int(ceil(n / 2.0))): + for i in range(1, int(ceil(n / 2.0))): odd = 2 * i + 1 even = 2 * i total = total + 4 * odd ** 2 - 6 * even diff --git a/project_euler/problem_29/solution.py b/project_euler/problem_29/solution.py index e67dafe4639d..24d3e20d94fe 100644 --- a/project_euler/problem_29/solution.py +++ b/project_euler/problem_29/solution.py @@ -14,13 +14,10 @@ How many distinct terms are in the sequence generated by ab for 2 <= a <= 100 and 2 <= b <= 100? """ -from __future__ import print_function - - def solution(n): """Returns the number of distinct terms in the sequence generated by a^b for 2 <= a <= 100 and 2 <= b <= 100. - + >>> solution(100) 9183 >>> solution(50) diff --git a/project_euler/problem_31/sol1.py b/project_euler/problem_31/sol1.py index e2a209e5df5a..f7439d346130 100644 --- a/project_euler/problem_31/sol1.py +++ b/project_euler/problem_31/sol1.py @@ -11,14 +11,6 @@ 1×£1 + 1×50p + 2×20p + 1×5p + 1×2p + 3×1p How many different ways can £2 be made using any number of coins? """ -from __future__ import print_function - -try: - raw_input # Python 2 -except NameError: - raw_input = input # Python 3 - - def one_pence(): return 1 diff --git a/project_euler/problem_36/sol1.py b/project_euler/problem_36/sol1.py index 38b60420992b..7ed74af8fd63 100644 --- a/project_euler/problem_36/sol1.py +++ b/project_euler/problem_36/sol1.py @@ -9,12 +9,6 @@ (Please note that the palindromic number, in either base, may not include leading zeros.) """ -try: - xrange # Python 2 -except NameError: - xrange = range # Python 3 - - def is_palindrome(n): n = str(n) @@ -47,7 +41,7 @@ def solution(n): """ total = 0 - for i in xrange(1, n): + for i in range(1, n): if is_palindrome(i) and is_palindrome(bin(i).split("b")[1]): total += i return total diff --git a/project_euler/problem_40/sol1.py b/project_euler/problem_40/sol1.py index accd7125354c..d15376b739db 100644 --- a/project_euler/problem_40/sol1.py +++ b/project_euler/problem_40/sol1.py @@ -14,11 +14,8 @@ d1 × d10 × d100 × d1000 × d10000 × d100000 × d1000000 """ -from __future__ import print_function - - def solution(): - """Returns + """Returns >>> solution() 210 diff --git a/project_euler/problem_48/sol1.py b/project_euler/problem_48/sol1.py index 95af951c0e8a..06ad1408dcef 100644 --- a/project_euler/problem_48/sol1.py +++ b/project_euler/problem_48/sol1.py @@ -7,11 +7,6 @@ Find the last ten digits of the series, 11 + 22 + 33 + ... + 10001000. """ -try: - xrange -except NameError: - xrange = range - def solution(): """Returns the last 10 digits of the series, 11 + 22 + 33 + ... + 10001000. @@ -20,7 +15,7 @@ def solution(): '9110846700' """ total = 0 - for i in xrange(1, 1001): + for i in range(1, 1001): total += i ** i return str(total)[-10:] diff --git a/project_euler/problem_53/sol1.py b/project_euler/problem_53/sol1.py index c72e0b993a34..f17508b005d1 100644 --- a/project_euler/problem_53/sol1.py +++ b/project_euler/problem_53/sol1.py @@ -17,14 +17,8 @@ How many, not necessarily distinct, values of nCr, for 1 ≤ n ≤ 100, are greater than one-million? """ -from __future__ import print_function from math import factorial -try: - xrange # Python 2 -except NameError: - xrange = range # Python 3 - def combinations(n, r): return factorial(n) / (factorial(r) * factorial(n - r)) @@ -39,8 +33,8 @@ def solution(): """ total = 0 - for i in xrange(1, 101): - for j in xrange(1, i + 1): + for i in range(1, 101): + for j in range(1, i + 1): if combinations(i, j) > 1e6: total += 1 return total diff --git a/project_euler/problem_76/sol1.py b/project_euler/problem_76/sol1.py index c9e3c452fbc4..ed0ee6b507e9 100644 --- a/project_euler/problem_76/sol1.py +++ b/project_euler/problem_76/sol1.py @@ -14,12 +14,6 @@ How many different ways can one hundred be written as a sum of at least two positive integers? """ -from __future__ import print_function - -try: - xrange # Python 2 -except NameError: - xrange = range # Python 3 def partition(m): @@ -43,12 +37,12 @@ def partition(m): >>> partition(1) 0 """ - memo = [[0 for _ in xrange(m)] for _ in xrange(m + 1)] - for i in xrange(m + 1): + memo = [[0 for _ in range(m)] for _ in range(m + 1)] + for i in range(m + 1): memo[i][0] = 1 - for n in xrange(m + 1): - for k in xrange(1, m): + for n in range(m + 1): + for k in range(1, m): memo[n][k] += memo[n][k - 1] if n > k: memo[n][k] += memo[n - k - 1][k] diff --git a/searches/binary_search.py b/searches/binary_search.py index e658dac2a3ef..77abf90239ab 100644 --- a/searches/binary_search.py +++ b/searches/binary_search.py @@ -9,14 +9,8 @@ For manual testing run: 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 @@ -112,7 +106,7 @@ def binary_search_by_recursion(sorted_collection, item, left, right): """ if (right < left): return None - + midpoint = left + (right - left) // 2 if sorted_collection[midpoint] == item: @@ -121,7 +115,7 @@ def binary_search_by_recursion(sorted_collection, item, left, right): return binary_search_by_recursion(sorted_collection, item, left, midpoint-1) else: return binary_search_by_recursion(sorted_collection, item, midpoint+1, right) - + def __assert_sorted(collection): """Check if collection is ascending sorted, if not - raises :py:class:`ValueError` @@ -145,14 +139,14 @@ def __assert_sorted(collection): if __name__ == '__main__': import sys - user_input = raw_input('Enter numbers separated by comma:\n').strip() + user_input = 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 ascending sorted to apply binary search') - target_input = raw_input('Enter a single number to be found in the list:\n') + target_input = 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 329596d340a5..27ee979bb649 100644 --- a/searches/interpolation_search.py +++ b/searches/interpolation_search.py @@ -1,12 +1,6 @@ """ This is pure python implementation of interpolation search algorithm """ -from __future__ import print_function - -try: - raw_input # Python 2 -except NameError: - raw_input = input # Python 3 def interpolation_search(sorted_collection, item): @@ -29,7 +23,7 @@ def interpolation_search(sorted_collection, item): return None point = left + ((item - sorted_collection[left]) * (right - left)) // (sorted_collection[right] - sorted_collection[left]) - + #out of range check if point<0 or point>=len(sorted_collection): return None @@ -42,9 +36,9 @@ def interpolation_search(sorted_collection, item): right = left left = point elif point>right: - left = right + left = right right = point - else: + else: if item < current_item: right = point - 1 else: @@ -70,7 +64,7 @@ def interpolation_search_by_recursion(sorted_collection, item, left, right): return None point = left + ((item - sorted_collection[left]) * (right - left)) // (sorted_collection[right] - sorted_collection[left]) - + #out of range check if point<0 or point>=len(sorted_collection): return None @@ -86,7 +80,7 @@ def interpolation_search_by_recursion(sorted_collection, item, left, right): return interpolation_search_by_recursion(sorted_collection, item, left, point-1) else: return interpolation_search_by_recursion(sorted_collection, item, point+1, right) - + def __assert_sorted(collection): """Check if collection is ascending sorted, if not - raises :py:class:`ValueError` :param collection: collection @@ -107,16 +101,16 @@ def __assert_sorted(collection): if __name__ == '__main__': import sys - + """ - user_input = raw_input('Enter numbers separated by comma:\n').strip() + user_input = 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 ascending sorted to apply interpolation search') - target_input = raw_input('Enter a single number to be found in the list:\n') + target_input = input('Enter a single number to be found in the list:\n') target = int(target_input) """ @@ -128,7 +122,7 @@ def __assert_sorted(collection): except ValueError: sys.exit('Sequence must be ascending sorted to apply interpolation search') target = 67 - + result = interpolation_search(collection, target) if result is not None: print('{} found at positions: {}'.format(target, result)) diff --git a/searches/jump_search.py b/searches/jump_search.py index 10cb933f2f35..78d9f79dc6a8 100644 --- a/searches/jump_search.py +++ b/searches/jump_search.py @@ -1,4 +1,3 @@ -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 058322f21d09..fb784924132e 100644 --- a/searches/linear_search.py +++ b/searches/linear_search.py @@ -9,12 +9,7 @@ For manual testing run: 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 @@ -43,10 +38,10 @@ def linear_search(sequence, target): if __name__ == '__main__': - user_input = raw_input('Enter numbers separated by comma:\n').strip() + user_input = input('Enter numbers separated by comma:\n').strip() sequence = [int(item) for item in user_input.split(',')] - target_input = raw_input('Enter a single number to be found in the list:\n') + target_input = 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/sentinel_linear_search.py b/searches/sentinel_linear_search.py index 336cc5ab3b74..eb9d32e5f503 100644 --- a/searches/sentinel_linear_search.py +++ b/searches/sentinel_linear_search.py @@ -45,15 +45,10 @@ def sentinel_linear_search(sequence, target): if __name__ == '__main__': - try: - raw_input # Python 2 - except NameError: - raw_input = input # Python 3 - - user_input = raw_input('Enter numbers separated by comma:\n').strip() + user_input = input('Enter numbers separated by comma:\n').strip() sequence = [int(item) for item in user_input.split(',')] - target_input = raw_input('Enter a single number to be found in the list:\n') + target_input = input('Enter a single number to be found in the list:\n') target = int(target_input) result = sentinel_linear_search(sequence, target) if result is not None: diff --git a/searches/ternary_search.py b/searches/ternary_search.py index c610f9b3c6da..41033f33cec6 100644 --- a/searches/ternary_search.py +++ b/searches/ternary_search.py @@ -1,20 +1,13 @@ ''' This is a type of divide and conquer algorithm which divides the search space into -3 parts and finds the target value based on the property of the array or list +3 parts and finds the target value based on the property of the array or list (usually monotonic property). 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 @@ -31,23 +24,23 @@ def ite_ternary_search(A, target): right = len(A) - 1; while(True): if(left>> bubble_sort([-2, -5, -45]) [-45, -5, -2] - - >>> bubble_sort([-23,0,6,-4,34]) + + >>> bubble_sort([-23, 0, 6, -4, 34]) [-23, -4, 0, 6, 34] + + >>> bubble_sort([-23, 0, 6, -4, 34]) == sorted([-23, 0, 6, -4, 34]) + True """ length = len(collection) for i in range(length-1): @@ -28,15 +28,12 @@ def bubble_sort(collection): if collection[j] > collection[j+1]: swapped = True collection[j], collection[j+1] = collection[j+1], collection[j] - if not swapped: break # Stop iteration if the collection is sorted. + if not swapped: + break # Stop iteration if the collection is sorted. return collection if __name__ == '__main__': - try: - raw_input # Python 2 - except NameError: - raw_input = input # Python 3 - user_input = raw_input('Enter numbers separated by a comma:').strip() + user_input = input('Enter numbers separated by a comma:').strip() unsorted = [int(item) for item in user_input.split(',')] print(*bubble_sort(unsorted), sep=',') diff --git a/sorts/cocktail_shaker_sort.py b/sorts/cocktail_shaker_sort.py index 8ad3383bbe9f..d486e6a11dfa 100644 --- a/sorts/cocktail_shaker_sort.py +++ b/sorts/cocktail_shaker_sort.py @@ -1,12 +1,10 @@ -from __future__ import print_function - def cocktail_shaker_sort(unsorted): """ Pure implementation of the cocktail shaker sort algorithm in Python. """ for i in range(len(unsorted)-1, 0, -1): swapped = False - + for j in range(i, 0, -1): if unsorted[j] < unsorted[j-1]: unsorted[j], unsorted[j-1] = unsorted[j-1], unsorted[j] @@ -16,17 +14,12 @@ def cocktail_shaker_sort(unsorted): if unsorted[j] > unsorted[j+1]: unsorted[j], unsorted[j+1] = unsorted[j+1], unsorted[j] swapped = True - + if not swapped: return unsorted - + if __name__ == '__main__': - try: - raw_input # Python 2 - except NameError: - raw_input = input # Python 3 - - user_input = raw_input('Enter numbers separated by a comma:\n').strip() + user_input = input('Enter numbers separated by a comma:\n').strip() unsorted = [int(item) for item in user_input.split(',')] cocktail_shaker_sort(unsorted) print(unsorted) diff --git a/sorts/comb_sort.py b/sorts/comb_sort.py index 22b6f66f04cc..6ce6c1c094f9 100644 --- a/sorts/comb_sort.py +++ b/sorts/comb_sort.py @@ -48,11 +48,6 @@ def comb_sort(data): if __name__ == '__main__': - try: - raw_input # Python 2 - except NameError: - raw_input = input # Python 3 - - user_input = raw_input('Enter numbers separated by a comma:\n').strip() + user_input = input('Enter numbers separated by a comma:\n').strip() unsorted = [int(item) for item in user_input.split(',')] print(comb_sort(unsorted)) diff --git a/sorts/counting_sort.py b/sorts/counting_sort.py index ad98f1a0da4c..a3de1811849e 100644 --- a/sorts/counting_sort.py +++ b/sorts/counting_sort.py @@ -8,8 +8,6 @@ python counting_sort.py """ -from __future__ import print_function - def counting_sort(collection): """Pure implementation of counting sort algorithm in Python @@ -58,6 +56,10 @@ def counting_sort(collection): return ordered def counting_sort_string(string): + """ + >>> counting_sort_string("thisisthestring") + 'eghhiiinrsssttt' + """ return ''.join([chr(i) for i in counting_sort([ord(c) for c in string])]) @@ -65,11 +67,6 @@ def counting_sort_string(string): # Test string sort assert "eghhiiinrsssttt" == counting_sort_string("thisisthestring") - try: - raw_input # Python 2 - except NameError: - raw_input = input # Python 3 - - user_input = raw_input('Enter numbers separated by a comma:\n').strip() + user_input = 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/cycle_sort.py b/sorts/cycle_sort.py index 492022164427..06a377cbd906 100644 --- a/sorts/cycle_sort.py +++ b/sorts/cycle_sort.py @@ -1,7 +1,4 @@ # Code contributed by Honey Sharma -from __future__ import print_function - - def cycle_sort(array): ans = 0 @@ -45,12 +42,7 @@ def cycle_sort(array): # Main Code starts here if __name__ == '__main__': - try: - raw_input # Python 2 - except NameError: - raw_input = input # Python 3 - - user_input = raw_input('Enter numbers separated by a comma:\n') + user_input = input('Enter numbers separated by a comma:\n') unsorted = [int(item) for item in user_input.split(',')] n = len(unsorted) cycle_sort(unsorted) diff --git a/sorts/gnome_sort.py b/sorts/gnome_sort.py index 075749e37663..fed70eb6bc1b 100644 --- a/sorts/gnome_sort.py +++ b/sorts/gnome_sort.py @@ -1,7 +1,5 @@ """Gnome Sort Algorithm.""" -from __future__ import print_function - def gnome_sort(unsorted): """Pure implementation of the gnome sort algorithm in Python.""" @@ -21,12 +19,7 @@ def gnome_sort(unsorted): if __name__ == '__main__': - try: - raw_input # Python 2 - except NameError: - raw_input = input # Python 3 - - user_input = raw_input('Enter numbers separated by a comma:\n').strip() + user_input = input('Enter numbers separated by a comma:\n').strip() unsorted = [int(item) for item in user_input.split(',')] gnome_sort(unsorted) print(unsorted) diff --git a/sorts/heap_sort.py b/sorts/heap_sort.py index 3c72abca8059..ca4a061afbb7 100644 --- a/sorts/heap_sort.py +++ b/sorts/heap_sort.py @@ -10,9 +10,6 @@ python heap_sort.py ''' -from __future__ import print_function - - def heapify(unsorted, index, heap_size): largest = index left_index = 2 * index + 1 @@ -54,11 +51,6 @@ def heap_sort(unsorted): return unsorted if __name__ == '__main__': - try: - raw_input # Python 2 - except NameError: - raw_input = input # Python 3 - - user_input = raw_input('Enter numbers separated by a comma:\n').strip() + user_input = 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 e088705947d4..e10497b0e282 100644 --- a/sorts/insertion_sort.py +++ b/sorts/insertion_sort.py @@ -9,9 +9,6 @@ For manual testing run: python insertion_sort.py """ -from __future__ import print_function - - def insertion_sort(collection): """Pure implementation of the insertion sort algorithm in Python @@ -40,11 +37,6 @@ def insertion_sort(collection): if __name__ == '__main__': - try: - raw_input # Python 2 - except NameError: - raw_input = input # Python 3 - - user_input = raw_input('Enter numbers separated by a comma:\n').strip() + user_input = 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 714861e72642..e64e90785a32 100644 --- a/sorts/merge_sort.py +++ b/sorts/merge_sort.py @@ -9,9 +9,6 @@ For manual testing run: python merge_sort.py """ -from __future__ import print_function - - def merge_sort(collection): """Pure implementation of the merge sort algorithm in Python @@ -46,11 +43,6 @@ def merge(left, right): if __name__ == '__main__': - try: - raw_input # Python 2 - except NameError: - raw_input = input # Python 3 - - user_input = raw_input('Enter numbers separated by a comma:\n').strip() + user_input = input('Enter numbers separated by a comma:\n').strip() unsorted = [int(item) for item in user_input.split(',')] print(*merge_sort(unsorted), sep=',') diff --git a/sorts/merge_sort_fastest.py b/sorts/merge_sort_fastest.py index bd356c935ca0..3c9ed3e9e8ee 100644 --- a/sorts/merge_sort_fastest.py +++ b/sorts/merge_sort_fastest.py @@ -4,9 +4,6 @@ Best Case Scenario : O(n) Worst Case Scenario : O(n^2) because native python functions:min, max and remove are already O(n) ''' -from __future__ import print_function - - def merge_sort(collection): """Pure implementation of the fastest merge sort algorithm in Python @@ -36,11 +33,6 @@ def merge_sort(collection): if __name__ == '__main__': - try: - raw_input # Python 2 - except NameError: - raw_input = input # Python 3 - - user_input = raw_input('Enter numbers separated by a comma:\n').strip() + user_input = input('Enter numbers separated by a comma:\n').strip() unsorted = [int(item) for item in user_input.split(',')] print(*merge_sort(unsorted), sep=',') diff --git a/sorts/pigeon_sort.py b/sorts/pigeon_sort.py index 65eb8896ea9c..5e5afa137685 100644 --- a/sorts/pigeon_sort.py +++ b/sorts/pigeon_sort.py @@ -1,9 +1,6 @@ ''' This is an implementation of Pigeon Hole Sort. ''' - -from __future__ import print_function - def pigeon_sort(array): # Manually finds the minimum and maximum of the array. min = array[0] @@ -38,12 +35,7 @@ def pigeon_sort(array): return array if __name__ == '__main__': - try: - raw_input # Python2 - except NameError: - raw_input = input # Python 3 - - user_input = raw_input('Enter numbers separated by comma:\n') + user_input = input('Enter numbers separated by comma:\n') unsorted = [int(x) for x in user_input.split(',')] sorted = pigeon_sort(unsorted) diff --git a/sorts/quick_sort.py b/sorts/quick_sort.py index 7e8c868ebb06..60f8803cb79c 100644 --- a/sorts/quick_sort.py +++ b/sorts/quick_sort.py @@ -9,9 +9,6 @@ For manual testing run: python quick_sort.py """ -from __future__ import print_function - - def quick_sort(collection): """Pure implementation of quick sort algorithm in Python @@ -47,11 +44,6 @@ def quick_sort(collection): if __name__ == '__main__': - try: - raw_input # Python 2 - except NameError: - raw_input = input # Python 3 - - user_input = raw_input('Enter numbers separated by a comma:\n').strip() + user_input = 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/quick_sort_3_partition.py b/sorts/quick_sort_3_partition.py index def646cdbc50..9056b204740a 100644 --- a/sorts/quick_sort_3_partition.py +++ b/sorts/quick_sort_3_partition.py @@ -1,5 +1,3 @@ -from __future__ import print_function - def quick_sort_3partition(sorting, left, right): if right <= left: return @@ -20,12 +18,7 @@ def quick_sort_3partition(sorting, left, right): quick_sort_3partition(sorting, b + 1, right) if __name__ == '__main__': - try: - raw_input # Python 2 - except NameError: - raw_input = input # Python 3 - - user_input = raw_input('Enter numbers separated by a comma:\n').strip() + user_input = input('Enter numbers separated by a comma:\n').strip() unsorted = [ int(item) for item in user_input.split(',') ] quick_sort_3partition(unsorted,0,len(unsorted)-1) print(unsorted) diff --git a/sorts/random_normal_distribution_quicksort.py b/sorts/random_normal_distribution_quicksort.py index dfa37da61e26..39c54c46e263 100644 --- a/sorts/random_normal_distribution_quicksort.py +++ b/sorts/random_normal_distribution_quicksort.py @@ -1,25 +1,23 @@ -from __future__ import print_function from random import randint from tempfile import TemporaryFile import numpy as np - -def _inPlaceQuickSort(A,start,end): +def _inPlaceQuickSort(A,start,end): count = 0 if start