zip
stringlengths 19
109
| filename
stringlengths 4
185
| contents
stringlengths 0
30.1M
| type_annotations
sequencelengths 0
1.97k
| type_annotation_starts
sequencelengths 0
1.97k
| type_annotation_ends
sequencelengths 0
1.97k
|
---|---|---|---|---|---|
archives/1098994933_python.zip | backtracking/sudoku.py | """
Given a partially filled 9×9 2D array, the objective is to fill a 9×9
square grid with digits numbered 1 to 9, so that every row, column, and
and each of the nine 3×3 sub-grids contains all of the digits.
This can be solved using Backtracking and is similar to n-queens.
We check to see if a cell is safe or not and recursively call the
function on the next column to see if it returns True. if yes, we
have solved the puzzle. else, we backtrack and place another number
in that cell and repeat this process.
"""
# assigning initial values to the grid
initial_grid = [
[3, 0, 6, 5, 0, 8, 4, 0, 0],
[5, 2, 0, 0, 0, 0, 0, 0, 0],
[0, 8, 7, 0, 0, 0, 0, 3, 1],
[0, 0, 3, 0, 1, 0, 0, 8, 0],
[9, 0, 0, 8, 6, 3, 0, 0, 5],
[0, 5, 0, 0, 9, 0, 6, 0, 0],
[1, 3, 0, 0, 0, 0, 2, 5, 0],
[0, 0, 0, 0, 0, 0, 0, 7, 4],
[0, 0, 5, 2, 0, 6, 3, 0, 0],
]
# a grid with no solution
no_solution = [
[5, 0, 6, 5, 0, 8, 4, 0, 3],
[5, 2, 0, 0, 0, 0, 0, 0, 2],
[1, 8, 7, 0, 0, 0, 0, 3, 1],
[0, 0, 3, 0, 1, 0, 0, 8, 0],
[9, 0, 0, 8, 6, 3, 0, 0, 5],
[0, 5, 0, 0, 9, 0, 6, 0, 0],
[1, 3, 0, 0, 0, 0, 2, 5, 0],
[0, 0, 0, 0, 0, 0, 0, 7, 4],
[0, 0, 5, 2, 0, 6, 3, 0, 0],
]
def is_safe(grid, row, column, n):
"""
This function checks the grid to see if each row,
column, and the 3x3 subgrids contain the digit 'n'.
It returns False if it is not 'safe' (a duplicate digit
is found) else returns True if it is 'safe'
"""
for i in range(9):
if grid[row][i] == n or grid[i][column] == n:
return False
for i in range(3):
for j in range(3):
if grid[(row - row % 3) + i][(column - column % 3) + j] == n:
return False
return True
def is_completed(grid):
"""
This function checks if the puzzle is completed or not.
it is completed when all the cells are assigned with a number(not zero)
and There is no repeating number in any column, row or 3x3 subgrid.
"""
for row in grid:
for cell in row:
if cell == 0:
return False
return True
def find_empty_location(grid):
"""
This function finds an empty location so that we can assign a number
for that particular row and column.
"""
for i in range(9):
for j in range(9):
if grid[i][j] == 0:
return i, j
def sudoku(grid):
"""
Takes a partially filled-in grid and attempts to assign values to
all unassigned locations in such a way to meet the requirements
for Sudoku solution (non-duplication across rows, columns, and boxes)
>>> sudoku(initial_grid) # doctest: +NORMALIZE_WHITESPACE
[[3, 1, 6, 5, 7, 8, 4, 9, 2],
[5, 2, 9, 1, 3, 4, 7, 6, 8],
[4, 8, 7, 6, 2, 9, 5, 3, 1],
[2, 6, 3, 4, 1, 5, 9, 8, 7],
[9, 7, 4, 8, 6, 3, 1, 2, 5],
[8, 5, 1, 7, 9, 2, 6, 4, 3],
[1, 3, 8, 9, 4, 7, 2, 5, 6],
[6, 9, 2, 3, 5, 1, 8, 7, 4],
[7, 4, 5, 2, 8, 6, 3, 1, 9]]
>>> sudoku(no_solution)
False
"""
if is_completed(grid):
return grid
row, column = find_empty_location(grid)
for digit in range(1, 10):
if is_safe(grid, row, column, digit):
grid[row][column] = digit
if sudoku(grid):
return grid
grid[row][column] = 0
return False
def print_solution(grid):
"""
A function to print the solution in the form
of a 9x9 grid
"""
for row in grid:
for cell in row:
print(cell, end=" ")
print()
if __name__ == "__main__":
# make a copy of grid so that you can compare with the unmodified grid
for grid in (initial_grid, no_solution):
grid = list(map(list, grid))
solution = sudoku(grid)
if solution:
print("grid after solving:")
print_solution(solution)
else:
print("Cannot find a solution.")
| [] | [] | [] |
archives/1098994933_python.zip | backtracking/sum_of_subsets.py | '''
The sum-of-subsetsproblem states that a set of non-negative integers, and a value M,
determine all possible subsets of the given set whose summation sum equal to given M.
Summation of the chosen numbers must be equal to given number M and one number can
be used only once.
'''
def generate_sum_of_subsets_soln(nums, max_sum):
result = []
path = []
num_index = 0
remaining_nums_sum = sum(nums)
create_state_space_tree(nums, max_sum, num_index, path,result, remaining_nums_sum)
return result
def create_state_space_tree(nums,max_sum,num_index,path,result, remaining_nums_sum):
'''
Creates a state space tree to iterate through each branch using DFS.
It terminates the branching of a node when any of the two conditions
given below satisfy.
This algorithm follows depth-fist-search and backtracks when the node is not branchable.
'''
if sum(path) > max_sum or (remaining_nums_sum + sum(path)) < max_sum:
return
if sum(path) == max_sum:
result.append(path)
return
for num_index in range(num_index,len(nums)):
create_state_space_tree(nums, max_sum, num_index + 1, path + [nums[num_index]], result, remaining_nums_sum - nums[num_index])
'''
remove the comment to take an input from the user
print("Enter the elements")
nums = list(map(int, input().split()))
print("Enter max_sum sum")
max_sum = int(input())
'''
nums = [3, 34, 4, 12, 5, 2]
max_sum = 9
result = generate_sum_of_subsets_soln(nums,max_sum)
print(*result) | [] | [] | [] |
archives/1098994933_python.zip | boolean_algebra/quine_mc_cluskey.py | def compare_string(string1, string2):
"""
>>> compare_string('0010','0110')
'0_10'
>>> compare_string('0110','1101')
-1
"""
l1 = list(string1); l2 = list(string2)
count = 0
for i in range(len(l1)):
if l1[i] != l2[i]:
count += 1
l1[i] = '_'
if count > 1:
return -1
else:
return("".join(l1))
def check(binary):
"""
>>> check(['0.00.01.5'])
['0.00.01.5']
"""
pi = []
while 1:
check1 = ['$']*len(binary)
temp = []
for i in range(len(binary)):
for j in range(i+1, len(binary)):
k=compare_string(binary[i], binary[j])
if k != -1:
check1[i] = '*'
check1[j] = '*'
temp.append(k)
for i in range(len(binary)):
if check1[i] == '$':
pi.append(binary[i])
if len(temp) == 0:
return pi
binary = list(set(temp))
def decimal_to_binary(no_of_variable, minterms):
"""
>>> decimal_to_binary(3,[1.5])
['0.00.01.5']
"""
temp = []
s = ''
for m in minterms:
for i in range(no_of_variable):
s = str(m%2) + s
m //= 2
temp.append(s)
s = ''
return temp
def is_for_table(string1, string2, count):
"""
>>> is_for_table('__1','011',2)
True
>>> is_for_table('01_','001',1)
False
"""
l1 = list(string1);l2=list(string2)
count_n = 0
for i in range(len(l1)):
if l1[i] != l2[i]:
count_n += 1
if count_n == count:
return True
else:
return False
def selection(chart, prime_implicants):
"""
>>> selection([[1]],['0.00.01.5'])
['0.00.01.5']
>>> selection([[1]],['0.00.01.5'])
['0.00.01.5']
"""
temp = []
select = [0]*len(chart)
for i in range(len(chart[0])):
count = 0
rem = -1
for j in range(len(chart)):
if chart[j][i] == 1:
count += 1
rem = j
if count == 1:
select[rem] = 1
for i in range(len(select)):
if select[i] == 1:
for j in range(len(chart[0])):
if chart[i][j] == 1:
for k in range(len(chart)):
chart[k][j] = 0
temp.append(prime_implicants[i])
while 1:
max_n = 0; rem = -1; count_n = 0
for i in range(len(chart)):
count_n = chart[i].count(1)
if count_n > max_n:
max_n = count_n
rem = i
if max_n == 0:
return temp
temp.append(prime_implicants[rem])
for i in range(len(chart[0])):
if chart[rem][i] == 1:
for j in range(len(chart)):
chart[j][i] = 0
def prime_implicant_chart(prime_implicants, binary):
"""
>>> prime_implicant_chart(['0.00.01.5'],['0.00.01.5'])
[[1]]
"""
chart = [[0 for x in range(len(binary))] for x in range(len(prime_implicants))]
for i in range(len(prime_implicants)):
count = prime_implicants[i].count('_')
for j in range(len(binary)):
if(is_for_table(prime_implicants[i], binary[j], count)):
chart[i][j] = 1
return chart
def main():
no_of_variable = int(input("Enter the no. of variables\n"))
minterms = [int(x) for x in input("Enter the decimal representation of Minterms 'Spaces Seprated'\n").split()]
binary = decimal_to_binary(no_of_variable, minterms)
prime_implicants = check(binary)
print("Prime Implicants are:")
print(prime_implicants)
chart = prime_implicant_chart(prime_implicants, binary)
essential_prime_implicants = selection(chart,prime_implicants)
print("Essential Prime Implicants are:")
print(essential_prime_implicants)
if __name__ == '__main__':
import doctest
doctest.testmod()
main()
| [] | [] | [] |
archives/1098994933_python.zip | ciphers/affine_cipher.py | import sys, random, cryptomath_module as cryptoMath
SYMBOLS = r""" !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~"""
def main():
message = input('Enter message: ')
key = int(input('Enter key [2000 - 9000]: '))
mode = input('Encrypt/Decrypt [E/D]: ')
if mode.lower().startswith('e'):
mode = 'encrypt'
translated = encryptMessage(key, message)
elif mode.lower().startswith('d'):
mode = 'decrypt'
translated = decryptMessage(key, message)
print('\n%sed text: \n%s' % (mode.title(), translated))
def getKeyParts(key):
keyA = key // len(SYMBOLS)
keyB = key % len(SYMBOLS)
return (keyA, keyB)
def checkKeys(keyA, keyB, mode):
if keyA == 1 and mode == 'encrypt':
sys.exit('The affine cipher becomes weak when key A is set to 1. Choose different key')
if keyB == 0 and mode == 'encrypt':
sys.exit('The affine cipher becomes weak when key A is set to 1. Choose different key')
if keyA < 0 or keyB < 0 or keyB > len(SYMBOLS) - 1:
sys.exit('Key A must be greater than 0 and key B must be between 0 and %s.' % (len(SYMBOLS) - 1))
if cryptoMath.gcd(keyA, len(SYMBOLS)) != 1:
sys.exit('Key A %s and the symbol set size %s are not relatively prime. Choose a different key.' % (keyA, len(SYMBOLS)))
def encryptMessage(key, message):
'''
>>> encryptMessage(4545, 'The affine cipher is a type of monoalphabetic substitution cipher.')
'VL}p MM{I}p~{HL}Gp{vp pFsH}pxMpyxIx JHL O}F{~pvuOvF{FuF{xIp~{HL}Gi'
'''
keyA, keyB = getKeyParts(key)
checkKeys(keyA, keyB, 'encrypt')
cipherText = ''
for symbol in message:
if symbol in SYMBOLS:
symIndex = SYMBOLS.find(symbol)
cipherText += SYMBOLS[(symIndex * keyA + keyB) % len(SYMBOLS)]
else:
cipherText += symbol
return cipherText
def decryptMessage(key, message):
'''
>>> decryptMessage(4545, 'VL}p MM{I}p~{HL}Gp{vp pFsH}pxMpyxIx JHL O}F{~pvuOvF{FuF{xIp~{HL}Gi')
'The affine cipher is a type of monoalphabetic substitution cipher.'
'''
keyA, keyB = getKeyParts(key)
checkKeys(keyA, keyB, 'decrypt')
plainText = ''
modInverseOfkeyA = cryptoMath.findModInverse(keyA, len(SYMBOLS))
for symbol in message:
if symbol in SYMBOLS:
symIndex = SYMBOLS.find(symbol)
plainText += SYMBOLS[(symIndex - keyB) * modInverseOfkeyA % len(SYMBOLS)]
else:
plainText += symbol
return plainText
def getRandomKey():
while True:
keyA = random.randint(2, len(SYMBOLS))
keyB = random.randint(2, len(SYMBOLS))
if cryptoMath.gcd(keyA, len(SYMBOLS)) == 1:
return keyA * len(SYMBOLS) + keyB
if __name__ == '__main__':
import doctest
doctest.testmod()
main()
| [] | [] | [] |
archives/1098994933_python.zip | ciphers/atbash.py | def atbash():
output=""
for i in input("Enter the sentence to be encrypted ").strip():
extract = ord(i)
if 65 <= extract <= 90:
output += chr(155-extract)
elif 97 <= extract <= 122:
output += chr(219-extract)
else:
output += i
print(output)
if __name__ == '__main__':
atbash()
| [] | [] | [] |
archives/1098994933_python.zip | ciphers/base16.py | import base64
def main():
inp = input('->')
encoded = inp.encode('utf-8') #encoded the input (we need a bytes like object)
b16encoded = base64.b16encode(encoded) #b16encoded the encoded string
print(b16encoded)
print(base64.b16decode(b16encoded).decode('utf-8'))#decoded it
if __name__ == '__main__':
main()
| [] | [] | [] |
archives/1098994933_python.zip | ciphers/base32.py | import base64
def main():
inp = input('->')
encoded = inp.encode('utf-8') #encoded the input (we need a bytes like object)
b32encoded = base64.b32encode(encoded) #b32encoded the encoded string
print(b32encoded)
print(base64.b32decode(b32encoded).decode('utf-8'))#decoded it
if __name__ == '__main__':
main()
| [] | [] | [] |
archives/1098994933_python.zip | ciphers/base64_cipher.py | def encodeBase64(text):
base64chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
r = "" #the result
c = 3 - len(text) % 3 #the length of padding
p = "=" * c #the padding
s = text + "\0" * c #the text to encode
i = 0
while i < len(s):
if i > 0 and ((i / 3 * 4) % 76) == 0:
r = r + "\r\n"
n = (ord(s[i]) << 16) + (ord(s[i+1]) << 8 ) + ord(s[i+2])
n1 = (n >> 18) & 63
n2 = (n >> 12) & 63
n3 = (n >> 6) & 63
n4 = n & 63
r += base64chars[n1] + base64chars[n2] + base64chars[n3] + base64chars[n4]
i += 3
return r[0: len(r)-len(p)] + p
def decodeBase64(text):
base64chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
s = ""
for i in text:
if i in base64chars:
s += i
c = ""
else:
if i == '=':
c += '='
p = ""
if c == "=":
p = 'A'
else:
if c == "==":
p = "AA"
r = ""
s = s + p
i = 0
while i < len(s):
n = (base64chars.index(s[i]) << 18) + (base64chars.index(s[i+1]) << 12) + (base64chars.index(s[i+2]) << 6) +base64chars.index(s[i+3])
r += chr((n >> 16) & 255) + chr((n >> 8) & 255) + chr(n & 255)
i += 4
return r[0: len(r) - len(p)]
def main():
print(encodeBase64("WELCOME to base64 encoding"))
print(decodeBase64(encodeBase64("WELCOME to base64 encoding")))
if __name__ == '__main__':
main()
| [] | [] | [] |
archives/1098994933_python.zip | ciphers/base85.py | import base64
def main():
inp = input('->')
encoded = inp.encode('utf-8') #encoded the input (we need a bytes like object)
a85encoded = base64.a85encode(encoded) #a85encoded the encoded string
print(a85encoded)
print(base64.a85decode(a85encoded).decode('utf-8'))#decoded it
if __name__ == '__main__':
main()
| [] | [] | [] |
archives/1098994933_python.zip | ciphers/brute_force_caesar_cipher.py | def decrypt(message):
"""
>>> decrypt('TMDETUX PMDVU')
Decryption using Key #0: TMDETUX PMDVU
Decryption using Key #1: SLCDSTW OLCUT
Decryption using Key #2: RKBCRSV NKBTS
Decryption using Key #3: QJABQRU MJASR
Decryption using Key #4: PIZAPQT LIZRQ
Decryption using Key #5: OHYZOPS KHYQP
Decryption using Key #6: NGXYNOR JGXPO
Decryption using Key #7: MFWXMNQ IFWON
Decryption using Key #8: LEVWLMP HEVNM
Decryption using Key #9: KDUVKLO GDUML
Decryption using Key #10: JCTUJKN FCTLK
Decryption using Key #11: IBSTIJM EBSKJ
Decryption using Key #12: HARSHIL DARJI
Decryption using Key #13: GZQRGHK CZQIH
Decryption using Key #14: FYPQFGJ BYPHG
Decryption using Key #15: EXOPEFI AXOGF
Decryption using Key #16: DWNODEH ZWNFE
Decryption using Key #17: CVMNCDG YVMED
Decryption using Key #18: BULMBCF XULDC
Decryption using Key #19: ATKLABE WTKCB
Decryption using Key #20: ZSJKZAD VSJBA
Decryption using Key #21: YRIJYZC URIAZ
Decryption using Key #22: XQHIXYB TQHZY
Decryption using Key #23: WPGHWXA SPGYX
Decryption using Key #24: VOFGVWZ ROFXW
Decryption using Key #25: UNEFUVY QNEWV
"""
LETTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
for key in range(len(LETTERS)):
translated = ""
for symbol in message:
if symbol in LETTERS:
num = LETTERS.find(symbol)
num = num - key
if num < 0:
num = num + len(LETTERS)
translated = translated + LETTERS[num]
else:
translated = translated + symbol
print("Decryption using Key #%s: %s" % (key, translated))
def main():
message = input("Encrypted message: ")
message = message.upper()
decrypt(message)
if __name__ == '__main__':
import doctest
doctest.testmod()
main()
| [] | [] | [] |
archives/1098994933_python.zip | ciphers/caesar_cipher.py | def encrypt(strng, key):
encrypted = ''
for x in strng:
indx = (ord(x) + key) % 256
if indx > 126:
indx = indx - 95
encrypted = encrypted + chr(indx)
return encrypted
def decrypt(strng, key):
decrypted = ''
for x in strng:
indx = (ord(x) - key) % 256
if indx < 32:
indx = indx + 95
decrypted = decrypted + chr(indx)
return decrypted
def brute_force(strng):
key = 1
decrypted = ''
while key <= 94:
for x in strng:
indx = (ord(x) - key) % 256
if indx < 32:
indx = indx + 95
decrypted = decrypted + chr(indx)
print("Key: {}\t| Message: {}".format(key, decrypted))
decrypted = ''
key += 1
return None
def main():
while True:
print('-' * 10 + "\n**Menu**\n" + '-' * 10)
print("1.Encrpyt")
print("2.Decrypt")
print("3.BruteForce")
print("4.Quit")
choice = input("What would you like to do?: ")
if choice not in ['1', '2', '3', '4']:
print("Invalid choice, please enter a valid choice")
elif choice == '1':
strng = input("Please enter the string to be encrypted: ")
key = int(input("Please enter off-set between 1-94: "))
if key in range(1, 95):
print(encrypt(strng.lower(), key))
elif choice == '2':
strng = input("Please enter the string to be decrypted: ")
key = int(input("Please enter off-set between 1-94: "))
if key in range(1,95):
print(decrypt(strng, key))
elif choice == '3':
strng = input("Please enter the string to be decrypted: ")
brute_force(strng)
main()
elif choice == '4':
print("Goodbye.")
break
if __name__ == '__main__':
main()
| [] | [] | [] |
archives/1098994933_python.zip | ciphers/cryptomath_module.py | def gcd(a, b):
while a != 0:
a, b = b % a, a
return b
def findModInverse(a, m):
if gcd(a, m) != 1:
return None
u1, u2, u3 = 1, 0, a
v1, v2, v3 = 0, 1, m
while v3 != 0:
q = u3 // v3
v1, v2, v3, u1, u2, u3 = (u1 - q * v1), (u2 - q * v2), (u3 - q *v3), v1, v2, v3
return u1 % m
| [] | [] | [] |
archives/1098994933_python.zip | ciphers/elgamal_key_generator.py | import os
import random
import sys
import rabin_miller as rabinMiller, cryptomath_module as cryptoMath
min_primitive_root = 3
def main():
print('Making key files...')
makeKeyFiles('elgamal', 2048)
print('Key files generation successful')
# I have written my code naively same as definition of primitive root
# however every time I run this program, memory exceeded...
# so I used 4.80 Algorithm in Handbook of Applied Cryptography(CRC Press, ISBN : 0-8493-8523-7, October 1996)
# and it seems to run nicely!
def primitiveRoot(p_val):
print("Generating primitive root of p")
while True:
g = random.randrange(3,p_val)
if pow(g, 2, p_val) == 1:
continue
if pow(g, p_val, p_val) == 1:
continue
return g
def generateKey(keySize):
print('Generating prime p...')
p = rabinMiller.generateLargePrime(keySize) # select large prime number.
e_1 = primitiveRoot(p) # one primitive root on modulo p.
d = random.randrange(3, p) # private_key -> have to be greater than 2 for safety.
e_2 = cryptoMath.findModInverse(pow(e_1, d, p), p)
publicKey = (keySize, e_1, e_2, p)
privateKey = (keySize, d)
return publicKey, privateKey
def makeKeyFiles(name, keySize):
if os.path.exists('%s_pubkey.txt' % name) or os.path.exists('%s_privkey.txt' % name):
print('\nWARNING:')
print('"%s_pubkey.txt" or "%s_privkey.txt" already exists. \n'
'Use a different name or delete these files and re-run this program.' %
(name, name))
sys.exit()
publicKey, privateKey = generateKey(keySize)
print('\nWriting public key to file %s_pubkey.txt...' % name)
with open('%s_pubkey.txt' % name, 'w') as fo:
fo.write('%d,%d,%d,%d' % (publicKey[0], publicKey[1], publicKey[2], publicKey[3]))
print('Writing private key to file %s_privkey.txt...' % name)
with open('%s_privkey.txt' % name, 'w') as fo:
fo.write('%d,%d' % (privateKey[0], privateKey[1]))
if __name__ == '__main__':
main()
| [] | [] | [] |
archives/1098994933_python.zip | ciphers/hill_cipher.py | """
Hill Cipher:
The below defined class 'HillCipher' implements the Hill Cipher algorithm.
The Hill Cipher is an algorithm that implements modern linear algebra techniques
In this algortihm, you have an encryption key matrix. This is what will be used
in encoding and decoding your text.
Algortihm:
Let the order of the encryption key be N (as it is a square matrix).
Your text is divided into batches of length N and converted to numerical vectors
by a simple mapping starting with A=0 and so on.
The key is then mulitplied with the newly created batch vector to obtain the
encoded vector. After each multiplication modular 36 calculations are performed
on the vectors so as to bring the numbers between 0 and 36 and then mapped with
their corresponding alphanumerics.
While decrypting, the decrypting key is found which is the inverse of the
encrypting key modular 36. The same process is repeated for decrypting to get
the original message back.
Constraints:
The determinant of the encryption key matrix must be relatively prime w.r.t 36.
Note:
The algorithm implemented in this code considers only alphanumerics in the text.
If the length of the text to be encrypted is not a multiple of the
break key(the length of one batch of letters),the last character of the text
is added to the text until the length of the text reaches a multiple of
the break_key. So the text after decrypting might be a little different than
the original text.
References:
https://apprendre-en-ligne.net/crypto/hill/Hillciph.pdf
https://www.youtube.com/watch?v=kfmNeskzs2o
https://www.youtube.com/watch?v=4RhLNDqcjpA
"""
import numpy
def gcd(a, b):
if a == 0:
return b
return gcd(b%a, a)
class HillCipher:
key_string = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
# This cipher takes alphanumerics into account
# i.e. a total of 36 characters
replaceLetters = lambda self, letter: self.key_string.index(letter)
replaceNumbers = lambda self, num: self.key_string[round(num)]
# take x and return x % len(key_string)
modulus = numpy.vectorize(lambda x: x % 36)
toInt = numpy.vectorize(lambda x: round(x))
def __init__(self, encrypt_key):
"""
encrypt_key is an NxN numpy matrix
"""
self.encrypt_key = self.modulus(encrypt_key) # mod36 calc's on the encrypt key
self.checkDeterminant() # validate the determinant of the encryption key
self.decrypt_key = None
self.break_key = encrypt_key.shape[0]
def checkDeterminant(self):
det = round(numpy.linalg.det(self.encrypt_key))
if det < 0:
det = det % len(self.key_string)
req_l = len(self.key_string)
if gcd(det, len(self.key_string)) != 1:
raise ValueError("discriminant modular {0} of encryption key({1}) is not co prime w.r.t {2}.\nTry another key.".format(req_l, det, req_l))
def processText(self, text):
text = list(text.upper())
text = [char for char in text if char in self.key_string]
last = text[-1]
while len(text) % self.break_key != 0:
text.append(last)
return ''.join(text)
def encrypt(self, text):
text = self.processText(text.upper())
encrypted = ''
for i in range(0, len(text) - self.break_key + 1, self.break_key):
batch = text[i:i+self.break_key]
batch_vec = list(map(self.replaceLetters, batch))
batch_vec = numpy.matrix([batch_vec]).T
batch_encrypted = self.modulus(self.encrypt_key.dot(batch_vec)).T.tolist()[0]
encrypted_batch = ''.join(list(map(self.replaceNumbers, batch_encrypted)))
encrypted += encrypted_batch
return encrypted
def makeDecryptKey(self):
det = round(numpy.linalg.det(self.encrypt_key))
if det < 0:
det = det % len(self.key_string)
det_inv = None
for i in range(len(self.key_string)):
if (det * i) % len(self.key_string) == 1:
det_inv = i
break
inv_key = det_inv * numpy.linalg.det(self.encrypt_key) *\
numpy.linalg.inv(self.encrypt_key)
return self.toInt(self.modulus(inv_key))
def decrypt(self, text):
self.decrypt_key = self.makeDecryptKey()
text = self.processText(text.upper())
decrypted = ''
for i in range(0, len(text) - self.break_key + 1, self.break_key):
batch = text[i:i+self.break_key]
batch_vec = list(map(self.replaceLetters, batch))
batch_vec = numpy.matrix([batch_vec]).T
batch_decrypted = self.modulus(self.decrypt_key.dot(batch_vec)).T.tolist()[0]
decrypted_batch = ''.join(list(map(self.replaceNumbers, batch_decrypted)))
decrypted += decrypted_batch
return decrypted
def main():
N = int(input("Enter the order of the encryption key: "))
hill_matrix = []
print("Enter each row of the encryption key with space separated integers")
for i in range(N):
row = list(map(int, input().split()))
hill_matrix.append(row)
hc = HillCipher(numpy.matrix(hill_matrix))
print("Would you like to encrypt or decrypt some text? (1 or 2)")
option = input("""
1. Encrypt
2. Decrypt
"""
)
if option == '1':
text_e = input("What text would you like to encrypt?: ")
print("Your encrypted text is:")
print(hc.encrypt(text_e))
elif option == '2':
text_d = input("What text would you like to decrypt?: ")
print("Your decrypted text is:")
print(hc.decrypt(text_d))
if __name__ == "__main__":
main()
| [] | [] | [] |
archives/1098994933_python.zip | ciphers/morse_code_implementation.py | # Python program to implement Morse Code Translator
# Dictionary representing the morse code chart
MORSE_CODE_DICT = { 'A':'.-', 'B':'-...',
'C':'-.-.', 'D':'-..', 'E':'.',
'F':'..-.', 'G':'--.', 'H':'....',
'I':'..', 'J':'.---', 'K':'-.-',
'L':'.-..', 'M':'--', 'N':'-.',
'O':'---', 'P':'.--.', 'Q':'--.-',
'R':'.-.', 'S':'...', 'T':'-',
'U':'..-', 'V':'...-', 'W':'.--',
'X':'-..-', 'Y':'-.--', 'Z':'--..',
'1':'.----', '2':'..---', '3':'...--',
'4':'....-', '5':'.....', '6':'-....',
'7':'--...', '8':'---..', '9':'----.',
'0':'-----', ', ':'--..--', '.':'.-.-.-',
'?':'..--..', '/':'-..-.', '-':'-....-',
'(':'-.--.', ')':'-.--.-'}
def encrypt(message):
cipher = ''
for letter in message:
if letter != ' ':
cipher += MORSE_CODE_DICT[letter] + ' '
else:
cipher += ' '
return cipher
def decrypt(message):
message += ' '
decipher = ''
citext = ''
for letter in message:
if (letter != ' '):
i = 0
citext += letter
else:
i += 1
if i == 2 :
decipher += ' '
else:
decipher += list(MORSE_CODE_DICT.keys())[list(MORSE_CODE_DICT
.values()).index(citext)]
citext = ''
return decipher
def main():
message = "Morse code here"
result = encrypt(message.upper())
print(result)
message = result
result = decrypt(message)
print(result)
if __name__ == '__main__':
main()
| [] | [] | [] |
archives/1098994933_python.zip | ciphers/onepad_cipher.py | import random
class Onepad:
def encrypt(self, text):
'''Function to encrypt text using psedo-random numbers'''
plain = [ord(i) for i in text]
key = []
cipher = []
for i in plain:
k = random.randint(1, 300)
c = (i+k)*k
cipher.append(c)
key.append(k)
return cipher, key
def decrypt(self, cipher, key):
'''Function to decrypt text using psedo-random numbers.'''
plain = []
for i in range(len(key)):
p = int((cipher[i]-(key[i])**2)/key[i])
plain.append(chr(p))
plain = ''.join([i for i in plain])
return plain
if __name__ == '__main__':
c, k = Onepad().encrypt('Hello')
print(c, k)
print(Onepad().decrypt(c, k))
| [] | [] | [] |
archives/1098994933_python.zip | ciphers/playfair_cipher.py | import string
import itertools
def chunker(seq, size):
it = iter(seq)
while True:
chunk = tuple(itertools.islice(it, size))
if not chunk:
return
yield chunk
def prepare_input(dirty):
"""
Prepare the plaintext by up-casing it
and separating repeated letters with X's
"""
dirty = ''.join([c.upper() for c in dirty if c in string.ascii_letters])
clean = ""
if len(dirty) < 2:
return dirty
for i in range(len(dirty)-1):
clean += dirty[i]
if dirty[i] == dirty[i+1]:
clean += 'X'
clean += dirty[-1]
if len(clean) & 1:
clean += 'X'
return clean
def generate_table(key):
# I and J are used interchangeably to allow
# us to use a 5x5 table (25 letters)
alphabet = "ABCDEFGHIKLMNOPQRSTUVWXYZ"
# we're using a list instead of a '2d' array because it makes the math
# for setting up the table and doing the actual encoding/decoding simpler
table = []
# copy key chars into the table if they are in `alphabet` ignoring duplicates
for char in key.upper():
if char not in table and char in alphabet:
table.append(char)
# fill the rest of the table in with the remaining alphabet chars
for char in alphabet:
if char not in table:
table.append(char)
return table
def encode(plaintext, key):
table = generate_table(key)
plaintext = prepare_input(plaintext)
ciphertext = ""
# https://en.wikipedia.org/wiki/Playfair_cipher#Description
for char1, char2 in chunker(plaintext, 2):
row1, col1 = divmod(table.index(char1), 5)
row2, col2 = divmod(table.index(char2), 5)
if row1 == row2:
ciphertext += table[row1*5+(col1+1)%5]
ciphertext += table[row2*5+(col2+1)%5]
elif col1 == col2:
ciphertext += table[((row1+1)%5)*5+col1]
ciphertext += table[((row2+1)%5)*5+col2]
else: # rectangle
ciphertext += table[row1*5+col2]
ciphertext += table[row2*5+col1]
return ciphertext
def decode(ciphertext, key):
table = generate_table(key)
plaintext = ""
# https://en.wikipedia.org/wiki/Playfair_cipher#Description
for char1, char2 in chunker(ciphertext, 2):
row1, col1 = divmod(table.index(char1), 5)
row2, col2 = divmod(table.index(char2), 5)
if row1 == row2:
plaintext += table[row1*5+(col1-1)%5]
plaintext += table[row2*5+(col2-1)%5]
elif col1 == col2:
plaintext += table[((row1-1)%5)*5+col1]
plaintext += table[((row2-1)%5)*5+col2]
else: # rectangle
plaintext += table[row1*5+col2]
plaintext += table[row2*5+col1]
return plaintext
| [] | [] | [] |
archives/1098994933_python.zip | ciphers/rabin_miller.py | # Primality Testing with the Rabin-Miller Algorithm
import random
def rabinMiller(num):
s = num - 1
t = 0
while s % 2 == 0:
s = s // 2
t += 1
for trials in range(5):
a = random.randrange(2, num - 1)
v = pow(a, s, num)
if v != 1:
i = 0
while v != (num - 1):
if i == t - 1:
return False
else:
i = i + 1
v = (v ** 2) % num
return True
def isPrime(num):
if (num < 2):
return False
lowPrimes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59,
61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127,
131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191,
193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257,
263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331,
337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401,
409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467,
479, 487, 491, 499, 503, 509, 521, 523, 541, 547, 557, 563,
569, 571, 577, 587, 593, 599, 601, 607, 613, 617, 619, 631,
641, 643, 647, 653, 659, 661, 673, 677, 683, 691, 701, 709,
719, 727, 733, 739, 743, 751, 757, 761, 769, 773, 787, 797,
809, 811, 821, 823, 827, 829, 839, 853, 857, 859, 863, 877,
881, 883, 887, 907, 911, 919, 929, 937, 941, 947, 953, 967,
971, 977, 983, 991, 997]
if num in lowPrimes:
return True
for prime in lowPrimes:
if (num % prime) == 0:
return False
return rabinMiller(num)
def generateLargePrime(keysize = 1024):
while True:
num = random.randrange(2 ** (keysize - 1), 2 ** (keysize))
if isPrime(num):
return num
if __name__ == '__main__':
num = generateLargePrime()
print(('Prime number:', num))
print(('isPrime:', isPrime(num)))
| [] | [] | [] |
archives/1098994933_python.zip | ciphers/rot13.py | def dencrypt(s, n):
out = ''
for c in s:
if c >= 'A' and c <= 'Z':
out += chr(ord('A') + (ord(c) - ord('A') + n) % 26)
elif c >= 'a' and c <= 'z':
out += chr(ord('a') + (ord(c) - ord('a') + n) % 26)
else:
out += c
return out
def main():
s0 = 'HELLO'
s1 = dencrypt(s0, 13)
print(s1) # URYYB
s2 = dencrypt(s1, 13)
print(s2) # HELLO
if __name__ == '__main__':
main()
| [] | [] | [] |
archives/1098994933_python.zip | ciphers/rsa_cipher.py | import sys, rsa_key_generator as rkg, os
DEFAULT_BLOCK_SIZE = 128
BYTE_SIZE = 256
def main():
filename = 'encrypted_file.txt'
response = input(r'Encrypte\Decrypt [e\d]: ')
if response.lower().startswith('e'):
mode = 'encrypt'
elif response.lower().startswith('d'):
mode = 'decrypt'
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))
encryptedText = encryptAndWriteToFile(filename, pubKeyFilename, message)
print('\nEncrypted text:')
print(encryptedText)
elif mode == 'decrypt':
privKeyFilename = 'rsa_privkey.txt'
print('Reading from %s and decrypting...' % (filename))
decryptedText = readFromFileAndDecrypt(filename, privKeyFilename)
print('writing decryption to rsa_decryption.txt...')
with open('rsa_decryption.txt', 'w') as dec:
dec.write(decryptedText)
print('\nDecryption:')
print(decryptedText)
def getBlocksFromText(message, blockSize=DEFAULT_BLOCK_SIZE):
messageBytes = message.encode('ascii')
blockInts = []
for blockStart in range(0, len(messageBytes), blockSize):
blockInt = 0
for i in range(blockStart, min(blockStart + blockSize, len(messageBytes))):
blockInt += messageBytes[i] * (BYTE_SIZE ** (i % blockSize))
blockInts.append(blockInt)
return blockInts
def getTextFromBlocks(blockInts, messageLength, blockSize=DEFAULT_BLOCK_SIZE):
message = []
for blockInt in blockInts:
blockMessage = []
for i in range(blockSize - 1, -1, -1):
if len(message) + i < messageLength:
asciiNumber = blockInt // (BYTE_SIZE ** i)
blockInt = blockInt % (BYTE_SIZE ** i)
blockMessage.insert(0, chr(asciiNumber))
message.extend(blockMessage)
return ''.join(message)
def encryptMessage(message, key, blockSize=DEFAULT_BLOCK_SIZE):
encryptedBlocks = []
n, e = key
for block in getBlocksFromText(message, blockSize):
encryptedBlocks.append(pow(block, e, n))
return encryptedBlocks
def decryptMessage(encryptedBlocks, messageLength, key, blockSize=DEFAULT_BLOCK_SIZE):
decryptedBlocks = []
n, d = key
for block in encryptedBlocks:
decryptedBlocks.append(pow(block, d, n))
return getTextFromBlocks(decryptedBlocks, messageLength, blockSize)
def readKeyFile(keyFilename):
with open(keyFilename) as fo:
content = fo.read()
keySize, n, EorD = content.split(',')
return (int(keySize), int(n), int(EorD))
def encryptAndWriteToFile(messageFilename, keyFilename, message, blockSize=DEFAULT_BLOCK_SIZE):
keySize, n, e = readKeyFile(keyFilename)
if keySize < blockSize * 8:
sys.exit('ERROR: Block size is %s bits and key size is %s bits. The RSA cipher requires the block size to be equal to or greater than the key size. Either decrease the block size or use different keys.' % (blockSize * 8, keySize))
encryptedBlocks = encryptMessage(message, (n, e), blockSize)
for i in range(len(encryptedBlocks)):
encryptedBlocks[i] = str(encryptedBlocks[i])
encryptedContent = ','.join(encryptedBlocks)
encryptedContent = '%s_%s_%s' % (len(message), blockSize, encryptedContent)
with open(messageFilename, 'w') as fo:
fo.write(encryptedContent)
return encryptedContent
def readFromFileAndDecrypt(messageFilename, keyFilename):
keySize, n, d = readKeyFile(keyFilename)
with open(messageFilename) as fo:
content = fo.read()
messageLength, blockSize, encryptedMessage = content.split('_')
messageLength = int(messageLength)
blockSize = int(blockSize)
if keySize < blockSize * 8:
sys.exit('ERROR: Block size is %s bits and key size is %s bits. The RSA cipher requires the block size to be equal to or greater than the key size. Did you specify the correct key file and encrypted file?' % (blockSize * 8, keySize))
encryptedBlocks = []
for block in encryptedMessage.split(','):
encryptedBlocks.append(int(block))
return decryptMessage(encryptedBlocks, messageLength, (n, d), blockSize)
if __name__ == '__main__':
main()
| [] | [] | [] |
archives/1098994933_python.zip | ciphers/rsa_key_generator.py | import random, sys, os
import rabin_miller as rabinMiller, cryptomath_module as cryptoMath
def main():
print('Making key files...')
makeKeyFiles('rsa', 1024)
print('Key files generation successful.')
def generateKey(keySize):
print('Generating prime p...')
p = rabinMiller.generateLargePrime(keySize)
print('Generating prime q...')
q = rabinMiller.generateLargePrime(keySize)
n = p * q
print('Generating e that is relatively prime to (p - 1) * (q - 1)...')
while True:
e = random.randrange(2 ** (keySize - 1), 2 ** (keySize))
if cryptoMath.gcd(e, (p - 1) * (q - 1)) == 1:
break
print('Calculating d that is mod inverse of e...')
d = cryptoMath.findModInverse(e, (p - 1) * (q - 1))
publicKey = (n, e)
privateKey = (n, d)
return (publicKey, privateKey)
def makeKeyFiles(name, keySize):
if os.path.exists('%s_pubkey.txt' % (name)) or os.path.exists('%s_privkey.txt' % (name)):
print('\nWARNING:')
print('"%s_pubkey.txt" or "%s_privkey.txt" already exists. \nUse a different name or delete these files and re-run this program.' % (name, name))
sys.exit()
publicKey, privateKey = generateKey(keySize)
print('\nWriting public key to file %s_pubkey.txt...' % name)
with open('%s_pubkey.txt' % name, 'w') as fo:
fo.write('%s,%s,%s' % (keySize, publicKey[0], publicKey[1]))
print('Writing private key to file %s_privkey.txt...' % name)
with open('%s_privkey.txt' % name, 'w') as fo:
fo.write('%s,%s,%s' % (keySize, privateKey[0], privateKey[1]))
if __name__ == '__main__':
main()
| [] | [] | [] |
archives/1098994933_python.zip | ciphers/simple_substitution_cipher.py | import sys, random
LETTERS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
def main():
message = input('Enter message: ')
key = 'LFWOAYUISVKMNXPBDCRJTQEGHZ'
resp = input('Encrypt/Decrypt [e/d]: ')
checkValidKey(key)
if resp.lower().startswith('e'):
mode = 'encrypt'
translated = encryptMessage(key, message)
elif resp.lower().startswith('d'):
mode = 'decrypt'
translated = decryptMessage(key, message)
print('\n%sion: \n%s' % (mode.title(), translated))
def checkValidKey(key):
keyList = list(key)
lettersList = list(LETTERS)
keyList.sort()
lettersList.sort()
if keyList != lettersList:
sys.exit('Error in the key or symbol set.')
def encryptMessage(key, message):
"""
>>> encryptMessage('LFWOAYUISVKMNXPBDCRJTQEGHZ', 'Harshil Darji')
'Ilcrism Olcvs'
"""
return translateMessage(key, message, 'encrypt')
def decryptMessage(key, message):
"""
>>> decryptMessage('LFWOAYUISVKMNXPBDCRJTQEGHZ', 'Ilcrism Olcvs')
'Harshil Darji'
"""
return translateMessage(key, message, 'decrypt')
def translateMessage(key, message, mode):
translated = ''
charsA = LETTERS
charsB = key
if mode == 'decrypt':
charsA, charsB = charsB, charsA
for symbol in message:
if symbol.upper() in charsA:
symIndex = charsA.find(symbol.upper())
if symbol.isupper():
translated += charsB[symIndex].upper()
else:
translated += charsB[symIndex].lower()
else:
translated += symbol
return translated
def getRandomKey():
key = list(LETTERS)
random.shuffle(key)
return ''.join(key)
if __name__ == '__main__':
main()
| [] | [] | [] |
archives/1098994933_python.zip | ciphers/trafid_cipher.py | #https://en.wikipedia.org/wiki/Trifid_cipher
def __encryptPart(messagePart, character2Number):
one, two, three = "", "", ""
tmp = []
for character in messagePart:
tmp.append(character2Number[character])
for each in tmp:
one += each[0]
two += each[1]
three += each[2]
return one+two+three
def __decryptPart(messagePart, character2Number):
tmp, thisPart = "", ""
result = []
for character in messagePart:
thisPart += character2Number[character]
for digit in thisPart:
tmp += digit
if len(tmp) == len(messagePart):
result.append(tmp)
tmp = ""
return result[0], result[1], result[2]
def __prepare(message, alphabet):
#Validate message and alphabet, set to upper and remove spaces
alphabet = alphabet.replace(" ", "").upper()
message = message.replace(" ", "").upper()
#Check length and characters
if len(alphabet) != 27:
raise KeyError("Length of alphabet has to be 27.")
for each in message:
if each not in alphabet:
raise ValueError("Each message character has to be included in alphabet!")
#Generate dictionares
numbers = ("111","112","113","121","122","123","131","132","133","211","212","213","221","222","223","231","232","233","311","312","313","321","322","323","331","332","333")
character2Number = {}
number2Character = {}
for letter, number in zip(alphabet, numbers):
character2Number[letter] = number
number2Character[number] = letter
return message, alphabet, character2Number, number2Character
def encryptMessage(message, alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ.", period=5):
message, alphabet, character2Number, number2Character = __prepare(message, alphabet)
encrypted, encrypted_numeric = "", ""
for i in range(0, len(message)+1, period):
encrypted_numeric += __encryptPart(message[i:i+period], character2Number)
for i in range(0, len(encrypted_numeric), 3):
encrypted += number2Character[encrypted_numeric[i:i+3]]
return encrypted
def decryptMessage(message, alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ.", period=5):
message, alphabet, character2Number, number2Character = __prepare(message, alphabet)
decrypted_numeric = []
decrypted = ""
for i in range(0, len(message)+1, period):
a,b,c = __decryptPart(message[i:i+period], character2Number)
for j in range(0, len(a)):
decrypted_numeric.append(a[j]+b[j]+c[j])
for each in decrypted_numeric:
decrypted += number2Character[each]
return decrypted
if __name__ == '__main__':
msg = "DEFEND THE EAST WALL OF THE CASTLE."
encrypted = encryptMessage(msg,"EPSDUCVWYM.ZLKXNBTFGORIJHAQ")
decrypted = decryptMessage(encrypted, "EPSDUCVWYM.ZLKXNBTFGORIJHAQ")
print("Encrypted: {}\nDecrypted: {}".format(encrypted, decrypted))
| [] | [] | [] |
archives/1098994933_python.zip | ciphers/transposition_cipher.py | import math
def main():
message = input('Enter message: ')
key = int(input('Enter key [2-%s]: ' % (len(message) - 1)))
mode = input('Encryption/Decryption [e/d]: ')
if mode.lower().startswith('e'):
text = encryptMessage(key, message)
elif mode.lower().startswith('d'):
text = decryptMessage(key, message)
# Append pipe symbol (vertical bar) to identify spaces at the end.
print('Output:\n%s' %(text + '|'))
def encryptMessage(key, message):
"""
>>> encryptMessage(6, 'Harshil Darji')
'Hlia rDsahrij'
"""
cipherText = [''] * key
for col in range(key):
pointer = col
while pointer < len(message):
cipherText[col] += message[pointer]
pointer += key
return ''.join(cipherText)
def decryptMessage(key, message):
"""
>>> decryptMessage(6, 'Hlia rDsahrij')
'Harshil Darji'
"""
numCols = math.ceil(len(message) / key)
numRows = key
numShadedBoxes = (numCols * numRows) - len(message)
plainText = [""] * numCols
col = 0; row = 0;
for symbol in message:
plainText[col] += symbol
col += 1
if (col == numCols) or (col == numCols - 1) and (row >= numRows - numShadedBoxes):
col = 0
row += 1
return "".join(plainText)
if __name__ == '__main__':
import doctest
doctest.testmod()
main()
| [] | [] | [] |
archives/1098994933_python.zip | ciphers/transposition_cipher_encrypt_decrypt_file.py | import time, os, sys
import transposition_cipher as transCipher
def main():
inputFile = 'Prehistoric Men.txt'
outputFile = 'Output.txt'
key = int(input('Enter key: '))
mode = input('Encrypt/Decrypt [e/d]: ')
if not os.path.exists(inputFile):
print('File %s does not exist. Quitting...' % inputFile)
sys.exit()
if os.path.exists(outputFile):
print('Overwrite %s? [y/n]' % outputFile)
response = input('> ')
if not response.lower().startswith('y'):
sys.exit()
startTime = time.time()
if mode.lower().startswith('e'):
with open(inputFile) as f:
content = f.read()
translated = transCipher.encryptMessage(key, content)
elif mode.lower().startswith('d'):
with open(outputFile) as f:
content = f.read()
translated =transCipher .decryptMessage(key, content)
with open(outputFile, 'w') as outputObj:
outputObj.write(translated)
totalTime = round(time.time() - startTime, 2)
print(('Done (', totalTime, 'seconds )'))
if __name__ == '__main__':
main()
| [] | [] | [] |
archives/1098994933_python.zip | ciphers/vigenere_cipher.py | LETTERS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
def main():
message = input('Enter message: ')
key = input('Enter key [alphanumeric]: ')
mode = input('Encrypt/Decrypt [e/d]: ')
if mode.lower().startswith('e'):
mode = 'encrypt'
translated = encryptMessage(key, message)
elif mode.lower().startswith('d'):
mode = 'decrypt'
translated = decryptMessage(key, message)
print('\n%sed message:' % mode.title())
print(translated)
def encryptMessage(key, message):
'''
>>> encryptMessage('HDarji', 'This is Harshil Darji from Dharmaj.')
'Akij ra Odrjqqs Gaisq muod Mphumrs.'
'''
return translateMessage(key, message, 'encrypt')
def decryptMessage(key, message):
'''
>>> decryptMessage('HDarji', 'Akij ra Odrjqqs Gaisq muod Mphumrs.')
'This is Harshil Darji from Dharmaj.'
'''
return translateMessage(key, message, 'decrypt')
def translateMessage(key, message, mode):
translated = []
keyIndex = 0
key = key.upper()
for symbol in message:
num = LETTERS.find(symbol.upper())
if num != -1:
if mode == 'encrypt':
num += LETTERS.find(key[keyIndex])
elif mode == 'decrypt':
num -= LETTERS.find(key[keyIndex])
num %= len(LETTERS)
if symbol.isupper():
translated.append(LETTERS[num])
elif symbol.islower():
translated.append(LETTERS[num].lower())
keyIndex += 1
if keyIndex == len(key):
keyIndex = 0
else:
translated.append(symbol)
return ''.join(translated)
if __name__ == '__main__':
main()
| [] | [] | [] |
archives/1098994933_python.zip | ciphers/xor_cipher.py | """
author: Christian Bender
date: 21.12.2017
class: XORCipher
This class implements the XOR-cipher algorithm and provides
some useful methods for encrypting and decrypting strings and
files.
Overview about methods
- encrypt : list of char
- decrypt : list of char
- encrypt_string : str
- decrypt_string : str
- encrypt_file : boolean
- decrypt_file : boolean
"""
class XORCipher(object):
def __init__(self, key = 0):
"""
simple constructor that receives a key or uses
default key = 0
"""
#private field
self.__key = key
def encrypt(self, content, key):
"""
input: 'content' of type string and 'key' of type int
output: encrypted string 'content' as a list of chars
if key not passed the method uses the key by the constructor.
otherwise key = 1
"""
# precondition
assert (isinstance(key,int) and isinstance(content,str))
key = key or self.__key or 1
# make sure key can be any size
while (key > 255):
key -= 255
# This will be returned
ans = []
for ch in content:
ans.append(chr(ord(ch) ^ key))
return ans
def decrypt(self,content,key):
"""
input: 'content' of type list and 'key' of type int
output: decrypted string 'content' as a list of chars
if key not passed the method uses the key by the constructor.
otherwise key = 1
"""
# precondition
assert (isinstance(key,int) and isinstance(content,list))
key = key or self.__key or 1
# make sure key can be any size
while (key > 255):
key -= 255
# This will be returned
ans = []
for ch in content:
ans.append(chr(ord(ch) ^ key))
return ans
def encrypt_string(self,content, key = 0):
"""
input: 'content' of type string and 'key' of type int
output: encrypted string 'content'
if key not passed the method uses the key by the constructor.
otherwise key = 1
"""
# precondition
assert (isinstance(key,int) and isinstance(content,str))
key = key or self.__key or 1
# make sure key can be any size
while (key > 255):
key -= 255
# This will be returned
ans = ""
for ch in content:
ans += chr(ord(ch) ^ key)
return ans
def decrypt_string(self,content,key = 0):
"""
input: 'content' of type string and 'key' of type int
output: decrypted string 'content'
if key not passed the method uses the key by the constructor.
otherwise key = 1
"""
# precondition
assert (isinstance(key,int) and isinstance(content,str))
key = key or self.__key or 1
# make sure key can be any size
while (key > 255):
key -= 255
# This will be returned
ans = ""
for ch in content:
ans += chr(ord(ch) ^ key)
return ans
def encrypt_file(self, file, key = 0):
"""
input: filename (str) and a key (int)
output: returns true if encrypt process was
successful otherwise false
if key not passed the method uses the key by the constructor.
otherwise key = 1
"""
#precondition
assert (isinstance(file,str) and isinstance(key,int))
try:
with open(file,"r") as fin:
with open("encrypt.out","w+") as fout:
# actual encrypt-process
for line in fin:
fout.write(self.encrypt_string(line,key))
except:
return False
return True
def decrypt_file(self,file, key):
"""
input: filename (str) and a key (int)
output: returns true if decrypt process was
successful otherwise false
if key not passed the method uses the key by the constructor.
otherwise key = 1
"""
#precondition
assert (isinstance(file,str) and isinstance(key,int))
try:
with open(file,"r") as fin:
with open("decrypt.out","w+") as fout:
# actual encrypt-process
for line in fin:
fout.write(self.decrypt_string(line,key))
except:
return False
return True
# Tests
# crypt = XORCipher()
# key = 67
# # test enrcypt
# print(crypt.encrypt("hallo welt",key))
# # test decrypt
# print(crypt.decrypt(crypt.encrypt("hallo welt",key), key))
# # test encrypt_string
# print(crypt.encrypt_string("hallo welt",key))
# # test decrypt_string
# print(crypt.decrypt_string(crypt.encrypt_string("hallo welt",key),key))
# if (crypt.encrypt_file("test.txt",key)):
# print("encrypt successful")
# else:
# print("encrypt unsuccessful")
# if (crypt.decrypt_file("encrypt.out",key)):
# print("decrypt successful")
# else:
# print("decrypt unsuccessful")
| [] | [] | [] |
archives/1098994933_python.zip | compression/burrows_wheeler.py | """
https://en.wikipedia.org/wiki/Burrows%E2%80%93Wheeler_transform
The Burrows–Wheeler transform (BWT, also called block-sorting compression)
rearranges a character string into runs of similar characters. This is useful
for compression, since it tends to be easy to compress a string that has runs
of repeated characters by techniques such as move-to-front transform and
run-length encoding. More importantly, the transformation is reversible,
without needing to store any additional data except the position of the first
original character. The BWT is thus a "free" method of improving the efficiency
of text compression algorithms, costing only some extra computation.
"""
from typing import List, Dict
def all_rotations(s: str) -> List[str]:
"""
:param s: The string that will be rotated len(s) times.
:return: A list with the rotations.
:raises TypeError: If s is not an instance of str.
Examples:
>>> all_rotations("^BANANA|") # doctest: +NORMALIZE_WHITESPACE
['^BANANA|', 'BANANA|^', 'ANANA|^B', 'NANA|^BA', 'ANA|^BAN', 'NA|^BANA',
'A|^BANAN', '|^BANANA']
>>> all_rotations("a_asa_da_casa") # doctest: +NORMALIZE_WHITESPACE
['a_asa_da_casa', '_asa_da_casaa', 'asa_da_casaa_', 'sa_da_casaa_a',
'a_da_casaa_as', '_da_casaa_asa', 'da_casaa_asa_', 'a_casaa_asa_d',
'_casaa_asa_da', 'casaa_asa_da_', 'asaa_asa_da_c', 'saa_asa_da_ca',
'aa_asa_da_cas']
>>> all_rotations("panamabanana") # doctest: +NORMALIZE_WHITESPACE
['panamabanana', 'anamabananap', 'namabananapa', 'amabananapan',
'mabananapana', 'abananapanam', 'bananapanama', 'ananapanamab',
'nanapanamaba', 'anapanamaban', 'napanamabana', 'apanamabanan']
>>> all_rotations(5)
Traceback (most recent call last):
...
TypeError: The parameter s type must be str.
"""
if not isinstance(s, str):
raise TypeError("The parameter s type must be str.")
return [s[i:] + s[:i] for i in range(len(s))]
def bwt_transform(s: str) -> Dict:
"""
:param s: The string that will be used at bwt algorithm
:return: the string composed of the last char of each row of the ordered
rotations and the index of the original string at ordered rotations list
:raises TypeError: If the s parameter type is not str
:raises ValueError: If the s parameter is empty
Examples:
>>> bwt_transform("^BANANA")
{'bwt_string': 'BNN^AAA', 'idx_original_string': 6}
>>> bwt_transform("a_asa_da_casa")
{'bwt_string': 'aaaadss_c__aa', 'idx_original_string': 3}
>>> bwt_transform("panamabanana")
{'bwt_string': 'mnpbnnaaaaaa', 'idx_original_string': 11}
>>> bwt_transform(4)
Traceback (most recent call last):
...
TypeError: The parameter s type must be str.
>>> bwt_transform('')
Traceback (most recent call last):
...
ValueError: The parameter s must not be empty.
"""
if not isinstance(s, str):
raise TypeError("The parameter s type must be str.")
if not s:
raise ValueError("The parameter s must not be empty.")
rotations = all_rotations(s)
rotations.sort() # sort the list of rotations in alphabetically order
# make a string composed of the last char of each rotation
return {
"bwt_string": "".join([word[-1] for word in rotations]),
"idx_original_string": rotations.index(s),
}
def reverse_bwt(bwt_string: str, idx_original_string: int) -> str:
"""
:param bwt_string: The string returned from bwt algorithm execution
:param idx_original_string: A 0-based index of the string that was used to
generate bwt_string at ordered rotations list
:return: The string used to generate bwt_string when bwt was executed
:raises TypeError: If the bwt_string parameter type is not str
:raises ValueError: If the bwt_string parameter is empty
:raises TypeError: If the idx_original_string type is not int or if not
possible to cast it to int
:raises ValueError: If the idx_original_string value is lower than 0 or
greater than len(bwt_string) - 1
>>> reverse_bwt("BNN^AAA", 6)
'^BANANA'
>>> reverse_bwt("aaaadss_c__aa", 3)
'a_asa_da_casa'
>>> reverse_bwt("mnpbnnaaaaaa", 11)
'panamabanana'
>>> reverse_bwt(4, 11)
Traceback (most recent call last):
...
TypeError: The parameter bwt_string type must be str.
>>> reverse_bwt("", 11)
Traceback (most recent call last):
...
ValueError: The parameter bwt_string must not be empty.
>>> reverse_bwt("mnpbnnaaaaaa", "asd") # doctest: +NORMALIZE_WHITESPACE
Traceback (most recent call last):
...
TypeError: The parameter idx_original_string type must be int or passive
of cast to int.
>>> reverse_bwt("mnpbnnaaaaaa", -1)
Traceback (most recent call last):
...
ValueError: The parameter idx_original_string must not be lower than 0.
>>> reverse_bwt("mnpbnnaaaaaa", 12) # doctest: +NORMALIZE_WHITESPACE
Traceback (most recent call last):
...
ValueError: The parameter idx_original_string must be lower than
len(bwt_string).
>>> reverse_bwt("mnpbnnaaaaaa", 11.0)
'panamabanana'
>>> reverse_bwt("mnpbnnaaaaaa", 11.4)
'panamabanana'
"""
if not isinstance(bwt_string, str):
raise TypeError("The parameter bwt_string type must be str.")
if not bwt_string:
raise ValueError("The parameter bwt_string must not be empty.")
try:
idx_original_string = int(idx_original_string)
except ValueError:
raise TypeError(
(
"The parameter idx_original_string type must be int or passive"
" of cast to int."
)
)
if idx_original_string < 0:
raise ValueError(
"The parameter idx_original_string must not be lower than 0."
)
if idx_original_string >= len(bwt_string):
raise ValueError(
(
"The parameter idx_original_string must be lower than"
" len(bwt_string)."
)
)
ordered_rotations = [""] * len(bwt_string)
for x in range(len(bwt_string)):
for i in range(len(bwt_string)):
ordered_rotations[i] = bwt_string[i] + ordered_rotations[i]
ordered_rotations.sort()
return ordered_rotations[idx_original_string]
if __name__ == "__main__":
entry_msg = "Provide a string that I will generate its BWT transform: "
s = input(entry_msg).strip()
result = bwt_transform(s)
bwt_output_msg = "Burrows Wheeler tranform for string '{}' results in '{}'"
print(bwt_output_msg.format(s, result["bwt_string"]))
original_string = reverse_bwt(
result["bwt_string"], result["idx_original_string"]
)
fmt = (
"Reversing Burrows Wheeler tranform for entry '{}' we get original"
" string '{}'"
)
print(fmt.format(result["bwt_string"], original_string))
| [
"str",
"str",
"str",
"int"
] | [
732,
1986,
3404,
3430
] | [
735,
1989,
3407,
3433
] |
archives/1098994933_python.zip | compression/huffman.py | import sys
class Letter:
def __init__(self, letter, freq):
self.letter = letter
self.freq = freq
self.bitstring = ""
def __repr__(self):
return f'{self.letter}:{self.freq}'
class TreeNode:
def __init__(self, freq, left, right):
self.freq = freq
self.left = left
self.right = right
def parse_file(file_path):
"""
Read the file and build a dict of all letters and their
frequences, then convert the dict into a list of Letters.
"""
chars = {}
with open(file_path) as f:
while True:
c = f.read(1)
if not c:
break
chars[c] = chars[c] + 1 if c in chars.keys() else 1
return sorted([Letter(c, f) for c, f in chars.items()], key=lambda l: l.freq)
def build_tree(letters):
"""
Run through the list of Letters and build the min heap
for the Huffman Tree.
"""
while len(letters) > 1:
left = letters.pop(0)
right = letters.pop(0)
total_freq = left.freq + right.freq
node = TreeNode(total_freq, left, right)
letters.append(node)
letters.sort(key=lambda l: l.freq)
return letters[0]
def traverse_tree(root, bitstring):
"""
Recursively traverse the Huffman Tree to set each
Letter's bitstring, and return the list of Letters
"""
if type(root) is Letter:
root.bitstring = bitstring
return [root]
letters = []
letters += traverse_tree(root.left, bitstring + "0")
letters += traverse_tree(root.right, bitstring + "1")
return letters
def huffman(file_path):
"""
Parse the file, build the tree, then run through the file
again, using the list of Letters to find and print out the
bitstring for each letter.
"""
letters_list = parse_file(file_path)
root = build_tree(letters_list)
letters = traverse_tree(root, "")
print(f'Huffman Coding of {file_path}: ')
with open(file_path) as f:
while True:
c = f.read(1)
if not c:
break
le = list(filter(lambda l: l.letter == c, letters))[0]
print(le.bitstring, end=" ")
print()
if __name__ == "__main__":
# pass the file path to the huffman function
huffman(sys.argv[1])
| [] | [] | [] |
archives/1098994933_python.zip | compression/peak_signal_to_noise_ratio.py | """
Peak signal-to-noise ratio - PSNR - https://en.wikipedia.org/wiki/Peak_signal-to-noise_ratio
Soruce: https://tutorials.techonical.com/how-to-calculate-psnr-value-of-two-images-using-python/
"""
import math
import os
import cv2
import numpy as np
def psnr(original, contrast):
mse = np.mean((original - contrast) ** 2)
if mse == 0:
return 100
PIXEL_MAX = 255.0
PSNR = 20 * math.log10(PIXEL_MAX / math.sqrt(mse))
return PSNR
def main():
dir_path = os.path.dirname(os.path.realpath(__file__))
# Loading images (original image and compressed image)
original = cv2.imread(os.path.join(dir_path, 'image_data/original_image.png'))
contrast = cv2.imread(os.path.join(dir_path, 'image_data/compressed_image.png'), 1)
original2 = cv2.imread(os.path.join(dir_path, 'image_data/PSNR-example-base.png'))
contrast2 = cv2.imread(os.path.join(dir_path, 'image_data/PSNR-example-comp-10.jpg'), 1)
# Value expected: 29.73dB
print("-- First Test --")
print(f"PSNR value is {psnr(original, contrast)} dB")
# # Value expected: 31.53dB (Wikipedia Example)
print("\n-- Second Test --")
print(f"PSNR value is {psnr(original2, contrast2)} dB")
if __name__ == '__main__':
main()
| [] | [] | [] |
archives/1098994933_python.zip | conversions/decimal_to_binary.py | """Convert a Decimal Number to a Binary Number."""
def decimal_to_binary(num):
"""
Convert a Integer Decimal Number to a Binary Number as str.
>>> decimal_to_binary(0)
'0b0'
>>> decimal_to_binary(2)
'0b10'
>>> decimal_to_binary(7)
'0b111'
>>> decimal_to_binary(35)
'0b100011'
>>> # negatives work too
>>> decimal_to_binary(-2)
'-0b10'
>>> # other floats will error
>>> decimal_to_binary(16.16) # doctest: +ELLIPSIS
Traceback (most recent call last):
...
TypeError: 'float' object cannot be interpreted as an integer
>>> # strings will error as well
>>> decimal_to_binary('0xfffff') # doctest: +ELLIPSIS
Traceback (most recent call last):
...
TypeError: 'str' object cannot be interpreted as an integer
"""
if type(num) == float:
raise TypeError("'float' object cannot be interpreted as an integer")
if type(num) == str:
raise TypeError("'str' object cannot be interpreted as an integer")
if num == 0:
return "0b0"
negative = False
if num < 0:
negative = True
num = -num
binary = []
while num > 0:
binary.insert(0, num % 2)
num >>= 1
if negative:
return "-0b" + "".join(str(e) for e in binary)
return "0b" + "".join(str(e) for e in binary)
if __name__ == "__main__":
import doctest
doctest.testmod()
| [] | [] | [] |
archives/1098994933_python.zip | conversions/decimal_to_hexadecimal.py | """ Convert Base 10 (Decimal) Values to Hexadecimal Representations """
# set decimal value for each hexadecimal digit
values = {
0:'0',
1:'1',
2:'2',
3:'3',
4:'4',
5:'5',
6:'6',
7:'7',
8:'8',
9:'9',
10:'a',
11:'b',
12:'c',
13:'d',
14:'e',
15:'f'
}
def decimal_to_hexadecimal(decimal):
"""
take integer decimal value, return hexadecimal representation as str beginning with 0x
>>> decimal_to_hexadecimal(5)
'0x5'
>>> decimal_to_hexadecimal(15)
'0xf'
>>> decimal_to_hexadecimal(37)
'0x25'
>>> decimal_to_hexadecimal(255)
'0xff'
>>> decimal_to_hexadecimal(4096)
'0x1000'
>>> decimal_to_hexadecimal(999098)
'0xf3eba'
>>> # negatives work too
>>> decimal_to_hexadecimal(-256)
'-0x100'
>>> # floats are acceptable if equivalent to an int
>>> decimal_to_hexadecimal(17.0)
'0x11'
>>> # other floats will error
>>> decimal_to_hexadecimal(16.16) # doctest: +ELLIPSIS
Traceback (most recent call last):
...
AssertionError
>>> # strings will error as well
>>> decimal_to_hexadecimal('0xfffff') # doctest: +ELLIPSIS
Traceback (most recent call last):
...
AssertionError
>>> # results are the same when compared to Python's default hex function
>>> decimal_to_hexadecimal(-256) == hex(-256)
True
"""
assert type(decimal) in (int, float) and decimal == int(decimal)
hexadecimal = ''
negative = False
if decimal < 0:
negative = True
decimal *= -1
while decimal > 0:
decimal, remainder = divmod(decimal, 16)
hexadecimal = values[remainder] + hexadecimal
hexadecimal = '0x' + hexadecimal
if negative:
hexadecimal = '-' + hexadecimal
return hexadecimal
if __name__ == '__main__':
import doctest
doctest.testmod()
| [] | [] | [] |
archives/1098994933_python.zip | conversions/decimal_to_octal.py | """Convert a Decimal Number to an Octal Number."""
import math
# Modified from:
# https://github.com/TheAlgorithms/Javascript/blob/master/Conversions/DecimalToOctal.js
def decimal_to_octal(num):
"""Convert a Decimal Number to an Octal Number."""
octal = 0
counter = 0
while num > 0:
remainder = num % 8
octal = octal + (remainder * math.pow(10, counter))
counter += 1
num = math.floor(num / 8) # basically /= 8 without remainder if any
# This formatting removes trailing '.0' from `octal`.
return'{0:g}'.format(float(octal))
def main():
"""Print octal equivelents of decimal numbers."""
print("\n2 in octal is:")
print(decimal_to_octal(2)) # = 2
print("\n8 in octal is:")
print(decimal_to_octal(8)) # = 10
print("\n65 in octal is:")
print(decimal_to_octal(65)) # = 101
print("\n216 in octal is:")
print(decimal_to_octal(216)) # = 330
print("\n512 in octal is:")
print(decimal_to_octal(512)) # = 1000
print("\n")
if __name__ == '__main__':
main()
| [] | [] | [] |
archives/1098994933_python.zip | data_structures/binary_tree/avl_tree.py | # -*- coding: utf-8 -*-
'''
An auto-balanced binary tree!
'''
import math
import random
class my_queue:
def __init__(self):
self.data = []
self.head = 0
self.tail = 0
def isEmpty(self):
return self.head == self.tail
def push(self,data):
self.data.append(data)
self.tail = self.tail + 1
def pop(self):
ret = self.data[self.head]
self.head = self.head + 1
return ret
def count(self):
return self.tail - self.head
def print(self):
print(self.data)
print("**************")
print(self.data[self.head:self.tail])
class my_node:
def __init__(self,data):
self.data = data
self.left = None
self.right = None
self.height = 1
def getdata(self):
return self.data
def getleft(self):
return self.left
def getright(self):
return self.right
def getheight(self):
return self.height
def setdata(self,data):
self.data = data
return
def setleft(self,node):
self.left = node
return
def setright(self,node):
self.right = node
return
def setheight(self,height):
self.height = height
return
def getheight(node):
if node is None:
return 0
return node.getheight()
def my_max(a,b):
if a > b:
return a
return b
def leftrotation(node):
r'''
A B
/ \ / \
B C Bl A
/ \ --> / / \
Bl Br UB Br C
/
UB
UB = unbalanced node
'''
print("left rotation node:",node.getdata())
ret = node.getleft()
node.setleft(ret.getright())
ret.setright(node)
h1 = my_max(getheight(node.getright()),getheight(node.getleft())) + 1
node.setheight(h1)
h2 = my_max(getheight(ret.getright()),getheight(ret.getleft())) + 1
ret.setheight(h2)
return ret
def rightrotation(node):
'''
a mirror symmetry rotation of the leftrotation
'''
print("right rotation node:",node.getdata())
ret = node.getright()
node.setright(ret.getleft())
ret.setleft(node)
h1 = my_max(getheight(node.getright()),getheight(node.getleft())) + 1
node.setheight(h1)
h2 = my_max(getheight(ret.getright()),getheight(ret.getleft())) + 1
ret.setheight(h2)
return ret
def rlrotation(node):
r'''
A A Br
/ \ / \ / \
B C RR Br C LR B A
/ \ --> / \ --> / / \
Bl Br B UB Bl UB C
\ /
UB Bl
RR = rightrotation LR = leftrotation
'''
node.setleft(rightrotation(node.getleft()))
return leftrotation(node)
def lrrotation(node):
node.setright(leftrotation(node.getright()))
return rightrotation(node)
def insert_node(node,data):
if node is None:
return my_node(data)
if data < node.getdata():
node.setleft(insert_node(node.getleft(),data))
if getheight(node.getleft()) - getheight(node.getright()) == 2: #an unbalance detected
if data < node.getleft().getdata(): #new node is the left child of the left child
node = leftrotation(node)
else:
node = rlrotation(node) #new node is the right child of the left child
else:
node.setright(insert_node(node.getright(),data))
if getheight(node.getright()) - getheight(node.getleft()) == 2:
if data < node.getright().getdata():
node = lrrotation(node)
else:
node = rightrotation(node)
h1 = my_max(getheight(node.getright()),getheight(node.getleft())) + 1
node.setheight(h1)
return node
def getRightMost(root):
while root.getright() is not None:
root = root.getright()
return root.getdata()
def getLeftMost(root):
while root.getleft() is not None:
root = root.getleft()
return root.getdata()
def del_node(root,data):
if root.getdata() == data:
if root.getleft() is not None and root.getright() is not None:
temp_data = getLeftMost(root.getright())
root.setdata(temp_data)
root.setright(del_node(root.getright(),temp_data))
elif root.getleft() is not None:
root = root.getleft()
else:
root = root.getright()
elif root.getdata() > data:
if root.getleft() is None:
print("No such data")
return root
else:
root.setleft(del_node(root.getleft(),data))
elif root.getdata() < data:
if root.getright() is None:
return root
else:
root.setright(del_node(root.getright(),data))
if root is None:
return root
if getheight(root.getright()) - getheight(root.getleft()) == 2:
if getheight(root.getright().getright()) > getheight(root.getright().getleft()):
root = rightrotation(root)
else:
root = lrrotation(root)
elif getheight(root.getright()) - getheight(root.getleft()) == -2:
if getheight(root.getleft().getleft()) > getheight(root.getleft().getright()):
root = leftrotation(root)
else:
root = rlrotation(root)
height = my_max(getheight(root.getright()),getheight(root.getleft())) + 1
root.setheight(height)
return root
class AVLtree:
def __init__(self):
self.root = None
def getheight(self):
# print("yyy")
return getheight(self.root)
def insert(self,data):
print("insert:"+str(data))
self.root = insert_node(self.root,data)
def del_node(self,data):
print("delete:"+str(data))
if self.root is None:
print("Tree is empty!")
return
self.root = del_node(self.root,data)
def traversale(self): #a level traversale, gives a more intuitive look on the tree
q = my_queue()
q.push(self.root)
layer = self.getheight()
if layer == 0:
return
cnt = 0
while not q.isEmpty():
node = q.pop()
space = " "*int(math.pow(2,layer-1))
print(space,end = "")
if node is None:
print("*",end = "")
q.push(None)
q.push(None)
else:
print(node.getdata(),end = "")
q.push(node.getleft())
q.push(node.getright())
print(space,end = "")
cnt = cnt + 1
for i in range(100):
if cnt == math.pow(2,i) - 1:
layer = layer -1
if layer == 0:
print()
print("*************************************")
return
print()
break
print()
print("*************************************")
return
def test(self):
getheight(None)
print("****")
self.getheight()
if __name__ == "__main__":
t = AVLtree()
t.traversale()
l = list(range(10))
random.shuffle(l)
for i in l:
t.insert(i)
t.traversale()
random.shuffle(l)
for i in l:
t.del_node(i)
t.traversale()
| [] | [] | [] |
archives/1098994933_python.zip | data_structures/binary_tree/basic_binary_tree.py | class Node: # This is the Class Node with constructor that contains data variable to type data and left,right pointers.
def __init__(self, data):
self.data = data
self.left = None
self.right = None
def display(tree): #In Order traversal of the tree
if tree is None:
return
if tree.left is not None:
display(tree.left)
print(tree.data)
if tree.right is not None:
display(tree.right)
return
def depth_of_tree(tree): #This is the recursive function to find the depth of binary tree.
if tree is None:
return 0
else:
depth_l_tree = depth_of_tree(tree.left)
depth_r_tree = depth_of_tree(tree.right)
if depth_l_tree > depth_r_tree:
return 1 + depth_l_tree
else:
return 1 + depth_r_tree
def is_full_binary_tree(tree): # This functions returns that is it full binary tree or not?
if tree is None:
return True
if (tree.left is None) and (tree.right is None):
return True
if (tree.left is not None) and (tree.right is not None):
return (is_full_binary_tree(tree.left) and is_full_binary_tree(tree.right))
else:
return False
def main(): # Main func for testing.
tree = Node(1)
tree.left = Node(2)
tree.right = Node(3)
tree.left.left = Node(4)
tree.left.right = Node(5)
tree.left.right.left = Node(6)
tree.right.left = Node(7)
tree.right.left.left = Node(8)
tree.right.left.left.right = Node(9)
print(is_full_binary_tree(tree))
print(depth_of_tree(tree))
print("Tree is: ")
display(tree)
if __name__ == '__main__':
main()
| [] | [] | [] |
archives/1098994933_python.zip | data_structures/binary_tree/binary_search_tree.py | '''
A binary search Tree
'''
class Node:
def __init__(self, label, parent):
self.label = label
self.left = None
self.right = None
#Added in order to delete a node easier
self.parent = parent
def getLabel(self):
return self.label
def setLabel(self, label):
self.label = label
def getLeft(self):
return self.left
def setLeft(self, left):
self.left = left
def getRight(self):
return self.right
def setRight(self, right):
self.right = right
def getParent(self):
return self.parent
def setParent(self, parent):
self.parent = parent
class BinarySearchTree:
def __init__(self):
self.root = None
def insert(self, label):
# Create a new Node
new_node = Node(label, None)
# If Tree is empty
if self.empty():
self.root = new_node
else:
#If Tree is not empty
curr_node = self.root
#While we don't get to a leaf
while curr_node is not None:
#We keep reference of the parent node
parent_node = curr_node
#If node label is less than current node
if new_node.getLabel() < curr_node.getLabel():
#We go left
curr_node = curr_node.getLeft()
else:
#Else we go right
curr_node = curr_node.getRight()
#We insert the new node in a leaf
if new_node.getLabel() < parent_node.getLabel():
parent_node.setLeft(new_node)
else:
parent_node.setRight(new_node)
#Set parent to the new node
new_node.setParent(parent_node)
def delete(self, label):
if (not self.empty()):
#Look for the node with that label
node = self.getNode(label)
#If the node exists
if(node is not None):
#If it has no children
if(node.getLeft() is None and node.getRight() is None):
self.__reassignNodes(node, None)
node = None
#Has only right children
elif(node.getLeft() is None and node.getRight() is not None):
self.__reassignNodes(node, node.getRight())
#Has only left children
elif(node.getLeft() is not None and node.getRight() is None):
self.__reassignNodes(node, node.getLeft())
#Has two children
else:
#Gets the max value of the left branch
tmpNode = self.getMax(node.getLeft())
#Deletes the tmpNode
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
if(not self.empty()):
#Get tree root
curr_node = self.getRoot()
#While we don't find the node we look for
#I am using lazy evaluation here to avoid NoneType Attribute error
while curr_node is not None and curr_node.getLabel() is not label:
#If node label is less than current node
if label < curr_node.getLabel():
#We go left
curr_node = curr_node.getLeft()
else:
#Else we go right
curr_node = curr_node.getRight()
return curr_node
def getMax(self, root = None):
if(root is not None):
curr_node = root
else:
#We go deep on the right branch
curr_node = self.getRoot()
if(not self.empty()):
while(curr_node.getRight() is not None):
curr_node = curr_node.getRight()
return curr_node
def getMin(self, root = None):
if(root is not None):
curr_node = root
else:
#We go deep on the left branch
curr_node = self.getRoot()
if(not self.empty()):
curr_node = self.getRoot()
while(curr_node.getLeft() is not None):
curr_node = curr_node.getLeft()
return curr_node
def empty(self):
if self.root is None:
return True
return False
def __InOrderTraversal(self, curr_node):
nodeList = []
if curr_node is not None:
nodeList.insert(0, curr_node)
nodeList = nodeList + self.__InOrderTraversal(curr_node.getLeft())
nodeList = nodeList + self.__InOrderTraversal(curr_node.getRight())
return nodeList
def getRoot(self):
return self.root
def __isRightChildren(self, node):
if(node == node.getParent().getRight()):
return True
return False
def __reassignNodes(self, node, newChildren):
if(newChildren is not None):
newChildren.setParent(node.getParent())
if(node.getParent() is not None):
#If it is the Right Children
if(self.__isRightChildren(node)):
node.getParent().setRight(newChildren)
else:
#Else it is the left children
node.getParent().setLeft(newChildren)
#This function traversal the tree. By default it returns an
#In order traversal list. You can pass a function to traversal
#The tree as needed by client code
def traversalTree(self, traversalFunction = None, root = None):
if(traversalFunction is None):
#Returns a list of nodes in preOrder by default
return self.__InOrderTraversal(self.root)
else:
#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
#In Order Traversal
def __str__(self):
list = self.__InOrderTraversal(self.root)
str = ""
for x in list:
str = str + " " + x.getLabel().__str__()
return str
def InPreOrder(curr_node):
nodeList = []
if curr_node is not None:
nodeList = nodeList + InPreOrder(curr_node.getLeft())
nodeList.insert(0, curr_node.getLabel())
nodeList = nodeList + InPreOrder(curr_node.getRight())
return nodeList
def testBinarySearchTree():
r'''
Example
8
/ \
3 10
/ \ \
1 6 14
/ \ /
4 7 13
'''
r'''
Example After Deletion
7
/ \
1 4
'''
t = BinarySearchTree()
t.insert(8)
t.insert(3)
t.insert(6)
t.insert(1)
t.insert(10)
t.insert(14)
t.insert(13)
t.insert(4)
t.insert(7)
#Prints all the elements of the list in order traversal
print(t.__str__())
if(t.getNode(6) is not None):
print("The label 6 exists")
else:
print("The label 6 doesn't exist")
if(t.getNode(-1) is not None):
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)
t.delete(3)
t.delete(6)
t.delete(14)
#Gets all the elements of the tree In pre order
#And it prints them
list = t.traversalTree(InPreOrder, t.root)
for x in list:
print(x)
if __name__ == "__main__":
testBinarySearchTree()
| [] | [] | [] |
archives/1098994933_python.zip | data_structures/binary_tree/fenwick_tree.py | class FenwickTree:
def __init__(self, SIZE): # create fenwick tree with size SIZE
self.Size = SIZE
self.ft = [0 for i in range (0,SIZE)]
def update(self, i, val): # update data (adding) in index i in O(lg N)
while (i < self.Size):
self.ft[i] += val
i += i & (-i)
def query(self, i): # query cumulative data from index 0 to i in O(lg N)
ret = 0
while (i > 0):
ret += self.ft[i]
i -= i & (-i)
return ret
if __name__ == '__main__':
f = FenwickTree(100)
f.update(1,20)
f.update(4,4)
print(f.query(1))
print(f.query(3))
print(f.query(4))
f.update(2,-5)
print(f.query(1))
print(f.query(3))
| [] | [] | [] |
archives/1098994933_python.zip | data_structures/binary_tree/lazy_segment_tree.py | import math
class SegmentTree:
def __init__(self, N):
self.N = N
self.st = [0 for i in range(0,4*N)] # approximate the overall size of segment tree with array N
self.lazy = [0 for i in range(0,4*N)] # create array to store lazy update
self.flag = [0 for i in range(0,4*N)] # flag for lazy update
def left(self, idx):
return idx*2
def right(self, idx):
return idx*2 + 1
def build(self, idx, l, r, A):
if l==r:
self.st[idx] = A[l-1]
else :
mid = (l+r)//2
self.build(self.left(idx),l,mid, A)
self.build(self.right(idx),mid+1,r, A)
self.st[idx] = max(self.st[self.left(idx)] , self.st[self.right(idx)])
# update with O(lg N) (Normal segment tree without lazy update will take O(Nlg N) for each update)
def update(self, idx, l, r, a, b, val): # update(1, 1, N, a, b, v) for update val v to [a,b]
if self.flag[idx] == True:
self.st[idx] = self.lazy[idx]
self.flag[idx] = False
if l!=r:
self.lazy[self.left(idx)] = self.lazy[idx]
self.lazy[self.right(idx)] = self.lazy[idx]
self.flag[self.left(idx)] = True
self.flag[self.right(idx)] = True
if r < a or l > b:
return True
if l >= a and r <= b :
self.st[idx] = val
if l!=r:
self.lazy[self.left(idx)] = val
self.lazy[self.right(idx)] = val
self.flag[self.left(idx)] = True
self.flag[self.right(idx)] = True
return True
mid = (l+r)//2
self.update(self.left(idx),l,mid,a,b,val)
self.update(self.right(idx),mid+1,r,a,b,val)
self.st[idx] = max(self.st[self.left(idx)] , self.st[self.right(idx)])
return True
# query with O(lg N)
def query(self, idx, l, r, a, b): #query(1, 1, N, a, b) for query max of [a,b]
if self.flag[idx] == True:
self.st[idx] = self.lazy[idx]
self.flag[idx] = False
if l != r:
self.lazy[self.left(idx)] = self.lazy[idx]
self.lazy[self.right(idx)] = self.lazy[idx]
self.flag[self.left(idx)] = True
self.flag[self.right(idx)] = True
if r < a or l > b:
return -math.inf
if l >= a and r <= b:
return self.st[idx]
mid = (l+r)//2
q1 = self.query(self.left(idx),l,mid,a,b)
q2 = self.query(self.right(idx),mid+1,r,a,b)
return max(q1,q2)
def showData(self):
showList = []
for i in range(1,N+1):
showList += [self.query(1, 1, self.N, i, i)]
print(showList)
if __name__ == '__main__':
A = [1,2,-4,7,3,-5,6,11,-20,9,14,15,5,2,-8]
N = 15
segt = SegmentTree(N)
segt.build(1,1,N,A)
print(segt.query(1,1,N,4,6))
print(segt.query(1,1,N,7,11))
print(segt.query(1,1,N,7,12))
segt.update(1,1,N,1,3,111)
print(segt.query(1,1,N,1,15))
segt.update(1,1,N,7,8,235)
segt.showData()
| [] | [] | [] |
archives/1098994933_python.zip | data_structures/binary_tree/lca.py | import queue
def swap(a, b):
a ^= b
b ^= a
a ^= b
return a, b
# creating sparse table which saves each nodes 2^ith parent
def creatSparse(max_node, parent):
j = 1
while (1 << j) < max_node:
for i in range(1, max_node + 1):
parent[j][i] = parent[j - 1][parent[j - 1][i]]
j += 1
return parent
# returns lca of node u,v
def LCA(u, v, level, parent):
# u must be deeper in the tree than v
if level[u] < level[v]:
u, v = swap(u, v)
# making depth of u same as depth of v
for i in range(18, -1, -1):
if level[u] - (1 << i) >= level[v]:
u = parent[i][u]
# at the same depth if u==v that mean lca is found
if u == v:
return u
# moving both nodes upwards till lca in found
for i in range(18, -1, -1):
if parent[i][u] != 0 and parent[i][u] != parent[i][v]:
u, v = parent[i][u], parent[i][v]
# returning longest common ancestor of u,v
return parent[0][u]
# runs a breadth first search from root node of the tree
# sets every nodes direct parent
# parent of root node is set to 0
# calculates depth of each node from root node
def bfs(level, parent, max_node, graph, root=1):
level[root] = 0
q = queue.Queue(maxsize=max_node)
q.put(root)
while q.qsize() != 0:
u = q.get()
for v in graph[u]:
if level[v] == -1:
level[v] = level[u] + 1
q.put(v)
parent[0][v] = u
return level, parent
def main():
max_node = 13
# initializing with 0
parent = [[0 for _ in range(max_node + 10)] for _ in range(20)]
# initializing with -1 which means every node is unvisited
level = [-1 for _ in range(max_node + 10)]
graph = {
1: [2, 3, 4],
2: [5],
3: [6, 7],
4: [8],
5: [9, 10],
6: [11],
7: [],
8: [12, 13],
9: [],
10: [],
11: [],
12: [],
13: []
}
level, parent = bfs(level, parent, max_node, graph, 1)
parent = creatSparse(max_node, parent)
print("LCA of node 1 and 3 is: ", LCA(1, 3, level, parent))
print("LCA of node 5 and 6 is: ", LCA(5, 6, level, parent))
print("LCA of node 7 and 11 is: ", LCA(7, 11, level, parent))
print("LCA of node 6 and 7 is: ", LCA(6, 7, level, parent))
print("LCA of node 4 and 12 is: ", LCA(4, 12, level, parent))
print("LCA of node 8 and 8 is: ", LCA(8, 8, level, parent))
if __name__ == "__main__":
main()
| [] | [] | [] |
archives/1098994933_python.zip | data_structures/binary_tree/red_black_tree.py | """
python/black : true
flake8 : passed
"""
class RedBlackTree:
"""
A Red-Black tree, which is a self-balancing BST (binary search
tree).
This tree has similar performance to AVL trees, but the balancing is
less strict, so it will perform faster for writing/deleting nodes
and slower for reading in the average case, though, because they're
both balanced binary search trees, both will get the same asymptotic
perfomance.
To read more about them, https://en.wikipedia.org/wiki/Red–black_tree
Unless otherwise specified, all asymptotic runtimes are specified in
terms of the size of the tree.
"""
def __init__(self, label=None, color=0, parent=None, left=None, right=None):
"""Initialize a new Red-Black Tree node with the given values:
label: The value associated with this node
color: 0 if black, 1 if red
parent: The parent to this node
left: This node's left child
right: This node's right child
"""
self.label = label
self.parent = parent
self.left = left
self.right = right
self.color = color
# Here are functions which are specific to red-black trees
def rotate_left(self):
"""Rotate the subtree rooted at this node to the left and
returns the new root to this subtree.
Perfoming one rotation can be done in O(1).
"""
parent = self.parent
right = self.right
self.right = right.left
if self.right:
self.right.parent = self
self.parent = right
right.left = self
if parent is not None:
if parent.left == self:
parent.left = right
else:
parent.right = right
right.parent = parent
return right
def rotate_right(self):
"""Rotate the subtree rooted at this node to the right and
returns the new root to this subtree.
Performing one rotation can be done in O(1).
"""
parent = self.parent
left = self.left
self.left = left.right
if self.left:
self.left.parent = self
self.parent = left
left.right = self
if parent is not None:
if parent.right is self:
parent.right = left
else:
parent.left = left
left.parent = parent
return left
def insert(self, label):
"""Inserts label into the subtree rooted at self, performs any
rotations necessary to maintain balance, and then returns the
new root to this subtree (likely self).
This is guaranteed to run in O(log(n)) time.
"""
if self.label is None:
# Only possible with an empty tree
self.label = label
return self
if self.label == label:
return self
elif self.label > label:
if self.left:
self.left.insert(label)
else:
self.left = RedBlackTree(label, 1, self)
self.left._insert_repair()
else:
if self.right:
self.right.insert(label)
else:
self.right = RedBlackTree(label, 1, self)
self.right._insert_repair()
return self.parent or self
def _insert_repair(self):
"""Repair the coloring from inserting into a tree."""
if self.parent is None:
# This node is the root, so it just needs to be black
self.color = 0
elif color(self.parent) == 0:
# If the parent is black, then it just needs to be red
self.color = 1
else:
uncle = self.parent.sibling
if color(uncle) == 0:
if self.is_left() and self.parent.is_right():
self.parent.rotate_right()
self.right._insert_repair()
elif self.is_right() and self.parent.is_left():
self.parent.rotate_left()
self.left._insert_repair()
elif self.is_left():
self.grandparent.rotate_right()
self.parent.color = 0
self.parent.right.color = 1
else:
self.grandparent.rotate_left()
self.parent.color = 0
self.parent.left.color = 1
else:
self.parent.color = 0
uncle.color = 0
self.grandparent.color = 1
self.grandparent._insert_repair()
def remove(self, label):
"""Remove label from this tree."""
if self.label == label:
if self.left and self.right:
# It's easier to balance a node with at most one child,
# so we replace this node with the greatest one less than
# it and remove that.
value = self.left.get_max()
self.label = value
self.left.remove(value)
else:
# This node has at most one non-None child, so we don't
# need to replace
child = self.left or self.right
if self.color == 1:
# This node is red, and its child is black
# The only way this happens to a node with one child
# is if both children are None leaves.
# We can just remove this node and call it a day.
if self.is_left():
self.parent.left = None
else:
self.parent.right = None
else:
# The node is black
if child is None:
# This node and its child are black
if self.parent is None:
# The tree is now empty
return RedBlackTree(None)
else:
self._remove_repair()
if self.is_left():
self.parent.left = None
else:
self.parent.right = None
self.parent = None
else:
# This node is black and its child is red
# Move the child node here and make it black
self.label = child.label
self.left = child.left
self.right = child.right
if self.left:
self.left.parent = self
if self.right:
self.right.parent = self
elif self.label > label:
if self.left:
self.left.remove(label)
else:
if self.right:
self.right.remove(label)
return self.parent or self
def _remove_repair(self):
"""Repair the coloring of the tree that may have been messed up."""
if color(self.sibling) == 1:
self.sibling.color = 0
self.parent.color = 1
if self.is_left():
self.parent.rotate_left()
else:
self.parent.rotate_right()
if (
color(self.parent) == 0
and color(self.sibling) == 0
and color(self.sibling.left) == 0
and color(self.sibling.right) == 0
):
self.sibling.color = 1
self.parent._remove_repair()
return
if (
color(self.parent) == 1
and color(self.sibling) == 0
and color(self.sibling.left) == 0
and color(self.sibling.right) == 0
):
self.sibling.color = 1
self.parent.color = 0
return
if (
self.is_left()
and color(self.sibling) == 0
and color(self.sibling.right) == 0
and color(self.sibling.left) == 1
):
self.sibling.rotate_right()
self.sibling.color = 0
self.sibling.right.color = 1
if (
self.is_right()
and color(self.sibling) == 0
and color(self.sibling.right) == 1
and color(self.sibling.left) == 0
):
self.sibling.rotate_left()
self.sibling.color = 0
self.sibling.left.color = 1
if (
self.is_left()
and color(self.sibling) == 0
and color(self.sibling.right) == 1
):
self.parent.rotate_left()
self.grandparent.color = self.parent.color
self.parent.color = 0
self.parent.sibling.color = 0
if (
self.is_right()
and color(self.sibling) == 0
and color(self.sibling.left) == 1
):
self.parent.rotate_right()
self.grandparent.color = self.parent.color
self.parent.color = 0
self.parent.sibling.color = 0
def check_color_properties(self):
"""Check the coloring of the tree, and return True iff the tree
is colored in a way which matches these five properties:
(wording stolen from wikipedia article)
1. Each node is either red or black.
2. The root node is black.
3. All leaves are black.
4. If a node is red, then both its children are black.
5. Every path from any node to all of its descendent NIL nodes
has the same number of black nodes.
This function runs in O(n) time, because properties 4 and 5 take
that long to check.
"""
# I assume property 1 to hold because there is nothing that can
# make the color be anything other than 0 or 1.
# Property 2
if self.color:
# The root was red
print("Property 2")
return False
# Property 3 does not need to be checked, because None is assumed
# to be black and is all the leaves.
# Property 4
if not self.check_coloring():
print("Property 4")
return False
# Property 5
if self.black_height() is None:
print("Property 5")
return False
# All properties were met
return True
def check_coloring(self):
"""A helper function to recursively check Property 4 of a
Red-Black Tree. See check_color_properties for more info.
"""
if self.color == 1:
if color(self.left) == 1 or color(self.right) == 1:
return False
if self.left and not self.left.check_coloring():
return False
if self.right and not self.right.check_coloring():
return False
return True
def black_height(self):
"""Returns the number of black nodes from this node to the
leaves of the tree, or None if there isn't one such value (the
tree is color incorrectly).
"""
if self is None:
# If we're already at a leaf, there is no path
return 1
left = RedBlackTree.black_height(self.left)
right = RedBlackTree.black_height(self.right)
if left is None or right is None:
# There are issues with coloring below children nodes
return None
if left != right:
# The two children have unequal depths
return None
# Return the black depth of children, plus one if this node is
# black
return left + (1 - self.color)
# Here are functions which are general to all binary search trees
def __contains__(self, label):
"""Search through the tree for label, returning True iff it is
found somewhere in the tree.
Guaranteed to run in O(log(n)) time.
"""
return self.search(label) is not None
def search(self, label):
"""Search through the tree for label, returning its node if
it's found, and None otherwise.
This method is guaranteed to run in O(log(n)) time.
"""
if self.label == label:
return self
elif label > self.label:
if self.right is None:
return None
else:
return self.right.search(label)
else:
if self.left is None:
return None
else:
return self.left.search(label)
def floor(self, label):
"""Returns the largest element in this tree which is at most label.
This method is guaranteed to run in O(log(n)) time."""
if self.label == label:
return self.label
elif self.label > label:
if self.left:
return self.left.floor(label)
else:
return None
else:
if self.right:
attempt = self.right.floor(label)
if attempt is not None:
return attempt
return self.label
def ceil(self, label):
"""Returns the smallest element in this tree which is at least label.
This method is guaranteed to run in O(log(n)) time.
"""
if self.label == label:
return self.label
elif self.label < label:
if self.right:
return self.right.ceil(label)
else:
return None
else:
if self.left:
attempt = self.left.ceil(label)
if attempt is not None:
return attempt
return self.label
def get_max(self):
"""Returns the largest element in this tree.
This method is guaranteed to run in O(log(n)) time.
"""
if self.right:
# Go as far right as possible
return self.right.get_max()
else:
return self.label
def get_min(self):
"""Returns the smallest element in this tree.
This method is guaranteed to run in O(log(n)) time.
"""
if self.left:
# Go as far left as possible
return self.left.get_min()
else:
return self.label
@property
def grandparent(self):
"""Get the current node's grandparent, or None if it doesn't exist."""
if self.parent is None:
return None
else:
return self.parent.parent
@property
def sibling(self):
"""Get the current node's sibling, or None if it doesn't exist."""
if self.parent is None:
return None
elif self.parent.left is self:
return self.parent.right
else:
return self.parent.left
def is_left(self):
"""Returns true iff this node is the left child of its parent."""
return self.parent and self.parent.left is self
def is_right(self):
"""Returns true iff this node is the right child of its parent."""
return self.parent and self.parent.right is self
def __bool__(self):
return True
def __len__(self):
"""
Return the number of nodes in this tree.
"""
ln = 1
if self.left:
ln += len(self.left)
if self.right:
ln += len(self.right)
return ln
def preorder_traverse(self):
yield self.label
if self.left:
yield from self.left.preorder_traverse()
if self.right:
yield from self.right.preorder_traverse()
def inorder_traverse(self):
if self.left:
yield from self.left.inorder_traverse()
yield self.label
if self.right:
yield from self.right.inorder_traverse()
def postorder_traverse(self):
if self.left:
yield from self.left.postorder_traverse()
if self.right:
yield from self.right.postorder_traverse()
yield self.label
def __repr__(self):
from pprint import pformat
if self.left is None and self.right is None:
return "'%s %s'" % (self.label, (self.color and "red") or "blk")
return pformat(
{
"%s %s"
% (self.label, (self.color and "red") or "blk"): (self.left, self.right)
},
indent=1,
)
def __eq__(self, other):
"""Test if two trees are equal."""
if self.label == other.label:
return self.left == other.left and self.right == other.right
else:
return False
def color(node):
"""Returns the color of a node, allowing for None leaves."""
if node is None:
return 0
else:
return node.color
"""
Code for testing the various
functions of the red-black tree.
"""
def test_rotations():
"""Test that the rotate_left and rotate_right functions work."""
# Make a tree to test on
tree = RedBlackTree(0)
tree.left = RedBlackTree(-10, parent=tree)
tree.right = RedBlackTree(10, parent=tree)
tree.left.left = RedBlackTree(-20, parent=tree.left)
tree.left.right = RedBlackTree(-5, parent=tree.left)
tree.right.left = RedBlackTree(5, parent=tree.right)
tree.right.right = RedBlackTree(20, parent=tree.right)
# Make the right rotation
left_rot = RedBlackTree(10)
left_rot.left = RedBlackTree(0, parent=left_rot)
left_rot.left.left = RedBlackTree(-10, parent=left_rot.left)
left_rot.left.right = RedBlackTree(5, parent=left_rot.left)
left_rot.left.left.left = RedBlackTree(-20, parent=left_rot.left.left)
left_rot.left.left.right = RedBlackTree(-5, parent=left_rot.left.left)
left_rot.right = RedBlackTree(20, parent=left_rot)
tree = tree.rotate_left()
if tree != left_rot:
return False
tree = tree.rotate_right()
tree = tree.rotate_right()
# Make the left rotation
right_rot = RedBlackTree(-10)
right_rot.left = RedBlackTree(-20, parent=right_rot)
right_rot.right = RedBlackTree(0, parent=right_rot)
right_rot.right.left = RedBlackTree(-5, parent=right_rot.right)
right_rot.right.right = RedBlackTree(10, parent=right_rot.right)
right_rot.right.right.left = RedBlackTree(5, parent=right_rot.right.right)
right_rot.right.right.right = RedBlackTree(20, parent=right_rot.right.right)
if tree != right_rot:
return False
return True
def test_insertion_speed():
"""Test that the tree balances inserts to O(log(n)) by doing a lot
of them.
"""
tree = RedBlackTree(-1)
for i in range(300000):
tree = tree.insert(i)
return True
def test_insert():
"""Test the insert() method of the tree correctly balances, colors,
and inserts.
"""
tree = RedBlackTree(0)
tree.insert(8)
tree.insert(-8)
tree.insert(4)
tree.insert(12)
tree.insert(10)
tree.insert(11)
ans = RedBlackTree(0, 0)
ans.left = RedBlackTree(-8, 0, ans)
ans.right = RedBlackTree(8, 1, ans)
ans.right.left = RedBlackTree(4, 0, ans.right)
ans.right.right = RedBlackTree(11, 0, ans.right)
ans.right.right.left = RedBlackTree(10, 1, ans.right.right)
ans.right.right.right = RedBlackTree(12, 1, ans.right.right)
return tree == ans
def test_insert_and_search():
"""Tests searching through the tree for values."""
tree = RedBlackTree(0)
tree.insert(8)
tree.insert(-8)
tree.insert(4)
tree.insert(12)
tree.insert(10)
tree.insert(11)
if 5 in tree or -6 in tree or -10 in tree or 13 in tree:
# Found something not in there
return False
if not (11 in tree and 12 in tree and -8 in tree and 0 in tree):
# Didn't find something in there
return False
return True
def test_insert_delete():
"""Test the insert() and delete() method of the tree, verifying the
insertion and removal of elements, and the balancing of the tree.
"""
tree = RedBlackTree(0)
tree = tree.insert(-12)
tree = tree.insert(8)
tree = tree.insert(-8)
tree = tree.insert(15)
tree = tree.insert(4)
tree = tree.insert(12)
tree = tree.insert(10)
tree = tree.insert(9)
tree = tree.insert(11)
tree = tree.remove(15)
tree = tree.remove(-12)
tree = tree.remove(9)
if not tree.check_color_properties():
return False
if list(tree.inorder_traverse()) != [-8, 0, 4, 8, 10, 11, 12]:
return False
return True
def test_floor_ceil():
"""Tests the floor and ceiling functions in the tree."""
tree = RedBlackTree(0)
tree.insert(-16)
tree.insert(16)
tree.insert(8)
tree.insert(24)
tree.insert(20)
tree.insert(22)
tuples = [(-20, None, -16), (-10, -16, 0), (8, 8, 8), (50, 24, None)]
for val, floor, ceil in tuples:
if tree.floor(val) != floor or tree.ceil(val) != ceil:
return False
return True
def test_min_max():
"""Tests the min and max functions in the tree."""
tree = RedBlackTree(0)
tree.insert(-16)
tree.insert(16)
tree.insert(8)
tree.insert(24)
tree.insert(20)
tree.insert(22)
if tree.get_max() != 22 or tree.get_min() != -16:
return False
return True
def test_tree_traversal():
"""Tests the three different tree traversal functions."""
tree = RedBlackTree(0)
tree = tree.insert(-16)
tree.insert(16)
tree.insert(8)
tree.insert(24)
tree.insert(20)
tree.insert(22)
if list(tree.inorder_traverse()) != [-16, 0, 8, 16, 20, 22, 24]:
return False
if list(tree.preorder_traverse()) != [0, -16, 16, 8, 22, 20, 24]:
return False
if list(tree.postorder_traverse()) != [-16, 8, 20, 24, 22, 16, 0]:
return False
return True
def test_tree_chaining():
"""Tests the three different tree chaning functions."""
tree = RedBlackTree(0)
tree = tree.insert(-16).insert(16).insert(8).insert(24).insert(20).insert(22)
if list(tree.inorder_traverse()) != [-16, 0, 8, 16, 20, 22, 24]:
return False
if list(tree.preorder_traverse()) != [0, -16, 16, 8, 22, 20, 24]:
return False
if list(tree.postorder_traverse()) != [-16, 8, 20, 24, 22, 16, 0]:
return False
return True
def print_results(msg: str, passes: bool) -> None:
print(str(msg), "works!" if passes else "doesn't work :(")
def pytests():
assert test_rotations()
assert test_insert()
assert test_insert_and_search()
assert test_insert_delete()
assert test_floor_ceil()
assert test_tree_traversal()
assert test_tree_chaining()
def main():
"""
>>> pytests()
"""
print_results("Rotating right and left", test_rotations())
print_results("Inserting", test_insert())
print_results("Searching", test_insert_and_search())
print_results("Deleting", test_insert_delete())
print_results("Floor and ceil", test_floor_ceil())
print_results("Tree traversal", test_tree_traversal())
print_results("Tree traversal", test_tree_chaining())
print("Testing tree balancing...")
print("This should only be a few seconds.")
test_insertion_speed()
print("Done!")
if __name__ == "__main__":
main()
| [
"str",
"bool"
] | [
23153,
23166
] | [
23156,
23170
] |
archives/1098994933_python.zip | data_structures/binary_tree/segment_tree.py | import math
class SegmentTree:
def __init__(self, A):
self.N = len(A)
self.st = [0] * (4 * self.N) # approximate the overall size of segment tree with array N
self.build(1, 0, self.N - 1)
def left(self, idx):
return idx * 2
def right(self, idx):
return idx * 2 + 1
def build(self, idx, l, r):
if l == r:
self.st[idx] = A[l]
else:
mid = (l + r) // 2
self.build(self.left(idx), l, mid)
self.build(self.right(idx), mid + 1, r)
self.st[idx] = max(self.st[self.left(idx)] , self.st[self.right(idx)])
def update(self, a, b, val):
return self.update_recursive(1, 0, self.N - 1, a - 1, b - 1, val)
def update_recursive(self, idx, l, r, a, b, val): # update(1, 1, N, a, b, v) for update val v to [a,b]
if r < a or l > b:
return True
if l == r :
self.st[idx] = val
return True
mid = (l+r)//2
self.update_recursive(self.left(idx), l, mid, a, b, val)
self.update_recursive(self.right(idx), mid+1, r, a, b, val)
self.st[idx] = max(self.st[self.left(idx)] , self.st[self.right(idx)])
return True
def query(self, a, b):
return self.query_recursive(1, 0, self.N - 1, a - 1, b - 1)
def query_recursive(self, idx, l, r, a, b): #query(1, 1, N, a, b) for query max of [a,b]
if r < a or l > b:
return -math.inf
if l >= a and r <= b:
return self.st[idx]
mid = (l+r)//2
q1 = self.query_recursive(self.left(idx), l, mid, a, b)
q2 = self.query_recursive(self.right(idx), mid + 1, r, a, b)
return max(q1, q2)
def showData(self):
showList = []
for i in range(1,N+1):
showList += [self.query(i, i)]
print(showList)
if __name__ == '__main__':
A = [1,2,-4,7,3,-5,6,11,-20,9,14,15,5,2,-8]
N = 15
segt = SegmentTree(A)
print(segt.query(4, 6))
print(segt.query(7, 11))
print(segt.query(7, 12))
segt.update(1,3,111)
print(segt.query(1, 15))
segt.update(7,8,235)
segt.showData()
| [] | [] | [] |
archives/1098994933_python.zip | data_structures/binary_tree/treap.py | from random import random
from typing import Tuple
class Node:
"""
Treap's node
Treap is a binary tree by key and heap by priority
"""
def __init__(self, key: int):
self.key = key
self.prior = random()
self.l = None
self.r = None
def split(root: Node, key: int) -> Tuple[Node, Node]:
"""
We split current tree into 2 trees with key:
Left tree contains all keys less than split key.
Right tree contains all keys greater or equal, than split key
"""
if root is None: # None tree is split into 2 Nones
return (None, None)
if root.key >= key:
"""
Right tree's root will be current node.
Now we split(with the same key) current node's left son
Left tree: left part of that split
Right tree's left son: right part of that split
"""
l, root.l = split(root.l, key)
return (l, root)
else:
"""
Just symmetric to previous case
"""
root.r, r = split(root.r, key)
return (root, r)
def merge(left: Node, right: Node) -> Node:
"""
We merge 2 trees into one.
Note: all left tree's keys must be less than all right tree's
"""
if (not left) or (not right):
"""
If one node is None, return the other
"""
return left or right
if left.key > right.key:
"""
Left will be root because it has more priority
Now we need to merge left's right son and right tree
"""
left.r = merge(left.r, right)
return left
else:
"""
Symmetric as well
"""
right.l = merge(left, right.l)
return right
def insert(root: Node, key: int) -> Node:
"""
Insert element
Split current tree with a key into l, r,
Insert new node into the middle
Merge l, node, r into root
"""
node = Node(key)
l, r = split(root, key)
root = merge(l, node)
root = merge(root, r)
return root
def erase(root: Node, key: int) -> Node:
"""
Erase element
Split all nodes with keys less into l,
Split all nodes with keys greater into r.
Merge l, r
"""
l, r = split(root, key)
_, r = split(r, key + 1)
return merge(l, r)
def node_print(root: Node):
"""
Just recursive print of a tree
"""
if not root:
return
node_print(root.l)
print(root.key, end=" ")
node_print(root.r)
def interactTreap():
"""
Commands:
+ key to add key into treap
- key to erase all nodes with key
After each command, program prints treap
"""
root = None
while True:
cmd = input().split()
cmd[1] = int(cmd[1])
if cmd[0] == "+":
root = insert(root, cmd[1])
elif cmd[0] == "-":
root = erase(root, cmd[1])
else:
print("Unknown command")
node_print(root)
if __name__ == "__main__":
interactTreap()
| [
"int",
"Node",
"int",
"Node",
"Node",
"Node",
"int",
"Node",
"int",
"Node"
] | [
181,
302,
313,
1088,
1101,
1728,
1739,
2036,
2047,
2303
] | [
184,
306,
316,
1092,
1105,
1732,
1742,
2040,
2050,
2307
] |
archives/1098994933_python.zip | data_structures/hashing/double_hash.py | #!/usr/bin/env python3
from hash_table import HashTable
from number_theory.prime_numbers import next_prime, check_prime
class DoubleHash(HashTable):
"""
Hash Table example with open addressing and Double Hash
"""
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def __hash_function_2(self, value, data):
next_prime_gt = next_prime(value % self.size_table) \
if not check_prime(value % self.size_table) else value % self.size_table #gt = bigger than
return next_prime_gt - (data % next_prime_gt)
def __hash_double_function(self, key, data, increment):
return (increment * self.__hash_function_2(key, data)) % self.size_table
def _colision_resolution(self, key, data=None):
i = 1
new_key = self.hash_function(data)
while self.values[new_key] is not None and self.values[new_key] != key:
new_key = self.__hash_double_function(key, data, i) if \
self.balanced_factor() >= self.lim_charge else None
if new_key is None: break
else: i += 1
return new_key
| [] | [] | [] |
archives/1098994933_python.zip | data_structures/hashing/hash_table.py | #!/usr/bin/env python3
from number_theory.prime_numbers import next_prime
class HashTable:
"""
Basic Hash Table example with open addressing and linear probing
"""
def __init__(self, size_table, charge_factor=None, lim_charge=None):
self.size_table = size_table
self.values = [None] * self.size_table
self.lim_charge = 0.75 if lim_charge is None else lim_charge
self.charge_factor = 1 if charge_factor is None else charge_factor
self.__aux_list = []
self._keys = {}
def keys(self):
return self._keys
def balanced_factor(self):
return sum([1 for slot in self.values
if slot is not None]) / (self.size_table * self.charge_factor)
def hash_function(self, key):
return key % self.size_table
def _step_by_step(self, step_ord):
print("step {0}".format(step_ord))
print([i for i in range(len(self.values))])
print(self.values)
def bulk_insert(self, values):
i = 1
self.__aux_list = values
for value in values:
self.insert_data(value)
self._step_by_step(i)
i += 1
def _set_value(self, key, data):
self.values[key] = data
self._keys[key] = data
def _colision_resolution(self, key, data=None):
new_key = self.hash_function(key + 1)
while self.values[new_key] is not None \
and self.values[new_key] != key:
if self.values.count(None) > 0:
new_key = self.hash_function(new_key + 1)
else:
new_key = None
break
return new_key
def rehashing(self):
survivor_values = [value for value in self.values if value is not None]
self.size_table = next_prime(self.size_table, factor=2)
self._keys.clear()
self.values = [None] * self.size_table #hell's pointers D: don't DRY ;/
map(self.insert_data, survivor_values)
def insert_data(self, data):
key = self.hash_function(data)
if self.values[key] is None:
self._set_value(key, data)
elif self.values[key] == data:
pass
else:
colision_resolution = self._colision_resolution(key, data)
if colision_resolution is not None:
self._set_value(colision_resolution, data)
else:
self.rehashing()
self.insert_data(data)
| [] | [] | [] |
archives/1098994933_python.zip | data_structures/hashing/hash_table_with_linked_list.py | from hash_table import HashTable
from collections import deque
class HashTableWithLinkedList(HashTable):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def _set_value(self, key, data):
self.values[key] = deque([]) if self.values[key] is None else self.values[key]
self.values[key].appendleft(data)
self._keys[key] = self.values[key]
def balanced_factor(self):
return sum([self.charge_factor - len(slot) for slot in self.values])\
/ self.size_table * self.charge_factor
def _colision_resolution(self, key, data=None):
if not (len(self.values[key]) == self.charge_factor
and self.values.count(None) == 0):
return key
return super()._colision_resolution(key, data)
| [] | [] | [] |
archives/1098994933_python.zip | data_structures/hashing/number_theory/__init__.py | [] | [] | [] |
|
archives/1098994933_python.zip | data_structures/hashing/number_theory/prime_numbers.py | #!/usr/bin/env python3
"""
module to operations with prime numbers
"""
def check_prime(number):
"""
it's not the best solution
"""
special_non_primes = [0,1,2]
if number in special_non_primes[:2]:
return 2
elif number == special_non_primes[-1]:
return 3
return all([number % i for i in range(2, number)])
def next_prime(value, factor=1, **kwargs):
value = factor * value
first_value_val = value
while not check_prime(value):
value += 1 if not ("desc" in kwargs.keys() and kwargs["desc"] is True) else -1
if value == first_value_val:
return next_prime(value + 1, **kwargs)
return value
| [] | [] | [] |
archives/1098994933_python.zip | data_structures/hashing/quadratic_probing.py | #!/usr/bin/env python3
from hash_table import HashTable
class QuadraticProbing(HashTable):
"""
Basic Hash Table example with open addressing using Quadratic Probing
"""
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def _colision_resolution(self, key, data=None):
i = 1
new_key = self.hash_function(key + i*i)
while self.values[new_key] is not None \
and self.values[new_key] != key:
i += 1
new_key = self.hash_function(key + i*i) if not \
self.balanced_factor() >= self.lim_charge else None
if new_key is None:
break
return new_key
| [] | [] | [] |
archives/1098994933_python.zip | data_structures/heap/binomial_heap.py | """
Binomial Heap
Reference: Advanced Data Structures, Peter Brass
"""
class Node:
"""
Node in a doubly-linked binomial tree, containing:
- value
- size of left subtree
- link to left, right and parent nodes
"""
def __init__(self, val):
self.val = val
# Number of nodes in left subtree
self.left_tree_size = 0
self.left = None
self.right = None
self.parent = None
def mergeTrees(self, other):
"""
In-place merge of two binomial trees of equal size.
Returns the root of the resulting tree
"""
assert (
self.left_tree_size == other.left_tree_size
), "Unequal Sizes of Blocks"
if self.val < other.val:
other.left = self.right
other.parent = None
if self.right:
self.right.parent = other
self.right = other
self.left_tree_size = (
self.left_tree_size * 2 + 1
)
return self
else:
self.left = other.right
self.parent = None
if other.right:
other.right.parent = self
other.right = self
other.left_tree_size = (
other.left_tree_size * 2 + 1
)
return other
class BinomialHeap:
"""
Min-oriented priority queue implemented with the Binomial Heap data
structure implemented with the BinomialHeap class. It supports:
- Insert element in a heap with n elemnts: Guaranteed logn, amoratized 1
- Merge (meld) heaps of size m and n: O(logn + logm)
- Delete Min: O(logn)
- Peek (return min without deleting it): O(1)
Example:
Create a random permutation of 30 integers to be inserted and
19 of them deleted
>>> import numpy as np
>>> permutation = np.random.permutation(list(range(30)))
Create a Heap and insert the 30 integers
__init__() test
>>> first_heap = BinomialHeap()
30 inserts - insert() test
>>> for number in permutation:
... first_heap.insert(number)
Size test
>>> print(first_heap.size)
30
Deleting - delete() test
>>> for i in range(25):
... print(first_heap.deleteMin(), end=" ")
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
Create a new Heap
>>> second_heap = BinomialHeap()
>>> vals = [17, 20, 31, 34]
>>> for value in vals:
... second_heap.insert(value)
The heap should have the following structure:
17
/ \
# 31
/ \
20 34
/ \ / \
# # # #
preOrder() test
>>> print(second_heap.preOrder())
[(17, 0), ('#', 1), (31, 1), (20, 2), ('#', 3), ('#', 3), (34, 2), ('#', 3), ('#', 3)]
printing Heap - __str__() test
>>> print(second_heap)
17
-#
-31
--20
---#
---#
--34
---#
---#
mergeHeaps() test
>>> merged = second_heap.mergeHeaps(first_heap)
>>> merged.peek()
17
values in merged heap; (merge is inplace)
>>> while not first_heap.isEmpty():
... print(first_heap.deleteMin(), end=" ")
17 20 25 26 27 28 29 31 34
"""
def __init__(
self, bottom_root=None, min_node=None, heap_size=0
):
self.size = heap_size
self.bottom_root = bottom_root
self.min_node = min_node
def mergeHeaps(self, other):
"""
In-place merge of two binomial heaps.
Both of them become the resulting merged heap
"""
# Empty heaps corner cases
if other.size == 0:
return
if self.size == 0:
self.size = other.size
self.bottom_root = other.bottom_root
self.min_node = other.min_node
return
# Update size
self.size = self.size + other.size
# Update min.node
if self.min_node.val > other.min_node.val:
self.min_node = other.min_node
# Merge
# Order roots by left_subtree_size
combined_roots_list = []
i, j = self.bottom_root, other.bottom_root
while i or j:
if i and (
(not j)
or i.left_tree_size < j.left_tree_size
):
combined_roots_list.append((i, True))
i = i.parent
else:
combined_roots_list.append((j, False))
j = j.parent
# Insert links between them
for i in range(len(combined_roots_list) - 1):
if (
combined_roots_list[i][1]
!= combined_roots_list[i + 1][1]
):
combined_roots_list[i][
0
].parent = combined_roots_list[i + 1][0]
combined_roots_list[i + 1][
0
].left = combined_roots_list[i][0]
# Consecutively merge roots with same left_tree_size
i = combined_roots_list[0][0]
while i.parent:
if (
(
i.left_tree_size
== i.parent.left_tree_size
)
and (not i.parent.parent)
) or (
i.left_tree_size == i.parent.left_tree_size
and i.left_tree_size
!= i.parent.parent.left_tree_size
):
# Neighbouring Nodes
previous_node = i.left
next_node = i.parent.parent
# Merging trees
i = i.mergeTrees(i.parent)
# Updating links
i.left = previous_node
i.parent = next_node
if previous_node:
previous_node.parent = i
if next_node:
next_node.left = i
else:
i = i.parent
# Updating self.bottom_root
while i.left:
i = i.left
self.bottom_root = i
# Update other
other.size = self.size
other.bottom_root = self.bottom_root
other.min_node = self.min_node
# Return the merged heap
return self
def insert(self, val):
"""
insert a value in the heap
"""
if self.size == 0:
self.bottom_root = Node(val)
self.size = 1
self.min_node = self.bottom_root
else:
# Create new node
new_node = Node(val)
# Update size
self.size += 1
# update min_node
if val < self.min_node.val:
self.min_node = new_node
# Put new_node as a bottom_root in heap
self.bottom_root.left = new_node
new_node.parent = self.bottom_root
self.bottom_root = new_node
# Consecutively merge roots with same left_tree_size
while (
self.bottom_root.parent
and self.bottom_root.left_tree_size
== self.bottom_root.parent.left_tree_size
):
# Next node
next_node = self.bottom_root.parent.parent
# Merge
self.bottom_root = self.bottom_root.mergeTrees(
self.bottom_root.parent
)
# Update Links
self.bottom_root.parent = next_node
self.bottom_root.left = None
if next_node:
next_node.left = self.bottom_root
def peek(self):
"""
return min element without deleting it
"""
return self.min_node.val
def isEmpty(self):
return self.size == 0
def deleteMin(self):
"""
delete min element and return it
"""
# assert not self.isEmpty(), "Empty Heap"
# Save minimal value
min_value = self.min_node.val
# Last element in heap corner case
if self.size == 1:
# Update size
self.size = 0
# Update bottom root
self.bottom_root = None
# Update min_node
self.min_node = None
return min_value
# No right subtree corner case
# The structure of the tree implies that this should be the bottom root
# and there is at least one other root
if self.min_node.right == None:
# Update size
self.size -= 1
# Update bottom root
self.bottom_root = self.bottom_root.parent
self.bottom_root.left = None
# Update min_node
self.min_node = self.bottom_root
i = self.bottom_root.parent
while i:
if i.val < self.min_node.val:
self.min_node = i
i = i.parent
return min_value
# General case
# Find the BinomialHeap of the right subtree of min_node
bottom_of_new = self.min_node.right
bottom_of_new.parent = None
min_of_new = bottom_of_new
size_of_new = 1
# Size, min_node and bottom_root
while bottom_of_new.left:
size_of_new = size_of_new * 2 + 1
bottom_of_new = bottom_of_new.left
if bottom_of_new.val < min_of_new.val:
min_of_new = bottom_of_new
# Corner case of single root on top left path
if (not self.min_node.left) and (
not self.min_node.parent
):
self.size = size_of_new
self.bottom_root = bottom_of_new
self.min_node = min_of_new
# print("Single root, multiple nodes case")
return min_value
# Remaining cases
# Construct heap of right subtree
newHeap = BinomialHeap(
bottom_root=bottom_of_new,
min_node=min_of_new,
heap_size=size_of_new,
)
# Update size
self.size = self.size - 1 - size_of_new
# Neighbour nodes
previous_node = self.min_node.left
next_node = self.min_node.parent
# Initialize new bottom_root and min_node
self.min_node = previous_node or next_node
self.bottom_root = next_node
# Update links of previous_node and search below for new min_node and
# bottom_root
if previous_node:
previous_node.parent = next_node
# Update bottom_root and search for min_node below
self.bottom_root = previous_node
self.min_node = previous_node
while self.bottom_root.left:
self.bottom_root = self.bottom_root.left
if self.bottom_root.val < self.min_node.val:
self.min_node = self.bottom_root
if next_node:
next_node.left = previous_node
# Search for new min_node above min_node
i = next_node
while i:
if i.val < self.min_node.val:
self.min_node = i
i = i.parent
# Merge heaps
self.mergeHeaps(newHeap)
return min_value
def preOrder(self):
"""
Returns the Pre-order representation of the heap including
values of nodes plus their level distance from the root;
Empty nodes appear as #
"""
# Find top root
top_root = self.bottom_root
while top_root.parent:
top_root = top_root.parent
# preorder
heap_preOrder = []
self.__traversal(top_root, heap_preOrder)
return heap_preOrder
def __traversal(self, curr_node, preorder, level=0):
"""
Pre-order traversal of nodes
"""
if curr_node:
preorder.append((curr_node.val, level))
self.__traversal(
curr_node.left, preorder, level + 1
)
self.__traversal(
curr_node.right, preorder, level + 1
)
else:
preorder.append(("#", level))
def __str__(self):
"""
Overwriting str for a pre-order print of nodes in heap;
Performance is poor, so use only for small examples
"""
if self.isEmpty():
return ""
preorder_heap = self.preOrder()
return "\n".join(
("-" * level + str(value))
for value, level in preorder_heap
)
# Unit Tests
if __name__ == "__main__":
import doctest
doctest.testmod()
| [] | [] | [] |
archives/1098994933_python.zip | data_structures/heap/heap.py | #!/usr/bin/python
# This heap class start from here.
class Heap:
def __init__(self): # Default constructor of heap class.
self.h = []
self.currsize = 0
def leftChild(self,i):
if 2*i+1 < self.currsize:
return 2*i+1
return None
def rightChild(self,i):
if 2*i+2 < self.currsize:
return 2*i+2
return None
def maxHeapify(self,node):
if node < self.currsize:
m = node
lc = self.leftChild(node)
rc = self.rightChild(node)
if lc is not None and self.h[lc] > self.h[m]:
m = lc
if rc is not None and self.h[rc] > self.h[m]:
m = rc
if m!=node:
temp = self.h[node]
self.h[node] = self.h[m]
self.h[m] = temp
self.maxHeapify(m)
def buildHeap(self,a): #This function is used to build the heap from the data container 'a'.
self.currsize = len(a)
self.h = list(a)
for i in range(self.currsize//2,-1,-1):
self.maxHeapify(i)
def getMax(self): #This function is used to get maximum value from the heap.
if self.currsize >= 1:
me = self.h[0]
temp = self.h[0]
self.h[0] = self.h[self.currsize-1]
self.h[self.currsize-1] = temp
self.currsize -= 1
self.maxHeapify(0)
return me
return None
def heapSort(self): #This function is used to sort the heap.
size = self.currsize
while self.currsize-1 >= 0:
temp = self.h[0]
self.h[0] = self.h[self.currsize-1]
self.h[self.currsize-1] = temp
self.currsize -= 1
self.maxHeapify(0)
self.currsize = size
def insert(self,data): #This function is used to insert data in the heap.
self.h.append(data)
curr = self.currsize
self.currsize+=1
while self.h[curr] > self.h[curr/2]:
temp = self.h[curr/2]
self.h[curr/2] = self.h[curr]
self.h[curr] = temp
curr = curr/2
def display(self): #This function is used to print the heap.
print(self.h)
def main():
l = list(map(int, input().split()))
h = Heap()
h.buildHeap(l)
h.heapSort()
h.display()
if __name__=='__main__':
main()
| [] | [] | [] |
archives/1098994933_python.zip | data_structures/linked_list/__init__.py | class Node:
def __init__(self, item, next):
self.item = item
self.next = next
class LinkedList:
def __init__(self):
self.head = None
def add(self, item):
self.head = Node(item, self.head)
def remove(self):
if self.is_empty():
return None
else:
item = self.head.item
self.head = self.head.next
return item
def is_empty(self):
return self.head is None
| [] | [] | [] |
archives/1098994933_python.zip | data_structures/linked_list/doubly_linked_list.py | '''
- A linked list is similar to an array, it holds values. However, links in a linked list do not have indexes.
- This is an example of a double ended, doubly linked list.
- 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'''
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
self.tail = newLink
else:
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.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
print()
class Link:
next = None #This points to the link in front of the new link
previous = None #This points to the link behind the new link
def __init__(self, x):
self.value = x
def displayLink(self):
print("{}".format(self.value), end=" ")
| [] | [] | [] |
archives/1098994933_python.zip | data_structures/linked_list/is_palindrome.py | def is_palindrome(head):
if not head:
return True
# split the list to two parts
fast, slow = head.next, head
while fast and fast.next:
fast = fast.next.next
slow = slow.next
second = slow.next
slow.next = None # Don't forget here! But forget still works!
# reverse the second part
node = None
while second:
nxt = second.next
second.next = node
node = second
second = nxt
# compare two parts
# second part has the same or one less node
while node:
if node.val != head.val:
return False
node = node.next
head = head.next
return True
def is_palindrome_stack(head):
if not head or not head.next:
return True
# 1. Get the midpoint (slow)
slow = fast = cur = head
while fast and fast.next:
fast, slow = fast.next.next, slow.next
# 2. Push the second half into the stack
stack = [slow.val]
while slow.next:
slow = slow.next
stack.append(slow.val)
# 3. Comparison
while stack:
if stack.pop() != cur.val:
return False
cur = cur.next
return True
def is_palindrome_dict(head):
if not head or not head.next:
return True
d = {}
pos = 0
while head:
if head.val in d.keys():
d[head.val].append(pos)
else:
d[head.val] = [pos]
head = head.next
pos += 1
checksum = pos - 1
middle = 0
for v in d.values():
if len(v) % 2 != 0:
middle += 1
else:
step = 0
for i in range(0, len(v)):
if v[i] + v[len(v) - 1 - step] != checksum:
return False
step += 1
if middle > 1:
return False
return True
| [] | [] | [] |
archives/1098994933_python.zip | data_structures/linked_list/singly_linked_list.py | class Node: # create a Node
def __init__(self, data):
self.data = data # given data
self.next = None # given next to None
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:
temp = self.Head
while(temp.next != None): #traverse to last node
temp = temp.next
temp.next = Node(data) #create node & link to tail
def insert_head(self, data):
newNod = Node(data) # create a new node
if self.Head != None:
newNod.next = self.Head # link newNode to head
self.Head = newNod # make NewNode as Head
def printList(self): # print every node data
tamp = self.Head
while tamp is not None:
print(tamp.data)
tamp = tamp.next
def delete_head(self): # delete from head
temp = self.Head
if self.Head != None:
self.Head = self.Head.next
temp.next = None
return temp
def delete_tail(self): # delete from tail
tamp = self.Head
if self.Head != None:
if(self.Head.next is None): # if Head is the only Node in the Linked List
self.Head = None
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
return tamp
def isEmpty(self):
return self.Head is None # Return if Head is none
def reverse(self):
prev = None
current = self.Head
while current:
# Store the current node's next node.
next_node = current.next
# Make the current node's next point backwards
current.next = prev
# Make the previous node be the current node
prev = current
# Make the current node the next node (to progress iteration)
current = next_node
# Return prev in order to put the head at the end
self.Head = prev
def main():
A = Linked_List()
print("Inserting 1st at Head")
a1=input()
A.insert_head(a1)
print("Inserting 2nd at Head")
a2=input()
A.insert_head(a2)
print("\nPrint List : ")
A.printList()
print("\nInserting 1st at Tail")
a3=input()
A.insert_tail(a3)
print("Inserting 2nd at Tail")
a4=input()
A.insert_tail(a4)
print("\nPrint List : ")
A.printList()
print("\nDelete Head")
A.delete_head()
print("Delete Tail")
A.delete_tail()
print("\nPrint List : ")
A.printList()
print("\nReverse Linked List")
A.reverse()
print("\nPrint List : ")
A.printList()
if __name__ == '__main__':
main()
| [] | [] | [] |
archives/1098994933_python.zip | data_structures/linked_list/swap_nodes.py | class Node:
def __init__(self, data):
self.data = data;
self.next = None
class Linkedlist:
def __init__(self):
self.head = None
def print_list(self):
temp = self.head
while temp is not None:
print(temp.data)
temp = temp.next
# adding nodes
def push(self, new_data):
new_node = Node(new_data)
new_node.next = self.head
self.head = new_node
# swapping nodes
def swapNodes(self, d1, d2):
prevD1 = None
prevD2 = None
if d1 == d2:
return
else:
# find d1
D1 = self.head
while D1 is not None and D1.data != d1:
prevD1 = D1
D1 = D1.next
# find d2
D2 = self.head
while D2 is not None and D2.data != d2:
prevD2 = D2
D2 = D2.next
if D1 is None and D2 is None:
return
# if D1 is head
if prevD1 is not None:
prevD1.next = D2
else:
self.head = D2
# if D2 is head
if prevD2 is not None:
prevD2.next = D1
else:
self.head = D1
temp = D1.next
D1.next = D2.next
D2.next = temp
# swapping code ends here
if __name__ == '__main__':
list = Linkedlist()
list.push(5)
list.push(4)
list.push(3)
list.push(2)
list.push(1)
list.print_list()
list.swapNodes(1, 4)
print("After swapping")
list.print_list()
| [] | [] | [] |
archives/1098994933_python.zip | data_structures/queue/double_ended_queue.py | # Python code to demonstrate working of
# extend(), extendleft(), rotate(), reverse()
# importing "collections" for deque operations
import collections
# initializing deque
de = collections.deque([1, 2, 3,])
# using extend() to add numbers to right end
# adds 4,5,6 to right end
de.extend([4,5,6])
# printing modified deque
print("The deque after extending deque at end is : ")
print(de)
# using extendleft() to add numbers to left end
# adds 7,8,9 to right end
de.extendleft([7,8,9])
# printing modified deque
print("The deque after extending deque at beginning is : ")
print(de)
# using rotate() to rotate the deque
# rotates by 3 to left
de.rotate(-3)
# printing modified deque
print("The deque after rotating deque is : ")
print(de)
# using reverse() to reverse the deque
de.reverse()
# printing modified deque
print("The deque after reversing deque is : ")
print(de)
| [] | [] | [] |
archives/1098994933_python.zip | data_structures/queue/queue_on_list.py | """Queue represented by a python list"""
class Queue():
def __init__(self):
self.entries = []
self.length = 0
self.front=0
def __str__(self):
printed = '<' + str(self.entries)[1:-1] + '>'
return printed
"""Enqueues {@code item}
@param item
item to enqueue"""
def put(self, item):
self.entries.append(item)
self.length = self.length + 1
"""Dequeues {@code item}
@requirement: |self.length| > 0
@return dequeued
item that was dequeued"""
def get(self):
self.length = self.length - 1
dequeued = self.entries[self.front]
#self.front-=1
#self.entries = self.entries[self.front:]
self.entries = self.entries[1:]
return dequeued
"""Rotates the queue {@code rotation} times
@param rotation
number of times to rotate queue"""
def rotate(self, rotation):
for i in range(rotation):
self.put(self.get())
"""Enqueues {@code item}
@return item at front of self.entries"""
def front(self):
return self.entries[0]
"""Returns the length of this.entries"""
def size(self):
return self.length
| [] | [] | [] |
archives/1098994933_python.zip | data_structures/queue/queue_on_pseudo_stack.py | """Queue represented by a pseudo stack (represented by a list with pop and append)"""
class Queue():
def __init__(self):
self.stack = []
self.length = 0
def __str__(self):
printed = '<' + str(self.stack)[1:-1] + '>'
return printed
"""Enqueues {@code item}
@param item
item to enqueue"""
def put(self, item):
self.stack.append(item)
self.length = self.length + 1
"""Dequeues {@code item}
@requirement: |self.length| > 0
@return dequeued
item that was dequeued"""
def get(self):
self.rotate(1)
dequeued = self.stack[self.length-1]
self.stack = self.stack[:-1]
self.rotate(self.length-1)
self.length = self.length -1
return dequeued
"""Rotates the queue {@code rotation} times
@param rotation
number of times to rotate queue"""
def rotate(self, rotation):
for i in range(rotation):
temp = self.stack[0]
self.stack = self.stack[1:]
self.put(temp)
self.length = self.length - 1
"""Reports item at the front of self
@return item at front of self.stack"""
def front(self):
front = self.get()
self.put(front)
self.rotate(self.length-1)
return front
"""Returns the length of this.stack"""
def size(self):
return self.length
| [] | [] | [] |
archives/1098994933_python.zip | data_structures/stacks/__init__.py | class Stack:
def __init__(self):
self.stack = []
self.top = 0
def is_empty(self):
return (self.top == 0)
def push(self, item):
if self.top < len(self.stack):
self.stack[self.top] = item
else:
self.stack.append(item)
self.top += 1
def pop(self):
if self.is_empty():
return None
else:
self.top -= 1
return self.stack[self.top]
| [] | [] | [] |
archives/1098994933_python.zip | data_structures/stacks/balanced_parentheses.py | from .stack import Stack
__author__ = 'Omkar Pathak'
def balanced_parentheses(parentheses):
""" Use a stack to check if a string of parentheses is balanced."""
stack = Stack(len(parentheses))
for parenthesis in parentheses:
if parenthesis == '(':
stack.push(parenthesis)
elif parenthesis == ')':
if stack.is_empty():
return False
stack.pop()
return stack.is_empty()
if __name__ == '__main__':
examples = ['((()))', '((())', '(()))']
print('Balanced parentheses demonstration:\n')
for example in examples:
print(example + ': ' + str(balanced_parentheses(example)))
| [] | [] | [] |
archives/1098994933_python.zip | data_structures/stacks/infix_to_postfix_conversion.py | import string
from .stack import Stack
__author__ = 'Omkar Pathak'
def is_operand(char):
return char in string.ascii_letters or char in string.digits
def precedence(char):
""" Return integer value representing an operator's precedence, or
order of operation.
https://en.wikipedia.org/wiki/Order_of_operations
"""
dictionary = {'+': 1, '-': 1,
'*': 2, '/': 2,
'^': 3}
return dictionary.get(char, -1)
def infix_to_postfix(expression):
""" Convert infix notation to postfix notation using the Shunting-yard
algorithm.
https://en.wikipedia.org/wiki/Shunting-yard_algorithm
https://en.wikipedia.org/wiki/Infix_notation
https://en.wikipedia.org/wiki/Reverse_Polish_notation
"""
stack = Stack(len(expression))
postfix = []
for char in expression:
if is_operand(char):
postfix.append(char)
elif char not in {'(', ')'}:
while (not stack.is_empty()
and precedence(char) <= precedence(stack.peek())):
postfix.append(stack.pop())
stack.push(char)
elif char == '(':
stack.push(char)
elif char == ')':
while not stack.is_empty() and stack.peek() != '(':
postfix.append(stack.pop())
# Pop '(' from stack. If there is no '(', there is a mismatched
# parentheses.
if stack.peek() != '(':
raise ValueError('Mismatched parentheses')
stack.pop()
while not stack.is_empty():
postfix.append(stack.pop())
return ' '.join(postfix)
if __name__ == '__main__':
expression = 'a+b*(c^d-e)^(f+g*h)-i'
print('Infix to Postfix Notation demonstration:\n')
print('Infix notation: ' + expression)
print('Postfix notation: ' + infix_to_postfix(expression))
| [] | [] | [] |
archives/1098994933_python.zip | data_structures/stacks/infix_to_prefix_conversion.py | """
Output:
Enter an Infix Equation = a + b ^c
Symbol | Stack | Postfix
----------------------------
c | | c
^ | ^ | c
b | ^ | cb
+ | + | cb^
a | + | cb^a
| | cb^a+
a+b^c (Infix) -> +a^bc (Prefix)
"""
def infix_2_postfix(Infix):
Stack = []
Postfix = []
priority = {'^':3, '*':2, '/':2, '%':2, '+':1, '-':1} # Priority of each operator
print_width = len(Infix) if(len(Infix)>7) else 7
# Print table header for output
print('Symbol'.center(8), 'Stack'.center(print_width), 'Postfix'.center(print_width), sep = " | ")
print('-'*(print_width*3+7))
for x in Infix:
if(x.isalpha() or x.isdigit()): Postfix.append(x) # if x is Alphabet / Digit, add it to Postfix
elif(x == '('): Stack.append(x) # if x is "(" push to Stack
elif(x == ')'): # if x is ")" pop stack until "(" is encountered
while(Stack[-1] != '('):
Postfix.append( Stack.pop() ) #Pop stack & add the content to Postfix
Stack.pop()
else:
if(len(Stack)==0): Stack.append(x) #If stack is empty, push x to stack
else:
while( len(Stack) > 0 and priority[x] <= priority[Stack[-1]]): # while priority of x is not greater than priority of element in the stack
Postfix.append( Stack.pop() ) # pop stack & add to Postfix
Stack.append(x) # push x to stack
print(x.center(8), (''.join(Stack)).ljust(print_width), (''.join(Postfix)).ljust(print_width), sep = " | ") # Output in tabular format
while(len(Stack) > 0): # while stack is not empty
Postfix.append( Stack.pop() ) # pop stack & add to Postfix
print(' '.center(8), (''.join(Stack)).ljust(print_width), (''.join(Postfix)).ljust(print_width), sep = " | ") # Output in tabular format
return "".join(Postfix) # return Postfix as str
def infix_2_prefix(Infix):
Infix = list(Infix[::-1]) # reverse the infix equation
for i in range(len(Infix)):
if(Infix[i] == '('): Infix[i] = ')' # change "(" to ")"
elif(Infix[i] == ')'): Infix[i] = '(' # change ")" to "("
return (infix_2_postfix("".join(Infix)))[::-1] # call infix_2_postfix on Infix, return reverse of Postfix
if __name__ == "__main__":
Infix = input("\nEnter an Infix Equation = ") #Input an Infix equation
Infix = "".join(Infix.split()) #Remove spaces from the input
print("\n\t", Infix, "(Infix) -> ", infix_2_prefix(Infix), "(Prefix)")
| [] | [] | [] |
archives/1098994933_python.zip | data_structures/stacks/next_greater_element.py | # 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)
| [] | [] | [] |
archives/1098994933_python.zip | data_structures/stacks/postfix_evaluation.py | """
Output:
Enter a Postfix Equation (space separated) = 5 6 9 * +
Symbol | Action | Stack
-----------------------------------
5 | push(5) | 5
6 | push(6) | 5,6
9 | push(9) | 5,6,9
| pop(9) | 5,6
| pop(6) | 5
* | push(6*9) | 5,54
| pop(54) | 5
| pop(5) |
+ | push(5+54) | 59
Result = 59
"""
import operator as op
def Solve(Postfix):
Stack = []
Div = lambda x, y: int(x/y) # integer division operation
Opr = {'^':op.pow, '*':op.mul, '/':Div, '+':op.add, '-':op.sub} # operators & their respective operation
# print table header
print('Symbol'.center(8), 'Action'.center(12), 'Stack', sep = " | ")
print('-'*(30+len(Postfix)))
for x in Postfix:
if( x.isdigit() ): # if x in digit
Stack.append(x) # append x to stack
print(x.rjust(8), ('push('+x+')').ljust(12), ','.join(Stack), sep = " | ") # output in tabular format
else:
B = Stack.pop() # pop stack
print("".rjust(8), ('pop('+B+')').ljust(12), ','.join(Stack), sep = " | ") # output in tabular format
A = Stack.pop() # pop stack
print("".rjust(8), ('pop('+A+')').ljust(12), ','.join(Stack), sep = " | ") # output in tabular format
Stack.append( str(Opr[x](int(A), int(B))) ) # evaluate the 2 values poped from stack & push result to stack
print(x.rjust(8), ('push('+A+x+B+')').ljust(12), ','.join(Stack), sep = " | ") # output in tabular format
return int(Stack[0])
if __name__ == "__main__":
Postfix = input("\n\nEnter a Postfix Equation (space separated) = ").split(' ')
print("\n\tResult = ", Solve(Postfix))
| [] | [] | [] |
archives/1098994933_python.zip | data_structures/stacks/stack.py | __author__ = 'Omkar Pathak'
class Stack(object):
""" A stack is an abstract data type that serves as a collection of
elements with two principal operations: push() and pop(). push() adds an
element to the top of the stack, and pop() removes an element from the top
of a stack. The order in which elements come off of a stack are
Last In, First Out (LIFO).
https://en.wikipedia.org/wiki/Stack_(abstract_data_type)
"""
def __init__(self, limit=10):
self.stack = []
self.limit = limit
def __bool__(self):
return bool(self.stack)
def __str__(self):
return str(self.stack)
def push(self, data):
""" Push an element to the top of the stack."""
if len(self.stack) >= self.limit:
raise StackOverflowError
self.stack.append(data)
def pop(self):
""" Pop an element off of the top of the stack."""
if self.stack:
return self.stack.pop()
else:
raise IndexError('pop from an empty stack')
def peek(self):
""" Peek at the top-most element of the stack."""
if self.stack:
return self.stack[-1]
def is_empty(self):
""" Check if a stack is empty."""
return not bool(self.stack)
def size(self):
""" Return the size of the stack."""
return len(self.stack)
class StackOverflowError(BaseException):
pass
if __name__ == '__main__':
stack = Stack()
for i in range(10):
stack.push(i)
print('Stack demonstration:\n')
print('Initial stack: ' + str(stack))
print('pop(): ' + str(stack.pop()))
print('After pop(), the stack is now: ' + str(stack))
print('peek(): ' + str(stack.peek()))
stack.push(100)
print('After push(100), the stack is now: ' + str(stack))
print('is_empty(): ' + str(stack.is_empty()))
print('size(): ' + str(stack.size()))
| [] | [] | [] |
archives/1098994933_python.zip | data_structures/stacks/stock_span_problem.py | '''
The stock span problem is a financial problem where we have a series of n daily
price quotes for a stock and we need to calculate span of stock's price for all n days.
The span Si of the stock's price on a given day i is defined as the maximum
number of consecutive days just before the given day, for which the price of the stock
on the current day is less than or equal to its price on the given day.
'''
def calculateSpan(price, S):
n = len(price)
# Create a stack and push index of fist element to it
st = []
st.append(0)
# Span value of first element is always 1
S[0] = 1
# Calculate span values for rest of the elements
for i in range(1, n):
# Pop elements from stack whlie stack is not
# empty and top of stack is smaller than price[i]
while( len(st) > 0 and price[st[0]] <= price[i]):
st.pop()
# If stack becomes empty, then price[i] is greater
# than all elements on left of it, i.e. price[0],
# price[1], ..price[i-1]. Else the price[i] is
# greater than elements after top of stack
S[i] = i+1 if len(st) <= 0 else (i - st[0])
# Push this element to stack
st.append(i)
# A utility function to print elements of array
def printArray(arr, n):
for i in range(0,n):
print(arr[i],end =" ")
# Driver program to test above function
price = [10, 4, 5, 90, 120, 80]
S = [0 for i in range(len(price)+1)]
# Fill the span values in array S[]
calculateSpan(price, S)
# Print the calculated span values
printArray(S, len(price))
| [] | [] | [] |
archives/1098994933_python.zip | data_structures/trie/trie.py | """
A Trie/Prefix Tree is a kind of search tree used to provide quick lookup
of words/patterns in a set of words. A basic Trie however has O(n^2) space complexity
making it impractical in practice. It however provides O(max(search_string, length of longest word)) lookup
time making it an optimal approach when space is not an issue.
"""
class TrieNode:
def __init__(self):
self.nodes = dict() # Mapping from char to TrieNode
self.is_leaf = False
def insert_many(self, words: [str]): # noqa: E999 This syntax is Python 3 only
"""
Inserts a list of words into the Trie
:param words: list of string words
:return: None
"""
for word in words:
self.insert(word)
def insert(self, word: str): # noqa: E999 This syntax is Python 3 only
"""
Inserts a word into the Trie
:param word: word to be inserted
:return: None
"""
curr = self
for char in word:
if char not in curr.nodes:
curr.nodes[char] = TrieNode()
curr = curr.nodes[char]
curr.is_leaf = True
def find(self, word: str) -> bool: # noqa: E999 This syntax is Python 3 only
"""
Tries to find word in a Trie
:param word: word to look for
:return: Returns True if word is found, False otherwise
"""
curr = self
for char in word:
if char not in curr.nodes:
return False
curr = curr.nodes[char]
return curr.is_leaf
def print_words(node: TrieNode, word: str): # noqa: E999 This syntax is Python 3 only
"""
Prints all the words in a Trie
:param node: root node of Trie
:param word: Word variable should be empty at start
:return: None
"""
if node.is_leaf:
print(word, end=' ')
for key, value in node.nodes.items():
print_words(value, word + key)
def test():
words = ['banana', 'bananas', 'bandana', 'band', 'apple', 'all', 'beast']
root = TrieNode()
root.insert_many(words)
# print_words(root, '')
assert root.find('banana')
assert not root.find('bandanas')
assert not root.find('apps')
assert root.find('apple')
test()
| [
"[str]",
"str",
"str",
"TrieNode",
"str"
] | [
505,
776,
1170,
1592,
1608
] | [
510,
779,
1173,
1600,
1611
] |
archives/1098994933_python.zip | digital_image_processing/__init__.py | [] | [] | [] |
|
archives/1098994933_python.zip | digital_image_processing/change_contrast.py | """
Changing contrast with PIL
This algorithm is used in
https://noivce.pythonanywhere.com/ python web app.
python/black: True
flake8 : True
"""
from PIL import Image
def change_contrast(img: Image, level: float) -> Image:
"""
Function to change contrast
"""
factor = (259 * (level + 255)) / (255 * (259 - level))
def contrast(c: int) -> float:
"""
Fundamental Transformation/Operation that'll be performed on
every bit.
"""
return 128 + factor * (c - 128)
return img.point(contrast)
if __name__ == "__main__":
# Load image
with Image.open("image_data/lena.jpg") as img:
# Change contrast to 170
cont_img = change_contrast(img, 170)
cont_img.save("image_data/lena_high_contrast.png", format="png")
| [
"Image",
"float",
"int"
] | [
210,
224,
375
] | [
215,
229,
378
] |
archives/1098994933_python.zip | digital_image_processing/edge_detection/__init__.py | [] | [] | [] |
|
archives/1098994933_python.zip | digital_image_processing/edge_detection/canny.py | import cv2
import numpy as np
from digital_image_processing.filters.convolve import img_convolve
from digital_image_processing.filters.sobel_filter import sobel_filter
PI = 180
def gen_gaussian_kernel(k_size, sigma):
center = k_size // 2
x, y = np.mgrid[0 - center:k_size - center, 0 - center:k_size - center]
g = 1 / (2 * np.pi * sigma) * np.exp(-(np.square(x) + np.square(y)) / (2 * np.square(sigma)))
return g
def canny(image, threshold_low=15, threshold_high=30, weak=128, strong=255):
image_row, image_col = image.shape[0], image.shape[1]
# gaussian_filter
gaussian_out = img_convolve(image, gen_gaussian_kernel(9, sigma=1.4))
# get the gradient and degree by sobel_filter
sobel_grad, sobel_theta = sobel_filter(gaussian_out)
gradient_direction = np.rad2deg(sobel_theta)
gradient_direction += PI
dst = np.zeros((image_row, image_col))
"""
Non-maximum suppression. If the edge strength of the current pixel is the largest compared to the other pixels
in the mask with the same direction, the value will be preserved. Otherwise, the value will be suppressed.
"""
for row in range(1, image_row - 1):
for col in range(1, image_col - 1):
direction = gradient_direction[row, col]
if (
0 <= direction < 22.5
or 15 * PI / 8 <= direction <= 2 * PI
or 7 * PI / 8 <= direction <= 9 * PI / 8
):
W = sobel_grad[row, col - 1]
E = sobel_grad[row, col + 1]
if sobel_grad[row, col] >= W and sobel_grad[row, col] >= E:
dst[row, col] = sobel_grad[row, col]
elif (PI / 8 <= direction < 3 * PI / 8) or (9 * PI / 8 <= direction < 11 * PI / 8):
SW = sobel_grad[row + 1, col - 1]
NE = sobel_grad[row - 1, col + 1]
if sobel_grad[row, col] >= SW and sobel_grad[row, col] >= NE:
dst[row, col] = sobel_grad[row, col]
elif (3 * PI / 8 <= direction < 5 * PI / 8) or (11 * PI / 8 <= direction < 13 * PI / 8):
N = sobel_grad[row - 1, col]
S = sobel_grad[row + 1, col]
if sobel_grad[row, col] >= N and sobel_grad[row, col] >= S:
dst[row, col] = sobel_grad[row, col]
elif (5 * PI / 8 <= direction < 7 * PI / 8) or (13 * PI / 8 <= direction < 15 * PI / 8):
NW = sobel_grad[row - 1, col - 1]
SE = sobel_grad[row + 1, col + 1]
if sobel_grad[row, col] >= NW and sobel_grad[row, col] >= SE:
dst[row, col] = sobel_grad[row, col]
"""
High-Low threshold detection. If an edge pixel’s gradient value is higher than the high threshold
value, it is marked as a strong edge pixel. If an edge pixel’s gradient value is smaller than the high
threshold value and larger than the low threshold value, it is marked as a weak edge pixel. If an edge
pixel's value is smaller than the low threshold value, it will be suppressed.
"""
if dst[row, col] >= threshold_high:
dst[row, col] = strong
elif dst[row, col] <= threshold_low:
dst[row, col] = 0
else:
dst[row, col] = weak
"""
Edge tracking. Usually a weak edge pixel caused from true edges will be connected to a strong edge pixel while
noise responses are unconnected. As long as there is one strong edge pixel that is involved in its 8-connected
neighborhood, that weak edge point can be identified as one that should be preserved.
"""
for row in range(1, image_row):
for col in range(1, image_col):
if dst[row, col] == weak:
if 255 in (
dst[row, col + 1],
dst[row, col - 1],
dst[row - 1, col],
dst[row + 1, col],
dst[row - 1, col - 1],
dst[row + 1, col - 1],
dst[row - 1, col + 1],
dst[row + 1, col + 1],
):
dst[row, col] = strong
else:
dst[row, col] = 0
return dst
if __name__ == '__main__':
# read original image in gray mode
lena = cv2.imread(r'../image_data/lena.jpg', 0)
# canny edge detection
canny_dst = canny(lena)
cv2.imshow('canny', canny_dst)
cv2.waitKey(0)
| [] | [] | [] |
archives/1098994933_python.zip | digital_image_processing/filters/__init__.py | [] | [] | [] |
|
archives/1098994933_python.zip | digital_image_processing/filters/convolve.py | # @Author : lightXu
# @File : convolve.py
# @Time : 2019/7/8 0008 下午 16:13
from cv2 import imread, cvtColor, COLOR_BGR2GRAY, imshow, waitKey
from numpy import array, zeros, ravel, pad, dot, uint8
def im2col(image, block_size):
rows, cols = image.shape
dst_height = cols - block_size[1] + 1
dst_width = rows - block_size[0] + 1
image_array = zeros((dst_height * dst_width, block_size[1] * block_size[0]))
row = 0
for i in range(0, dst_height):
for j in range(0, dst_width):
window = ravel(image[i:i + block_size[0], j:j + block_size[1]])
image_array[row, :] = window
row += 1
return image_array
def img_convolve(image, filter_kernel):
height, width = image.shape[0], image.shape[1]
k_size = filter_kernel.shape[0]
pad_size = k_size//2
# Pads image with the edge values of array.
image_tmp = pad(image, pad_size, mode='edge')
# im2col, turn the k_size*k_size pixels into a row and np.vstack all rows
image_array = im2col(image_tmp, (k_size, k_size))
# turn the kernel into shape(k*k, 1)
kernel_array = ravel(filter_kernel)
# reshape and get the dst image
dst = dot(image_array, kernel_array).reshape(height, width)
return dst
if __name__ == '__main__':
# read original image
img = imread(r'../image_data/lena.jpg')
# turn image in gray scale value
gray = cvtColor(img, COLOR_BGR2GRAY)
# Laplace operator
Laplace_kernel = array([[0, 1, 0], [1, -4, 1], [0, 1, 0]])
out = img_convolve(gray, Laplace_kernel).astype(uint8)
imshow('Laplacian', out)
waitKey(0)
| [] | [] | [] |
archives/1098994933_python.zip | digital_image_processing/filters/gaussian_filter.py | """
Implementation of gaussian filter algorithm
"""
from cv2 import imread, cvtColor, COLOR_BGR2GRAY, imshow, waitKey
from numpy import pi, mgrid, exp, square, zeros, ravel, dot, uint8
def gen_gaussian_kernel(k_size, sigma):
center = k_size // 2
x, y = mgrid[0-center:k_size-center, 0-center:k_size-center]
g = 1/(2*pi*sigma) * exp(-(square(x) + square(y))/(2*square(sigma)))
return g
def gaussian_filter(image, k_size, sigma):
height, width = image.shape[0], image.shape[1]
# dst image height and width
dst_height = height-k_size+1
dst_width = width-k_size+1
# im2col, turn the k_size*k_size pixels into a row and np.vstack all rows
image_array = zeros((dst_height*dst_width, k_size*k_size))
row = 0
for i in range(0, dst_height):
for j in range(0, dst_width):
window = ravel(image[i:i + k_size, j:j + k_size])
image_array[row, :] = window
row += 1
# turn the kernel into shape(k*k, 1)
gaussian_kernel = gen_gaussian_kernel(k_size, sigma)
filter_array = ravel(gaussian_kernel)
# reshape and get the dst image
dst = dot(image_array, filter_array).reshape(dst_height, dst_width).astype(uint8)
return dst
if __name__ == '__main__':
# read original image
img = imread(r'../image_data/lena.jpg')
# turn image in gray scale value
gray = cvtColor(img, COLOR_BGR2GRAY)
# get values with two different mask size
gaussian3x3 = gaussian_filter(gray, 3, sigma=1)
gaussian5x5 = gaussian_filter(gray, 5, sigma=0.8)
# show result images
imshow('gaussian filter with 3x3 mask', gaussian3x3)
imshow('gaussian filter with 5x5 mask', gaussian5x5)
waitKey()
| [] | [] | [] |
archives/1098994933_python.zip | digital_image_processing/filters/median_filter.py | """
Implementation of median filter algorithm
"""
from cv2 import imread, cvtColor, COLOR_BGR2GRAY, imshow, waitKey
from numpy import zeros_like, ravel, sort, multiply, divide, int8
def median_filter(gray_img, mask=3):
"""
:param gray_img: gray image
:param mask: mask size
:return: image with median filter
"""
# set image borders
bd = int(mask / 2)
# copy image size
median_img = zeros_like(gray_img)
for i in range(bd, gray_img.shape[0] - bd):
for j in range(bd, gray_img.shape[1] - bd):
# get mask according with mask
kernel = ravel(gray_img[i - bd:i + bd + 1, j - bd:j + bd + 1])
# calculate mask median
median = sort(kernel)[int8(divide((multiply(mask, mask)), 2) + 1)]
median_img[i, j] = median
return median_img
if __name__ == '__main__':
# read original image
img = imread('../image_data/lena.jpg')
# turn image in gray scale value
gray = cvtColor(img, COLOR_BGR2GRAY)
# get values with two different mask size
median3x3 = median_filter(gray, 3)
median5x5 = median_filter(gray, 5)
# show result images
imshow('median filter with 3x3 mask', median3x3)
imshow('median filter with 5x5 mask', median5x5)
waitKey(0)
| [] | [] | [] |
archives/1098994933_python.zip | digital_image_processing/filters/sobel_filter.py | # @Author : lightXu
# @File : sobel_filter.py
# @Time : 2019/7/8 0008 下午 16:26
import numpy as np
from cv2 import imread, cvtColor, COLOR_BGR2GRAY, imshow, waitKey
from digital_image_processing.filters.convolve import img_convolve
def sobel_filter(image):
kernel_x = np.array([[-1, 0, 1], [-2, 0, 2], [-1, 0, 1]])
kernel_y = np.array([[1, 2, 1], [0, 0, 0], [-1, -2, -1]])
dst_x = np.abs(img_convolve(image, kernel_x))
dst_y = np.abs(img_convolve(image, kernel_y))
# modify the pix within [0, 255]
dst_x = dst_x * 255/np.max(dst_x)
dst_y = dst_y * 255/np.max(dst_y)
dst_xy = np.sqrt((np.square(dst_x)) + (np.square(dst_y)))
dst_xy = dst_xy * 255/np.max(dst_xy)
dst = dst_xy.astype(np.uint8)
theta = np.arctan2(dst_y, dst_x)
return dst, theta
if __name__ == '__main__':
# read original image
img = imread('../image_data/lena.jpg')
# turn image in gray scale value
gray = cvtColor(img, COLOR_BGR2GRAY)
sobel_grad, sobel_theta = sobel_filter(gray)
# show result images
imshow('sobel filter', sobel_grad)
imshow('sobel theta', sobel_theta)
waitKey(0)
| [] | [] | [] |
archives/1098994933_python.zip | digital_image_processing/test_digital_image_processing.py | """
PyTest's for Digital Image Processing
"""
import digital_image_processing.edge_detection.canny as canny
import digital_image_processing.filters.gaussian_filter as gg
import digital_image_processing.filters.median_filter as med
import digital_image_processing.filters.sobel_filter as sob
import digital_image_processing.filters.convolve as conv
import digital_image_processing.change_contrast as cc
from cv2 import imread, cvtColor, COLOR_BGR2GRAY
from numpy import array, uint8
from PIL import Image
img = imread(r"digital_image_processing/image_data/lena.jpg")
gray = cvtColor(img, COLOR_BGR2GRAY)
# Test: change_contrast()
def test_change_contrast():
with Image.open("digital_image_processing/image_data/lena.jpg") as img:
# Work around assertion for response
assert str(cc.change_contrast(img, 110)).startswith(
"<PIL.Image.Image image mode=RGB size=512x512 at"
)
# canny.gen_gaussian_kernel()
def test_gen_gaussian_kernel():
resp = canny.gen_gaussian_kernel(9, sigma=1.4)
# Assert ambiguous array
assert resp.all()
# canny.py
def test_canny():
canny_img = imread("digital_image_processing/image_data/lena.jpg", 0)
# assert ambiguos array for all == True
assert canny_img.all()
canny_array = canny.canny(canny_img)
# assert canny array for at least one True
assert canny_array.any()
# filters/gaussian_filter.py
def test_gen_gaussian_kernel_filter():
assert gg.gaussian_filter(gray, 5, sigma=0.9).all()
def test_convolve_filter():
# laplace diagonals
Laplace = array([[0.25, 0.5, 0.25], [0.5, -3, 0.5], [0.25, 0.5, 0.25]])
res = conv.img_convolve(gray, Laplace).astype(uint8)
assert res.any()
def test_median_filter():
assert med.median_filter(gray, 3).any()
def test_sobel_filter():
grad, theta = sob.sobel_filter(gray)
assert grad.any() and theta.any()
| [] | [] | [] |
archives/1098994933_python.zip | divide_and_conquer/closest_pair_of_points.py | """
The algorithm finds distance between closest pair of points
in the given n points.
Approach used -> Divide and conquer
The points are sorted based on Xco-ords and
then based on Yco-ords separately.
And by applying divide and conquer approach,
minimum distance is obtained recursively.
>> Closest points can lie on different sides of partition.
This case handled by forming a strip of points
whose Xco-ords distance is less than closest_pair_dis
from mid-point's Xco-ords. Points sorted based on Yco-ords
are used in this step to reduce sorting time.
Closest pair distance is found in the strip of points. (closest_in_strip)
min(closest_pair_dis, closest_in_strip) would be the final answer.
Time complexity: O(n * log n)
"""
def euclidean_distance_sqr(point1, point2):
"""
>>> euclidean_distance_sqr([1,2],[2,4])
5
"""
return (point1[0] - point2[0]) ** 2 + (point1[1] - point2[1]) ** 2
def column_based_sort(array, column = 0):
"""
>>> column_based_sort([(5, 1), (4, 2), (3, 0)], 1)
[(3, 0), (5, 1), (4, 2)]
"""
return sorted(array, key = lambda x: x[column])
def dis_between_closest_pair(points, points_counts, min_dis = float("inf")):
"""
brute force approach to find distance between closest pair points
Parameters :
points, points_count, min_dis (list(tuple(int, int)), int, int)
Returns :
min_dis (float): distance between closest pair of points
>>> dis_between_closest_pair([[1,2],[2,4],[5,7],[8,9],[11,0]],5)
5
"""
for i in range(points_counts - 1):
for j in range(i+1, points_counts):
current_dis = euclidean_distance_sqr(points[i], points[j])
if current_dis < min_dis:
min_dis = current_dis
return min_dis
def dis_between_closest_in_strip(points, points_counts, min_dis = float("inf")):
"""
closest pair of points in strip
Parameters :
points, points_count, min_dis (list(tuple(int, int)), int, int)
Returns :
min_dis (float): distance btw closest pair of points in the strip (< min_dis)
>>> dis_between_closest_in_strip([[1,2],[2,4],[5,7],[8,9],[11,0]],5)
85
"""
for i in range(min(6, points_counts - 1), points_counts):
for j in range(max(0, i-6), i):
current_dis = euclidean_distance_sqr(points[i], points[j])
if current_dis < min_dis:
min_dis = current_dis
return min_dis
def closest_pair_of_points_sqr(points_sorted_on_x, points_sorted_on_y, points_counts):
""" divide and conquer approach
Parameters :
points, points_count (list(tuple(int, int)), int)
Returns :
(float): distance btw closest pair of points
>>> closest_pair_of_points_sqr([(1, 2), (3, 4)], [(5, 6), (7, 8)], 2)
8
"""
# base case
if points_counts <= 3:
return dis_between_closest_pair(points_sorted_on_x, points_counts)
# recursion
mid = points_counts//2
closest_in_left = closest_pair_of_points_sqr(points_sorted_on_x,
points_sorted_on_y[:mid],
mid)
closest_in_right = closest_pair_of_points_sqr(points_sorted_on_y,
points_sorted_on_y[mid:],
points_counts - mid)
closest_pair_dis = min(closest_in_left, closest_in_right)
"""
cross_strip contains the points, whose Xcoords are at a
distance(< closest_pair_dis) from mid's Xcoord
"""
cross_strip = []
for point in points_sorted_on_x:
if abs(point[0] - points_sorted_on_x[mid][0]) < closest_pair_dis:
cross_strip.append(point)
closest_in_strip = dis_between_closest_in_strip(cross_strip,
len(cross_strip), closest_pair_dis)
return min(closest_pair_dis, closest_in_strip)
def closest_pair_of_points(points, points_counts):
"""
>>> closest_pair_of_points([(2, 3), (12, 30)], len([(2, 3), (12, 30)]))
28.792360097775937
"""
points_sorted_on_x = column_based_sort(points, column = 0)
points_sorted_on_y = column_based_sort(points, column = 1)
return (closest_pair_of_points_sqr(points_sorted_on_x,
points_sorted_on_y,
points_counts)) ** 0.5
if __name__ == "__main__":
points = [(2, 3), (12, 30), (40, 50), (5, 1), (12, 10), (3, 4)]
print("Distance:", closest_pair_of_points(points, len(points)))
| [] | [] | [] |
archives/1098994933_python.zip | divide_and_conquer/convex_hull.py | from numbers import Number
"""
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.
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 log(n))
There are other several other algorithms for the convex hull problem
which have not been implemented here, yet.
"""
class Point:
"""
Defines a 2-d point for use by all convex-hull algorithms.
Parameters
----------
x: an int or a float, the x-coordinate of the 2-d point
y: an int or a float, the y-coordinate of the 2-d point
Examples
--------
>>> Point(1, 2)
(1, 2)
>>> Point("1", "2")
(1.0, 2.0)
>>> Point(1, 2) > Point(0, 1)
True
>>> Point(1, 1) == Point(1, 1)
True
>>> Point(-0.5, 1) == Point(0.5, 1)
False
>>> Point("pi", "e")
Traceback (most recent call last):
...
ValueError: x and y must be both numeric types but got <class 'str'>, <class 'str'> instead
"""
def __init__(self, x, y):
if not (isinstance(x, Number) and isinstance(y, Number)):
try:
x, y = float(x), float(y)
except ValueError as e:
e.args = ("x and y must be both numeric types "
"but got {}, {} instead".format(type(x), type(y)), )
raise
self.x = x
self.y = y
def __eq__(self, other):
return self.x == other.x and self.y == other.y
def __ne__(self, other):
return not self == other
def __gt__(self, other):
if self.x > other.x:
return True
elif self.x == other.x:
return self.y > other.y
return False
def __lt__(self, other):
return not self > other
def __ge__(self, other):
if self.x > other.x:
return True
elif self.x == other.x:
return self.y >= other.y
return False
def __le__(self, other):
if self.x < other.x:
return True
elif self.x == other.x:
return self.y <= other.y
return False
def __repr__(self):
return "({}, {})".format(self.x, self.y)
def __hash__(self):
return hash(self.x)
def _construct_points(list_of_tuples):
"""
constructs a list of points from an array-like object of numbers
Arguments
---------
list_of_tuples: array-like object of type numbers. Acceptable types so far
are lists, tuples and sets.
Returns
--------
points: a list where each item is of type Point. This contains only objects
which can be converted into a Point.
Examples
-------
>>> _construct_points([[1, 1], [2, -1], [0.3, 4]])
[(1, 1), (2, -1), (0.3, 4)]
>>> _construct_points(([1, 1], [2, -1], [0.3, 4]))
[(1, 1), (2, -1), (0.3, 4)]
>>> _construct_points([(1, 1), (2, -1), (0.3, 4)])
[(1, 1), (2, -1), (0.3, 4)]
>>> _construct_points([[1, 1], (2, -1), [0.3, 4]])
[(1, 1), (2, -1), (0.3, 4)]
>>> _construct_points([1, 2])
Ignoring deformed point 1. All points must have at least 2 coordinates.
Ignoring deformed point 2. All points must have at least 2 coordinates.
[]
>>> _construct_points([])
[]
>>> _construct_points(None)
[]
"""
points = []
if list_of_tuples:
for p in list_of_tuples:
try:
points.append(Point(p[0], p[1]))
except (IndexError, TypeError):
print("Ignoring deformed point {}. All points"
" must have at least 2 coordinates.".format(p))
return points
def _validate_input(points):
"""
validates an input instance before a convex-hull algorithms uses it
Parameters
---------
points: array-like, the 2d points to validate before using with
a convex-hull algorithm. The elements of points must be either lists, tuples or
Points.
Returns
-------
points: array_like, an iterable of all well-defined Points constructed passed in.
Exception
---------
ValueError: if points is empty or None, or if a wrong data structure like a scalar is passed
TypeError: if an iterable but non-indexable object (eg. dictionary) is passed.
The exception to this a set which we'll convert to a list before using
Examples
-------
>>> _validate_input([[1, 2]])
[(1, 2)]
>>> _validate_input([(1, 2)])
[(1, 2)]
>>> _validate_input([Point(2, 1), Point(-1, 2)])
[(2, 1), (-1, 2)]
>>> _validate_input([])
Traceback (most recent call last):
...
ValueError: Expecting a list of points but got []
>>> _validate_input(1)
Traceback (most recent call last):
...
ValueError: Expecting an iterable object but got an non-iterable type 1
"""
if not points:
raise ValueError("Expecting a list of points but got {}".format(points))
if isinstance(points, set):
points = list(points)
try:
if hasattr(points, "__iter__") and not isinstance(points[0], Point):
if isinstance(points[0], (list, tuple)):
points = _construct_points(points)
else:
raise ValueError("Expecting an iterable of type Point, list or tuple. "
"Found objects of type {} instead"
.format(["point", "list", "tuple"], type(points[0])))
elif not hasattr(points, "__iter__"):
raise ValueError("Expecting an iterable object "
"but got an non-iterable type {}".format(points))
except TypeError as e:
print("Expecting an iterable of type Point, list or tuple.")
raise
return points
def _det(a, b, c):
"""
Computes the sign perpendicular distance of a 2d point c from a line segment
ab. The sign indicates the direction of c relative to ab.
A Positive value means c is above ab (to the left), while a negative value
means c is below ab (to the right). 0 means all three points are on a straight line.
As a side note, 0.5 * abs|det| is the area of triangle abc
Parameters
----------
a: point, the point on the left end of line segment ab
b: point, the point on the right end of line segment ab
c: point, the point for which the direction and location is desired.
Returns
--------
det: float, abs(det) is the distance of c from ab. The sign
indicates which side of line segment ab c is. det is computed as
(a_xb_y + c_xa_y + b_xc_y) - (a_yb_x + c_ya_x + b_yc_x)
Examples
----------
>>> _det(Point(1, 1), Point(1, 2), Point(1, 5))
0
>>> _det(Point(0, 0), Point(10, 0), Point(0, 10))
100
>>> _det(Point(0, 0), Point(10, 0), Point(0, -10))
-100
"""
det = (a.x * b.y + b.x * c.y + c.x * a.y) - (a.y * b.x + b.y * c.x + c.y * a.x)
return det
def convex_hull_bf(points):
"""
Constructs the convex hull of a set of 2D points using a brute force algorithm.
The algorithm basically considers all combinations of points (i, j) and uses the
definition of convexity to determine whether (i, j) is part of the convex hull or not.
(i, j) is part of the convex hull if and only iff there are no points on both sides
of the line segment connecting the ij, and there is no point k such that k is on either end
of the ij.
Runtime: O(n^3) - definitely horrible
Parameters
---------
points: array-like of object of Points, lists or tuples.
The set of 2d points for which the convex-hull is needed
Returns
------
convex_set: list, the convex-hull of points sorted in non-decreasing order.
See Also
--------
convex_hull_recursive,
Examples
---------
>>> convex_hull_bf([[0, 0], [1, 0], [10, 1]])
[(0, 0), (1, 0), (10, 1)]
>>> convex_hull_bf([[0, 0], [1, 0], [10, 0]])
[(0, 0), (10, 0)]
>>> convex_hull_bf([[-1, 1],[-1, -1], [0, 0], [0.5, 0.5], [1, -1], [1, 1], [-0.75, 1]])
[(-1, -1), (-1, 1), (1, -1), (1, 1)]
>>> convex_hull_bf([(0, 3), (2, 2), (1, 1), (2, 1), (3, 0), (0, 0), (3, 3), (2, -1), (2, -4), (1, -3)])
[(0, 0), (0, 3), (1, -3), (2, -4), (3, 0), (3, 3)]
"""
points = sorted(_validate_input(points))
n = len(points)
convex_set = set()
for i in range(n-1):
for j in range(i + 1, n):
points_left_of_ij = points_right_of_ij = False
ij_part_of_convex_hull = True
for k in range(n):
if k != i and k != j:
det_k = _det(points[i], points[j], points[k])
if det_k > 0:
points_left_of_ij = True
elif det_k < 0:
points_right_of_ij = True
else:
# point[i], point[j], point[k] all lie on a straight line
# if point[k] is to the left of point[i] or it's to the
# right of point[j], then point[i], point[j] cannot be
# part of the convex hull of A
if points[k] < points[i] or points[k] > points[j]:
ij_part_of_convex_hull = False
break
if points_left_of_ij and points_right_of_ij:
ij_part_of_convex_hull = False
break
if ij_part_of_convex_hull:
convex_set.update([points[i], points[j]])
return sorted(convex_set)
def convex_hull_recursive(points):
"""
Constructs the convex hull of a set of 2D points using a divide-and-conquer strategy
The algorithm exploits the geometric properties of the problem by repeatedly partitioning
the set of points into smaller hulls, and finding the convex hull of these smaller hulls.
The union of the convex hull from smaller hulls is the solution to the convex hull of the larger problem.
Parameter
---------
points: array-like of object of Points, lists or tuples.
The set of 2d points for which the convex-hull is needed
Runtime: O(n log n)
Returns
-------
convex_set: list, the convex-hull of points sorted in non-decreasing order.
Examples
---------
>>> convex_hull_recursive([[0, 0], [1, 0], [10, 1]])
[(0, 0), (1, 0), (10, 1)]
>>> convex_hull_recursive([[0, 0], [1, 0], [10, 0]])
[(0, 0), (10, 0)]
>>> convex_hull_recursive([[-1, 1],[-1, -1], [0, 0], [0.5, 0.5], [1, -1], [1, 1], [-0.75, 1]])
[(-1, -1), (-1, 1), (1, -1), (1, 1)]
>>> convex_hull_recursive([(0, 3), (2, 2), (1, 1), (2, 1), (3, 0), (0, 0), (3, 3), (2, -1), (2, -4), (1, -3)])
[(0, 0), (0, 3), (1, -3), (2, -4), (3, 0), (3, 3)]
"""
points = sorted(_validate_input(points))
n = len(points)
# divide all the points into an upper hull and a lower hull
# the left most point and the right most point are definitely
# members of the convex hull by definition.
# use these two anchors to divide all the points into two hulls,
# an upper hull and a lower hull.
# all points to the left (above) the line joining the extreme points belong to the upper hull
# all points to the right (below) the line joining the extreme points below to the lower hull
# ignore all points on the line joining the extreme points since they cannot be part of the
# convex hull
left_most_point = points[0]
right_most_point = points[n-1]
convex_set = {left_most_point, right_most_point}
upperhull = []
lowerhull = []
for i in range(1, n-1):
det = _det(left_most_point, right_most_point, points[i])
if det > 0:
upperhull.append(points[i])
elif det < 0:
lowerhull.append(points[i])
_construct_hull(upperhull, left_most_point, right_most_point, convex_set)
_construct_hull(lowerhull, right_most_point, left_most_point, convex_set)
return sorted(convex_set)
def _construct_hull(points, left, right, convex_set):
"""
Parameters
---------
points: list or None, the hull of points from which to choose the next convex-hull point
left: Point, the point to the left of line segment joining left and right
right: The point to the right of the line segment joining left and right
convex_set: set, the current convex-hull. The state of convex-set gets updated by this function
Note
----
For the line segment 'ab', 'a' is on the left and 'b' on the right.
but the reverse is true for the line segment 'ba'.
Returns
-------
Nothing, only updates the state of convex-set
"""
if points:
extreme_point = None
extreme_point_distance = float('-inf')
candidate_points = []
for p in points:
det = _det(left, right, p)
if det > 0:
candidate_points.append(p)
if det > extreme_point_distance:
extreme_point_distance = det
extreme_point = p
if extreme_point:
_construct_hull(candidate_points, left, extreme_point, convex_set)
convex_set.add(extreme_point)
_construct_hull(candidate_points, extreme_point, right, convex_set)
def main():
points = [(0, 3), (2, 2), (1, 1), (2, 1), (3, 0),
(0, 0), (3, 3), (2, -1), (2, -4), (1, -3)]
# the convex set of points is
# [(0, 0), (0, 3), (1, -3), (2, -4), (3, 0), (3, 3)]
results_recursive = convex_hull_recursive(points)
results_bf = convex_hull_bf(points)
assert results_bf == results_recursive
print(results_bf)
if __name__ == '__main__':
main()
| [] | [] | [] |
archives/1098994933_python.zip | divide_and_conquer/inversions.py | """
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
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.
"""
def count_inversions_bf(arr):
"""
Counts the number of inversions using a a naive brute-force algorithm
Parameters
----------
arr: arr: array-like, the list containing the items for which the number
of inversions is desired. The elements of `arr` must be comparable.
Returns
-------
num_inversions: The total number of inversions in `arr`
Examples
---------
>>> count_inversions_bf([1, 4, 2, 4, 1])
4
>>> count_inversions_bf([1, 1, 2, 4, 4])
0
>>> count_inversions_bf([])
0
"""
num_inversions = 0
n = len(arr)
for i in range(n-1):
for j in range(i + 1, n):
if arr[i] > arr[j]:
num_inversions += 1
return num_inversions
def count_inversions_recursive(arr):
"""
Counts the number of inversions using a divide-and-conquer algorithm
Parameters
-----------
arr: array-like, the list containing the items for which the number
of inversions is desired. The elements of `arr` must be comparable.
Returns
-------
C: a sorted copy of `arr`.
num_inversions: int, the total number of inversions in 'arr'
Examples
--------
>>> count_inversions_recursive([1, 4, 2, 4, 1])
([1, 1, 2, 4, 4], 4)
>>> count_inversions_recursive([1, 1, 2, 4, 4])
([1, 1, 2, 4, 4], 0)
>>> count_inversions_recursive([])
([], 0)
"""
if len(arr) <= 1:
return arr, 0
else:
mid = len(arr)//2
P = arr[0:mid]
Q = arr[mid:]
A, inversion_p = count_inversions_recursive(P)
B, inversions_q = count_inversions_recursive(Q)
C, cross_inversions = _count_cross_inversions(A, B)
num_inversions = inversion_p + inversions_q + cross_inversions
return C, num_inversions
def _count_cross_inversions(P, Q):
"""
Counts the inversions across two sorted arrays.
And combine the two arrays into one sorted array
For all 1<= i<=len(P) and for all 1 <= j <= len(Q),
if P[i] > Q[j], then (i, j) is a cross inversion
Parameters
----------
P: array-like, sorted in non-decreasing order
Q: array-like, sorted in non-decreasing order
Returns
------
R: array-like, a sorted array of the elements of `P` and `Q`
num_inversion: int, the number of inversions across `P` and `Q`
Examples
--------
>>> _count_cross_inversions([1, 2, 3], [0, 2, 5])
([0, 1, 2, 2, 3, 5], 4)
>>> _count_cross_inversions([1, 2, 3], [3, 4, 5])
([1, 2, 3, 3, 4, 5], 0)
"""
R = []
i = j = num_inversion = 0
while i < len(P) and j < len(Q):
if P[i] > Q[j]:
# if P[1] > Q[j], then P[k] > Q[k] for all i < k <= len(P)
# These are all inversions. The claim emerges from the
# property that P is sorted.
num_inversion += (len(P) - i)
R.append(Q[j])
j += 1
else:
R.append(P[i])
i += 1
if i < len(P):
R.extend(P[i:])
else:
R.extend(Q[j:])
return R, num_inversion
def main():
arr_1 = [10, 2, 1, 5, 5, 2, 11]
# this arr has 8 inversions:
# (10, 2), (10, 1), (10, 5), (10, 5), (10, 2), (2, 1), (5, 2), (5, 2)
num_inversions_bf = count_inversions_bf(arr_1)
_, num_inversions_recursive = count_inversions_recursive(arr_1)
assert num_inversions_bf == num_inversions_recursive == 8
print("number of inversions = ", num_inversions_bf)
# testing an array with zero inversion (a sorted arr_1)
arr_1.sort()
num_inversions_bf = count_inversions_bf(arr_1)
_, num_inversions_recursive = count_inversions_recursive(arr_1)
assert num_inversions_bf == num_inversions_recursive == 0
print("number of inversions = ", num_inversions_bf)
# an empty list should also have zero inversions
arr_1 = []
num_inversions_bf = count_inversions_bf(arr_1)
_, num_inversions_recursive = count_inversions_recursive(arr_1)
assert num_inversions_bf == num_inversions_recursive == 0
print("number of inversions = ", num_inversions_bf)
if __name__ == "__main__":
main()
| [] | [] | [] |
archives/1098994933_python.zip | divide_and_conquer/max_subarray_sum.py | """
Given a array of length n, max_subarray_sum() finds
the maximum of sum of contiguous sub-array using divide and conquer method.
Time complexity : O(n log n)
Ref : INTRODUCTION TO ALGORITHMS THIRD EDITION
(section : 4, sub-section : 4.1, page : 70)
"""
def max_sum_from_start(array):
""" This function finds the maximum contiguous sum of array from 0 index
Parameters :
array (list[int]) : given array
Returns :
max_sum (int) : maximum contiguous sum of array from 0 index
"""
array_sum = 0
max_sum = float("-inf")
for num in array:
array_sum += num
if array_sum > max_sum:
max_sum = array_sum
return max_sum
def max_cross_array_sum(array, left, mid, right):
""" This function finds the maximum contiguous sum of left and right arrays
Parameters :
array, left, mid, right (list[int], int, int, int)
Returns :
(int) : maximum of sum of contiguous sum of left and right arrays
"""
max_sum_of_left = max_sum_from_start(array[left:mid+1][::-1])
max_sum_of_right = max_sum_from_start(array[mid+1: right+1])
return max_sum_of_left + max_sum_of_right
def max_subarray_sum(array, left, right):
""" Maximum contiguous sub-array sum, using divide and conquer method
Parameters :
array, left, right (list[int], int, int) :
given array, current left index and current right index
Returns :
int : maximum of sum of contiguous sub-array
"""
# base case: array has only one element
if left == right:
return array[right]
# Recursion
mid = (left + right) // 2
left_half_sum = max_subarray_sum(array, left, mid)
right_half_sum = max_subarray_sum(array, mid + 1, right)
cross_sum = max_cross_array_sum(array, left, mid, right)
return max(left_half_sum, right_half_sum, cross_sum)
array = [-2, -5, 6, -2, -3, 1, 5, -6]
array_length = len(array)
print("Maximum sum of contiguous subarray:", max_subarray_sum(array, 0, array_length - 1))
| [] | [] | [] |
archives/1098994933_python.zip | dynamic_programming/abbreviation.py | """
https://www.hackerrank.com/challenges/abbr/problem
You can perform the following operation on some string, :
1. Capitalize zero or more of 's lowercase letters at some index i
(i.e., make them uppercase).
2. Delete all of the remaining lowercase letters in .
Example:
a=daBcd and b="ABC"
daBcd -> capitalize a and c(dABCd) -> remove d (ABC)
"""
def abbr(a, b):
n = len(a)
m = len(b)
dp = [[False for _ in range(m + 1)] for _ in range(n + 1)]
dp[0][0] = True
for i in range(n):
for j in range(m + 1):
if dp[i][j]:
if j < m and a[i].upper() == b[j]:
dp[i + 1][j + 1] = True
if a[i].islower():
dp[i + 1][j] = True
return dp[n][m]
if __name__ == "__main__":
print(abbr("daBcd", "ABC")) # expect True
| [] | [] | [] |
archives/1098994933_python.zip | dynamic_programming/bitmask.py | """
This is a python implementation for questions involving task assignments between people.
Here Bitmasking and DP are used for solving this.
Question :-
We have N tasks and M people. Each person in M can do only certain of these tasks. Also a person can do only one task and a task is performed only by one person.
Find the total no of ways in which the tasks can be distributed.
"""
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<<len(task_performed)) - 1
def CountWaysUtil(self,mask,taskno):
# if mask == self.finalmask all persons are distributed tasks, return 1
if mask == self.finalmask:
return 1
#if not everyone gets the task and no more tasks are available, return 0
if taskno > self.total_tasks:
return 0
#if case already considered
if self.dp[mask][taskno]!=-1:
return self.dp[mask][taskno]
# Number of ways when we dont this task in the arrangement
total_ways_util = self.CountWaysUtil(mask,taskno+1)
# now assign the tasks one by one to all possible persons and recursively assign for the remaining tasks.
if taskno in self.task:
for p in self.task[taskno]:
# if p is already given a task
if mask & (1<<p):
continue
# assign this task to p and change the mask value. And recursively assign tasks with the new mask value.
total_ways_util+=self.CountWaysUtil(mask|(1<<p),taskno+1)
# save the value.
self.dp[mask][taskno] = total_ways_util
return self.dp[mask][taskno]
def countNoOfWays(self,task_performed):
# Store the list of persons for each task
for i in range(len(task_performed)):
for j in task_performed[i]:
self.task[j].append(i)
# call the function to fill the DP table, final answer is stored in dp[0][1]
return self.CountWaysUtil(0,1)
if __name__ == '__main__':
total_tasks = 5 #total no of tasks (the value of N)
#the list of tasks that can be done by M persons.
task_performed = [
[ 1 , 3 , 4 ],
[ 1 , 2 , 5 ],
[ 3 , 4 ]
]
print(AssignmentUsingBitmask(task_performed,total_tasks).countNoOfWays(task_performed))
"""
For the particular example the tasks can be distributed as
(1,2,3), (1,2,4), (1,5,3), (1,5,4), (3,1,4), (3,2,4), (3,5,4), (4,1,3), (4,2,3), (4,5,3)
total 10
""" | [] | [] | [] |
archives/1098994933_python.zip | dynamic_programming/climbing_stairs.py | #!/usr/bin/env python3
def climb_stairs(n: int) -> int:
"""
LeetCdoe No.70: Climbing Stairs
Distinct ways to climb a n step staircase where
each time you can either climb 1 or 2 steps.
Args:
n: number of steps of staircase
Returns:
Distinct ways to climb a n step staircase
Raises:
AssertionError: n not positive integer
>>> climb_stairs(3)
3
>>> climb_stairs(1)
1
>>> climb_stairs(-7) # doctest: +ELLIPSIS
Traceback (most recent call last):
...
AssertionError: n needs to be positive integer, your input -7
"""
fmt = "n needs to be positive integer, your input {}"
assert isinstance(n, int) and n > 0, fmt.format(n)
if n == 1:
return 1
dp = [0] * (n + 1)
dp[0], dp[1] = (1, 1)
for i in range(2, n + 1):
dp[i] = dp[i - 1] + dp[i - 2]
return dp[n]
if __name__ == "__main__":
import doctest
doctest.testmod()
| [
"int"
] | [
45
] | [
48
] |
archives/1098994933_python.zip | dynamic_programming/coin_change.py | """
You have m types of coins available in infinite quantities
where the value of each coins is given in the array S=[S0,... Sm-1]
Can you determine number of ways of making change for n units using
the given types of coins?
https://www.hackerrank.com/challenges/coin-change/problem
"""
def dp_count(S, m, n):
# table[i] represents the number of ways to get to amount i
table = [0] * (n + 1)
# There is exactly 1 way to get to zero(You pick no coins).
table[0] = 1
# Pick all coins one by one and update table[] values
# after the index greater than or equal to the value of the
# picked coin
for coin_val in S:
for j in range(coin_val, n + 1):
table[j] += table[j - coin_val]
return table[n]
if __name__ == '__main__':
print(dp_count([1, 2, 3], 3, 4)) # answer 4
print(dp_count([2, 5, 3, 6], 4, 10)) # answer 5
| [] | [] | [] |
archives/1098994933_python.zip | dynamic_programming/edit_distance.py | """
Author : Turfa Auliarachman
Date : October 12, 2016
This is a pure Python implementation of Dynamic Programming solution to the edit distance problem.
The problem is :
Given two strings A and B. Find the minimum number of operations to string B such that A = B. The permitted operations are removal, insertion, and substitution.
"""
class EditDistance:
"""
Use :
solver = EditDistance()
editDistanceResult = solver.solve(firstString, secondString)
"""
def __init__(self):
self.__prepare__()
def __prepare__(self, N = 0, M = 0):
self.dp = [[-1 for y in range(0,M)] for x in range(0,N)]
def __solveDP(self, x, y):
if (x==-1):
return y+1
elif (y==-1):
return x+1
elif (self.dp[x][y]>-1):
return self.dp[x][y]
else:
if (self.A[x]==self.B[y]):
self.dp[x][y] = self.__solveDP(x-1,y-1)
else:
self.dp[x][y] = 1+min(self.__solveDP(x,y-1), self.__solveDP(x-1,y), self.__solveDP(x-1,y-1))
return self.dp[x][y]
def solve(self, A, B):
if isinstance(A,bytes):
A = A.decode('ascii')
if isinstance(B,bytes):
B = B.decode('ascii')
self.A = str(A)
self.B = str(B)
self.__prepare__(len(A), len(B))
return self.__solveDP(len(A)-1, len(B)-1)
def min_distance_bottom_up(word1: str, word2: str) -> int:
"""
>>> min_distance_bottom_up("intention", "execution")
5
>>> min_distance_bottom_up("intention", "")
9
>>> min_distance_bottom_up("", "")
0
"""
m = len(word1)
n = len(word2)
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 word1[i-1] == word2[j-1]: #last character of both substing is equal
dp[i][j] = dp[i-1][j-1]
else:
insert = dp[i][j-1]
delete = dp[i-1][j]
replace = dp[i-1][j-1]
dp[i][j] = 1 + min(insert, delete, replace)
return dp[m][n]
if __name__ == '__main__':
solver = EditDistance()
print("****************** Testing Edit Distance DP Algorithm ******************")
print()
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)))
print("The minimum Edit Distance is: %d" % (min_distance_bottom_up(S1, S2)))
print()
print("*************** End of Testing Edit Distance DP Algorithm ***************")
| [
"str",
"str"
] | [
1453,
1465
] | [
1456,
1468
] |
archives/1098994933_python.zip | dynamic_programming/factorial.py | #Factorial of a number using memoization
result=[-1]*10
result[0]=result[1]=1
def factorial(num):
"""
>>> factorial(7)
5040
>>> factorial(-1)
'Number should not be negative.'
>>> [factorial(i) for i in range(5)]
[1, 1, 2, 6, 24]
"""
if num<0:
return "Number should not be negative."
if result[num]!=-1:
return result[num]
else:
result[num]=num*factorial(num-1)
#uncomment the following to see how recalculations are avoided
#print(result)
return result[num]
#factorial of num
#uncomment the following to see how recalculations are avoided
##result=[-1]*10
##result[0]=result[1]=1
##print(factorial(5))
# print(factorial(3))
# print(factorial(7))
if __name__ == "__main__":
import doctest
doctest.testmod()
| [] | [] | [] |
archives/1098994933_python.zip | dynamic_programming/fast_fibonacci.py | #!/usr/bin/python
# encoding=utf8
"""
This program calculates the nth Fibonacci number in O(log(n)).
It's possible to calculate F(1000000) in less than a second.
"""
import sys
# returns F(n)
def fibonacci(n: int): # noqa: E999 This syntax is Python 3 only
if n < 0:
raise ValueError("Negative arguments are not supported")
return _fib(n)[0]
# returns (F(n), F(n-1))
def _fib(n: int): # noqa: E999 This syntax is Python 3 only
if n == 0:
# (F(0), F(1))
return (0, 1)
else:
# F(2n) = F(n)[2F(n+1) − F(n)]
# F(2n+1) = F(n+1)^2+F(n)^2
a, b = _fib(n // 2)
c = a * (b * 2 - a)
d = a * a + b * b
if n % 2 == 0:
return (c, d)
else:
return (d, c + d)
if __name__ == "__main__":
args = sys.argv[1:]
if len(args) != 1:
print("Too few or too much parameters given.")
exit(1)
try:
n = int(args[0])
except ValueError:
print("Could not convert data to an integer.")
exit(1)
print("F(%d) = %d" % (n, fibonacci(n)))
| [
"int",
"int"
] | [
212,
401
] | [
215,
404
] |
archives/1098994933_python.zip | dynamic_programming/fibonacci.py | """
This is a pure Python implementation of Dynamic Programming solution to the fibonacci sequence problem.
"""
class Fibonacci:
def __init__(self, N=None):
self.fib_array = []
if N:
N = int(N)
self.fib_array.append(0)
self.fib_array.append(1)
for i in range(2, N + 1):
self.fib_array.append(self.fib_array[i - 1] + self.fib_array[i - 2])
elif N == 0:
self.fib_array.append(0)
def get(self, sequence_no=None):
if sequence_no != None:
if sequence_no < len(self.fib_array):
return print(self.fib_array[:sequence_no + 1])
else:
print("Out of bound.")
else:
print("Please specify a value")
if __name__ == '__main__':
print("\n********* Fibonacci Series Using Dynamic Programming ************\n")
print("\n Enter the upper limit for the fibonacci sequence: ", end="")
try:
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")
while True:
try:
i = int(input("Enter value: ").strip())
if i < 0:
print("\n********* Good Bye!! ************\n")
break
fib.get(i)
except NameError:
print("\nInvalid input, please try again.")
except NameError:
print("\n********* Invalid input, good bye!! ************\n")
| [] | [] | [] |
archives/1098994933_python.zip | dynamic_programming/floyd_warshall.py | import math
class Graph:
def __init__(self, N = 0): # a graph with Node 0,1,...,N-1
self.N = N
self.W = [[math.inf for j in range(0,N)] for i in range(0,N)] # adjacency matrix for weight
self.dp = [[math.inf for j in range(0,N)] for i in range(0,N)] # dp[i][j] stores minimum distance from i to j
def addEdge(self, u, v, w):
self.dp[u][v] = w
def floyd_warshall(self):
for k in range(0,self.N):
for i in range(0,self.N):
for j in range(0,self.N):
self.dp[i][j] = min(self.dp[i][j], self.dp[i][k] + self.dp[k][j])
def showMin(self, u, v):
return self.dp[u][v]
if __name__ == '__main__':
graph = Graph(5)
graph.addEdge(0,2,9)
graph.addEdge(0,4,10)
graph.addEdge(1,3,5)
graph.addEdge(2,3,7)
graph.addEdge(3,0,10)
graph.addEdge(3,1,2)
graph.addEdge(3,2,1)
graph.addEdge(3,4,6)
graph.addEdge(4,1,3)
graph.addEdge(4,2,4)
graph.addEdge(4,3,9)
graph.floyd_warshall()
graph.showMin(1,4)
graph.showMin(0,3)
| [] | [] | [] |
archives/1098994933_python.zip | dynamic_programming/fractional_knapsack.py | from itertools import accumulate
from bisect import bisect
def fracKnapsack(vl, wt, W, n):
r = list(sorted(zip(vl,wt), key=lambda x:x[0]/x[1],reverse=True))
vl , wt = [i[0] for i in r],[i[1] for i in r]
acc=list(accumulate(wt))
k = bisect(acc,W)
return 0 if k == 0 else sum(vl[:k])+(W-acc[k-1])*(vl[k])/(wt[k]) if k!=n else sum(vl[:k])
print("%.0f"%fracKnapsack([60, 100, 120],[10, 20, 30],50,3))
| [] | [] | [] |
archives/1098994933_python.zip | dynamic_programming/integer_partition.py | '''
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 range(m)] for _ in range(m+1)]
for i in range(m+1):
memo[i][0] = 1
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]
return memo[m][m-1]
if __name__ == '__main__':
import sys
if len(sys.argv) == 1:
try:
n = int(input('Enter a number: ').strip())
print(partition(n))
except ValueError:
print('Please enter a number.')
else:
try:
n = int(sys.argv[1])
print(partition(n))
except ValueError:
print('Please pass a number.') | [] | [] | [] |
archives/1098994933_python.zip | dynamic_programming/k_means_clustering_tensorflow.py | import tensorflow as tf
from random import shuffle
from numpy import array
def TFKMeansCluster(vectors, noofclusters):
"""
K-Means Clustering using TensorFlow.
'vectors' should be a n*k 2-D NumPy array, where n is the number
of vectors of dimensionality k.
'noofclusters' should be an integer.
"""
noofclusters = int(noofclusters)
assert noofclusters < len(vectors)
#Find out the dimensionality
dim = len(vectors[0])
#Will help select random centroids from among the available vectors
vector_indices = list(range(len(vectors)))
shuffle(vector_indices)
#GRAPH OF COMPUTATION
#We initialize a new graph and set it as the default during each run
#of this algorithm. This ensures that as this function is called
#multiple times, the default graph doesn't keep getting crowded with
#unused ops and Variables from previous function calls.
graph = tf.Graph()
with graph.as_default():
#SESSION OF COMPUTATION
sess = tf.Session()
##CONSTRUCTING THE ELEMENTS OF COMPUTATION
##First lets ensure we have a Variable vector for each centroid,
##initialized to one of the vectors from the available data points
centroids = [tf.Variable((vectors[vector_indices[i]]))
for i in range(noofclusters)]
##These nodes will assign the centroid Variables the appropriate
##values
centroid_value = tf.placeholder("float64", [dim])
cent_assigns = []
for centroid in centroids:
cent_assigns.append(tf.assign(centroid, centroid_value))
##Variables for cluster assignments of individual vectors(initialized
##to 0 at first)
assignments = [tf.Variable(0) for i in range(len(vectors))]
##These nodes will assign an assignment Variable the appropriate
##value
assignment_value = tf.placeholder("int32")
cluster_assigns = []
for assignment in assignments:
cluster_assigns.append(tf.assign(assignment,
assignment_value))
##Now lets construct the node that will compute the mean
#The placeholder for the input
mean_input = tf.placeholder("float", [None, dim])
#The Node/op takes the input and computes a mean along the 0th
#dimension, i.e. the list of input vectors
mean_op = tf.reduce_mean(mean_input, 0)
##Node for computing Euclidean distances
#Placeholders for input
v1 = tf.placeholder("float", [dim])
v2 = tf.placeholder("float", [dim])
euclid_dist = tf.sqrt(tf.reduce_sum(tf.pow(tf.sub(
v1, v2), 2)))
##This node will figure out which cluster to assign a vector to,
##based on Euclidean distances of the vector from the centroids.
#Placeholder for input
centroid_distances = tf.placeholder("float", [noofclusters])
cluster_assignment = tf.argmin(centroid_distances, 0)
##INITIALIZING STATE VARIABLES
##This will help initialization of all Variables defined with respect
##to the graph. The Variable-initializer should be defined after
##all the Variables have been constructed, so that each of them
##will be included in the initialization.
init_op = tf.initialize_all_variables()
#Initialize all variables
sess.run(init_op)
##CLUSTERING ITERATIONS
#Now perform the Expectation-Maximization steps of K-Means clustering
#iterations. To keep things simple, we will only do a set number of
#iterations, instead of using a Stopping Criterion.
noofiterations = 100
for iteration_n in range(noofiterations):
##EXPECTATION STEP
##Based on the centroid locations till last iteration, compute
##the _expected_ centroid assignments.
#Iterate over each vector
for vector_n in range(len(vectors)):
vect = vectors[vector_n]
#Compute Euclidean distance between this vector and each
#centroid. Remember that this list cannot be named
#'centroid_distances', since that is the input to the
#cluster assignment node.
distances = [sess.run(euclid_dist, feed_dict={
v1: vect, v2: sess.run(centroid)})
for centroid in centroids]
#Now use the cluster assignment node, with the distances
#as the input
assignment = sess.run(cluster_assignment, feed_dict = {
centroid_distances: distances})
#Now assign the value to the appropriate state variable
sess.run(cluster_assigns[vector_n], feed_dict={
assignment_value: assignment})
##MAXIMIZATION STEP
#Based on the expected state computed from the Expectation Step,
#compute the locations of the centroids so as to maximize the
#overall objective of minimizing within-cluster Sum-of-Squares
for cluster_n in range(noofclusters):
#Collect all the vectors assigned to this cluster
assigned_vects = [vectors[i] for i in range(len(vectors))
if sess.run(assignments[i]) == cluster_n]
#Compute new centroid location
new_location = sess.run(mean_op, feed_dict={
mean_input: array(assigned_vects)})
#Assign value to appropriate variable
sess.run(cent_assigns[cluster_n], feed_dict={
centroid_value: new_location})
#Return centroids and assignments
centroids = sess.run(centroids)
assignments = sess.run(assignments)
return centroids, assignments
| [] | [] | [] |
archives/1098994933_python.zip | dynamic_programming/knapsack.py | """
Given weights and values of n items, put these items in a knapsack of
capacity W to get the maximum total value in the knapsack.
Note that only the integer weights 0-1 knapsack problem is solvable
using dynamic programming.
"""
def MF_knapsack(i, wt, val, j):
'''
This code involves the concept of memory functions. Here we solve the subproblems which are needed
unlike the below example
F is a 2D array with -1s filled up
'''
global F # a global dp table for knapsack
if F[i][j] < 0:
if j < wt[i-1]:
val = MF_knapsack(i-1, wt, val, j)
else:
val = max(MF_knapsack(i-1, wt, val, j),
MF_knapsack(i-1, wt, val, j - wt[i-1]) + val[i-1])
F[i][j] = val
return F[i][j]
def knapsack(W, wt, val, n):
dp = [[0 for i in range(W+1)]for j in range(n+1)]
for i in range(1,n+1):
for w in range(1, W+1):
if wt[i-1] <= w:
dp[i][w] = max(val[i-1] + dp[i-1][w-wt[i-1]], dp[i-1][w])
else:
dp[i][w] = dp[i-1][w]
return dp[n][W], dp
def knapsack_with_example_solution(W: int, wt: list, val:list):
"""
Solves the integer weights knapsack problem returns one of
the several possible optimal subsets.
Parameters
---------
W: int, the total maximum weight for the given knapsack problem.
wt: list, the vector of weights for all items where wt[i] is the weight
of the ith item.
val: list, the vector of values for all items where val[i] is the value
of te ith item
Returns
-------
optimal_val: float, the optimal value for the given knapsack problem
example_optional_set: set, the indices of one of the optimal subsets
which gave rise to the optimal value.
Examples
-------
>>> knapsack_with_example_solution(10, [1, 3, 5, 2], [10, 20, 100, 22])
(142, {2, 3, 4})
>>> knapsack_with_example_solution(6, [4, 3, 2, 3], [3, 2, 4, 4])
(8, {3, 4})
>>> knapsack_with_example_solution(6, [4, 3, 2, 3], [3, 2, 4])
Traceback (most recent call last):
...
ValueError: The number of weights must be the same as the number of values.
But got 4 weights and 3 values
"""
if not (isinstance(wt, (list, tuple)) and isinstance(val, (list, tuple))):
raise ValueError("Both the weights and values vectors must be either lists or tuples")
num_items = len(wt)
if num_items != len(val):
raise ValueError("The number of weights must be the "
"same as the number of values.\nBut "
"got {} weights and {} values".format(num_items, len(val)))
for i in range(num_items):
if not isinstance(wt[i], int):
raise TypeError("All weights must be integers but "
"got weight of type {} at index {}".format(type(wt[i]), i))
optimal_val, dp_table = knapsack(W, wt, val, num_items)
example_optional_set = set()
_construct_solution(dp_table, wt, num_items, W, example_optional_set)
return optimal_val, example_optional_set
def _construct_solution(dp:list, wt:list, i:int, j:int, optimal_set:set):
"""
Recursively reconstructs one of the optimal subsets given
a filled DP table and the vector of weights
Parameters
---------
dp: list of list, the table of a solved integer weight dynamic programming problem
wt: list or tuple, the vector of weights of the items
i: int, the index of the item under consideration
j: int, the current possible maximum weight
optimal_set: set, the optimal subset so far. This gets modified by the function.
Returns
-------
None
"""
# for the current item i at a maximum weight j to be part of an optimal subset,
# the optimal value at (i, j) must be greater than the optimal value at (i-1, j).
# where i - 1 means considering only the previous items at the given maximum weight
if i > 0 and j > 0:
if dp[i - 1][j] == dp[i][j]:
_construct_solution(dp, wt, i - 1, j, optimal_set)
else:
optimal_set.add(i)
_construct_solution(dp, wt, i - 1, j - wt[i-1], optimal_set)
if __name__ == '__main__':
'''
Adding test case for knapsack
'''
val = [3, 2, 4, 4]
wt = [4, 3, 2, 3]
n = 4
w = 6
F = [[0] * (w + 1)] + [[0] + [-1 for i in range(w + 1)] for j in range(n + 1)]
optimal_solution, _ = knapsack(w,wt,val, n)
print(optimal_solution)
print(MF_knapsack(n,wt,val,w)) # switched the n and w
# testing the dynamic programming problem with example
# the optimal subset for the above example are items 3 and 4
optimal_solution, optimal_subset = knapsack_with_example_solution(w, wt, val)
assert optimal_solution == 8
assert optimal_subset == {3, 4}
print("optimal_value = ", optimal_solution)
print("An optimal subset corresponding to the optimal value", optimal_subset)
| [
"int",
"list",
"list",
"list",
"list",
"int",
"int",
"set"
] | [
1143,
1152,
1162,
3141,
3150,
3158,
3165,
3182
] | [
1146,
1156,
1166,
3145,
3154,
3161,
3168,
3185
] |
archives/1098994933_python.zip | dynamic_programming/longest_common_subsequence.py | """
LCS Problem Statement: Given two sequences, find the length of longest subsequence present in both of them.
A subsequence is a sequence that appears in the same relative order, but not necessarily continuous.
Example:"abc", "abg" are subsequences of "abcdefgh".
"""
def longest_common_subsequence(x: str, y: str):
"""
Finds the longest common subsequence between two strings. Also returns the
The subsequence found
Parameters
----------
x: str, one of the strings
y: str, the other string
Returns
-------
L[m][n]: int, the length of the longest subsequence. Also equal to len(seq)
Seq: str, the subsequence found
>>> longest_common_subsequence("programming", "gaming")
(6, 'gaming')
>>> longest_common_subsequence("physics", "smartphone")
(2, 'ph')
>>> longest_common_subsequence("computer", "food")
(1, 'o')
"""
# find the length of strings
assert x is not None
assert y is not None
m = len(x)
n = len(y)
# declaring the array for storing the dp values
L = [[0] * (n + 1) for _ in range(m + 1)]
for i in range(1, m + 1):
for j in range(1, n + 1):
if x[i-1] == y[j-1]:
match = 1
else:
match = 0
L[i][j] = max(L[i-1][j], L[i][j-1], L[i-1][j-1] + match)
seq = ""
i, j = m, n
while i > 0 and j > 0:
if x[i - 1] == y[j - 1]:
match = 1
else:
match = 0
if L[i][j] == L[i - 1][j - 1] + match:
if match == 1:
seq = x[i - 1] + seq
i -= 1
j -= 1
elif L[i][j] == L[i - 1][j]:
i -= 1
else:
j -= 1
return L[m][n], seq
if __name__ == '__main__':
a = 'AGGTAB'
b = 'GXTXAYB'
expected_ln = 4
expected_subseq = "GTAB"
ln, subseq = longest_common_subsequence(a, b)
assert expected_ln == ln
assert expected_subseq == subseq
print("len =", ln, ", sub-sequence =", subseq)
| [
"str",
"str"
] | [
306,
314
] | [
309,
317
] |
archives/1098994933_python.zip | dynamic_programming/longest_increasing_subsequence.py | '''
Author : Mehdi ALAOUI
This is a pure Python implementation of Dynamic Programming solution to the longest increasing subsequence of a given sequence.
The problem is :
Given an ARRAY, to find the longest and increasing sub ARRAY in that given ARRAY and return it.
Example: [10, 22, 9, 33, 21, 50, 41, 60, 80] as input will return [10, 22, 33, 41, 60, 80] as output
'''
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
#Else
PIVOT=ARRAY[0]
isFound=False
i=1
LONGEST_SUB=[]
while(not isFound and i<ARRAY_LENGTH):
if (ARRAY[i] < PIVOT):
isFound=True
TEMPORARY_ARRAY = [ element for element in ARRAY[i:] if element >= ARRAY[i] ]
TEMPORARY_ARRAY = longestSub(TEMPORARY_ARRAY)
if ( len(TEMPORARY_ARRAY) > len(LONGEST_SUB) ):
LONGEST_SUB = TEMPORARY_ARRAY
else:
i+=1
TEMPORARY_ARRAY = [ element for element in ARRAY[1:] if element >= PIVOT ]
TEMPORARY_ARRAY = [PIVOT] + longestSub(TEMPORARY_ARRAY)
if ( len(TEMPORARY_ARRAY) > len(LONGEST_SUB) ):
return TEMPORARY_ARRAY
else:
return LONGEST_SUB
#Some examples
print(longestSub([4,8,7,5,1,12,2,3,9]))
print(longestSub([9,8,7,6,5,7])) | [] | [] | [] |
archives/1098994933_python.zip | dynamic_programming/longest_increasing_subsequence_o(nlogn).py | #############################
# 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
#############################
def CeilIndex(v,l,r,key):
while r-l > 1:
m = (l + r)/2
if v[m] >= key:
r = m
else:
l = m
return r
def LongestIncreasingSubsequenceLength(v):
if(len(v) == 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
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]
print(LongestIncreasingSubsequenceLength(v))
| [] | [] | [] |
archives/1098994933_python.zip | dynamic_programming/longest_sub_array.py | '''
Auther : Yvonne
This is a pure Python implementation of Dynamic Programming solution to the longest_sub_array problem.
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.
'''
class SubArray:
def __init__(self, arr):
# we need a list not a string, so do something to change the type
self.array = arr.split(',')
print(("the input array is:", self.array))
def solve_sub_array(self):
rear = [int(self.array[0])]*len(self.array)
sum_value = [int(self.array[0])]*len(self.array)
for i in range(1, len(self.array)):
sum_value[i] = max(int(self.array[i]) + sum_value[i-1], int(self.array[i]))
rear[i] = max(sum_value[i], rear[i-1])
return rear[len(self.array)-1]
if __name__ == '__main__':
whole_array = input("please input some numbers:")
array = SubArray(whole_array)
re = array.solve_sub_array()
print(("the results is:", re))
| [] | [] | [] |
archives/1098994933_python.zip | dynamic_programming/matrix_chain_order.py | import sys
'''
Dynamic Programming
Implementation of Matrix Chain Multiplication
Time Complexity: O(n^3)
Space Complexity: O(n^2)
'''
def MatrixChainOrder(array):
N=len(array)
Matrix=[[0 for x in range(N)] for x in range(N)]
Sol=[[0 for x in range(N)] for x in range(N)]
for ChainLength in range(2,N):
for a in range(1,N-ChainLength+1):
b = a+ChainLength-1
Matrix[a][b] = sys.maxsize
for c in range(a , b):
cost = Matrix[a][c] + Matrix[c+1][b] + array[a-1]*array[c]*array[b]
if cost < Matrix[a][b]:
Matrix[a][b] = cost
Sol[a][b] = c
return Matrix , Sol
#Print order of matrix with Ai as Matrix
def PrintOptimalSolution(OptimalSolution,i,j):
if i==j:
print("A" + str(i),end = " ")
else:
print("(",end = " ")
PrintOptimalSolution(OptimalSolution,i,OptimalSolution[i][j])
PrintOptimalSolution(OptimalSolution,OptimalSolution[i][j]+1,j)
print(")",end = " ")
def main():
array=[30,35,15,5,10,20,25]
n=len(array)
#Size of matrix created from above array will be
# 30*35 35*15 15*5 5*10 10*20 20*25
Matrix , OptimalSolution = MatrixChainOrder(array)
print("No. of Operation required: "+str((Matrix[1][n-1])))
PrintOptimalSolution(OptimalSolution,1,n-1)
if __name__ == '__main__':
main()
| [] | [] | [] |
archives/1098994933_python.zip | dynamic_programming/max_sub_array.py | """
author : Mayank Kumar Jha (mk9440)
"""
from typing import List
import time
import matplotlib.pyplot as plt
from random import randint
def find_max_sub_array(A,low,high):
if low==high:
return low,high,A[low]
else :
mid=(low+high)//2
left_low,left_high,left_sum=find_max_sub_array(A,low,mid)
right_low,right_high,right_sum=find_max_sub_array(A,mid+1,high)
cross_left,cross_right,cross_sum=find_max_cross_sum(A,low,mid,high)
if left_sum>=right_sum and left_sum>=cross_sum:
return left_low,left_high,left_sum
elif right_sum>=left_sum and right_sum>=cross_sum :
return right_low,right_high,right_sum
else:
return cross_left,cross_right,cross_sum
def find_max_cross_sum(A,low,mid,high):
left_sum,max_left=-999999999,-1
right_sum,max_right=-999999999,-1
summ=0
for i in range(mid,low-1,-1):
summ+=A[i]
if summ > left_sum:
left_sum=summ
max_left=i
summ=0
for i in range(mid+1,high+1):
summ+=A[i]
if summ > right_sum:
right_sum=summ
max_right=i
return max_left,max_right,(left_sum+right_sum)
def max_sub_array(nums: List[int]) -> int:
"""
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])
6
>>> max_sub_array([])
0
>>> max_sub_array([-1,-2,-3])
0
"""
best = 0
current = 0
for i in nums:
current += i
if current < 0:
current = 0
best = max(best, current)
return best
if __name__=='__main__':
inputs=[10,100,1000,10000,50000,100000,200000,300000,400000,500000]
tim=[]
for i in inputs:
li=[randint(1,i) for j in range(i)]
strt=time.time()
(find_max_sub_array(li,0,len(li)-1))
end=time.time()
tim.append(end-strt)
print("No of Inputs Time Taken")
for i in range(len(inputs)):
print(inputs[i],'\t\t',tim[i])
plt.plot(inputs,tim)
plt.xlabel("Number of Inputs");plt.ylabel("Time taken in seconds ")
plt.show()
| [
"List[int]"
] | [
1229
] | [
1238
] |