Skip to content

Commit

Permalink
Simplify code by dropping support for legacy Python (TheAlgorithms#1143)
Browse files Browse the repository at this point in the history
* Simplify code by dropping support for legacy Python

* sort() --> sorted()
  • Loading branch information
cclauss authored Aug 19, 2019
1 parent 32aa7ff commit 47a9ea2
Show file tree
Hide file tree
Showing 145 changed files with 367 additions and 976 deletions.
20 changes: 10 additions & 10 deletions CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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())
```
Expand All @@ -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.
Expand Down
1 change: 0 additions & 1 deletion ciphers/affine_cipher.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
from __future__ import print_function
import sys, random, cryptomath_module as cryptoMath

SYMBOLS = r""" !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~"""
Expand Down
20 changes: 6 additions & 14 deletions ciphers/atbash.py
Original file line number Diff line number Diff line change
@@ -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()
1 change: 0 additions & 1 deletion ciphers/brute_force_caesar_cipher.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
from __future__ import print_function
def decrypt(message):
"""
>>> decrypt('TMDETUX PMDVU')
Expand Down
4 changes: 1 addition & 3 deletions ciphers/onepad_cipher.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
from __future__ import print_function

import random


Expand All @@ -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 = []
Expand Down
1 change: 0 additions & 1 deletion ciphers/rabin_miller.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
from __future__ import print_function
# Primality Testing with the Rabin-Miller Algorithm

import random
Expand Down
1 change: 0 additions & 1 deletion ciphers/rot13.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
from __future__ import print_function
def dencrypt(s, n):
out = ''
for c in s:
Expand Down
3 changes: 1 addition & 2 deletions ciphers/rsa_cipher.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
from __future__ import print_function
import sys, rsa_key_generator as rkg, os

DEFAULT_BLOCK_SIZE = 128
Expand All @@ -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))
Expand Down
1 change: 0 additions & 1 deletion ciphers/rsa_key_generator.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
from __future__ import print_function
import random, sys, os
import rabin_miller as rabinMiller, cryptomath_module as cryptoMath

Expand Down
5 changes: 2 additions & 3 deletions ciphers/simple_substitution_cipher.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
from __future__ import print_function
import sys, random

LETTERS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
Expand All @@ -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)
Expand Down Expand Up @@ -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())
Expand Down
1 change: 0 additions & 1 deletion ciphers/transposition_cipher.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
from __future__ import print_function
import math

def main():
Expand Down
7 changes: 3 additions & 4 deletions ciphers/transposition_cipher_encrypt_decrypt_file.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
from __future__ import print_function
import time, os, sys
import transposition_cipher as transCipher

Expand All @@ -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:
Expand All @@ -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()
1 change: 0 additions & 1 deletion ciphers/vigenere_cipher.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
from __future__ import print_function
LETTERS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'

def main():
Expand Down
15 changes: 7 additions & 8 deletions data_structures/binary_tree/binary_search_tree.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
'''
A binary search Tree
'''
from __future__ import print_function
class Node:

def __init__(self, label, parent):
Expand Down Expand Up @@ -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
Expand All @@ -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
Expand Down Expand Up @@ -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)
Expand All @@ -203,7 +202,7 @@ def testBinarySearchTree():
/ \ \
1 6 14
/ \ /
4 7 13
4 7 13
'''

r'''
Expand Down Expand Up @@ -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)
Expand Down
1 change: 0 additions & 1 deletion data_structures/binary_tree/fenwick_tree.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
from __future__ import print_function
class FenwickTree:

def __init__(self, SIZE): # create fenwick tree with size SIZE
Expand Down
1 change: 0 additions & 1 deletion data_structures/binary_tree/lazy_segment_tree.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
from __future__ import print_function
import math

class SegmentTree:
Expand Down
1 change: 0 additions & 1 deletion data_structures/binary_tree/segment_tree.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
from __future__ import print_function
import math

class SegmentTree:
Expand Down
13 changes: 3 additions & 10 deletions data_structures/heap/heap.py
Original file line number Diff line number Diff line change
@@ -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

Expand Down Expand Up @@ -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()
Expand Down
27 changes: 13 additions & 14 deletions data_structures/linked_list/doubly_linked_list.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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:
Expand Down
Loading

0 comments on commit 47a9ea2

Please sign in to comment.