zip
stringlengths 19
109
| filename
stringlengths 4
185
| contents
stringlengths 0
30.1M
| type_annotations
listlengths 0
1.97k
| type_annotation_starts
listlengths 0
1.97k
| type_annotation_ends
listlengths 0
1.97k
|
---|---|---|---|---|---|
archives/1098994933_python.zip | project_euler/problem_29/__init__.py | []
| []
| []
|
|
archives/1098994933_python.zip | project_euler/problem_29/solution.py | """
Consider all integer combinations of ab for 2 <= a <= 5 and 2 <= b <= 5:
2^2=4, 2^3=8, 2^4=16, 2^5=32
3^2=9, 3^3=27, 3^4=81, 3^5=243
4^2=16, 4^3=64, 4^4=256, 4^5=1024
5^2=25, 5^3=125, 5^4=625, 5^5=3125
If they are then placed in numerical order, with any repeats removed, we get
the following sequence of 15 distinct terms:
4, 8, 9, 16, 25, 27, 32, 64, 81, 125, 243, 256, 625, 1024, 3125
How many distinct terms are in the sequence generated by ab
for 2 <= a <= 100 and 2 <= b <= 100?
"""
def solution(n):
"""Returns the number of distinct terms in the sequence generated by a^b
for 2 <= a <= 100 and 2 <= b <= 100.
>>> solution(100)
9183
>>> solution(50)
2184
>>> solution(20)
324
>>> solution(5)
15
>>> solution(2)
1
>>> solution(1)
0
"""
collectPowers = set()
currentPow = 0
N = n + 1 # maximum limit
for a in range(2, N):
for b in range(2, N):
currentPow = a ** b # calculates the current power
collectPowers.add(currentPow) # adds the result to the set
return len(collectPowers)
if __name__ == "__main__":
print("Number of terms ", solution(int(str(input()).strip())))
| []
| []
| []
|
archives/1098994933_python.zip | project_euler/problem_31/__init__.py | []
| []
| []
|
|
archives/1098994933_python.zip | project_euler/problem_31/sol1.py | # -*- coding: utf-8 -*-
"""
Coin sums
Problem 31
In England the currency is made up of pound, £, and pence, p, and there are
eight coins in general circulation:
1p, 2p, 5p, 10p, 20p, 50p, £1 (100p) and £2 (200p).
It is possible to make £2 in the following way:
1×£1 + 1×50p + 2×20p + 1×5p + 1×2p + 3×1p
How many different ways can £2 be made using any number of coins?
"""
def one_pence():
return 1
def two_pence(x):
return 0 if x < 0 else two_pence(x - 2) + one_pence()
def five_pence(x):
return 0 if x < 0 else five_pence(x - 5) + two_pence(x)
def ten_pence(x):
return 0 if x < 0 else ten_pence(x - 10) + five_pence(x)
def twenty_pence(x):
return 0 if x < 0 else twenty_pence(x - 20) + ten_pence(x)
def fifty_pence(x):
return 0 if x < 0 else fifty_pence(x - 50) + twenty_pence(x)
def one_pound(x):
return 0 if x < 0 else one_pound(x - 100) + fifty_pence(x)
def two_pound(x):
return 0 if x < 0 else two_pound(x - 200) + one_pound(x)
def solution(n):
"""Returns the number of different ways can £n be made using any number of
coins?
>>> solution(500)
6295434
>>> solution(200)
73682
>>> solution(50)
451
>>> solution(10)
11
"""
return two_pound(n)
if __name__ == "__main__":
print(solution(int(str(input()).strip())))
| []
| []
| []
|
archives/1098994933_python.zip | project_euler/problem_36/__init__.py | []
| []
| []
|
|
archives/1098994933_python.zip | project_euler/problem_36/sol1.py | """
Double-base palindromes
Problem 36
The decimal number, 585 = 10010010012 (binary), is palindromic in both bases.
Find the sum of all numbers, less than one million, which are palindromic in
base 10 and base 2.
(Please note that the palindromic number, in either base, may not include
leading zeros.)
"""
def is_palindrome(n):
n = str(n)
if n == n[::-1]:
return True
else:
return False
def solution(n):
"""Return the sum of all numbers, less than n , which are palindromic in
base 10 and base 2.
>>> solution(1000000)
872187
>>> solution(500000)
286602
>>> solution(100000)
286602
>>> solution(1000)
1772
>>> solution(100)
157
>>> solution(10)
25
>>> solution(2)
1
>>> solution(1)
0
"""
total = 0
for i in range(1, n):
if is_palindrome(i) and is_palindrome(bin(i).split("b")[1]):
total += i
return total
if __name__ == "__main__":
print(solution(int(str(input().strip()))))
| []
| []
| []
|
archives/1098994933_python.zip | project_euler/problem_40/__init__.py | []
| []
| []
|
|
archives/1098994933_python.zip | project_euler/problem_40/sol1.py | # -.- coding: latin-1 -.-
"""
Champernowne's constant
Problem 40
An irrational decimal fraction is created by concatenating the positive
integers:
0.123456789101112131415161718192021...
It can be seen that the 12th digit of the fractional part is 1.
If dn represents the nth digit of the fractional part, find the value of the
following expression.
d1 × d10 × d100 × d1000 × d10000 × d100000 × d1000000
"""
def solution():
"""Returns
>>> solution()
210
"""
constant = []
i = 1
while len(constant) < 1e6:
constant.append(str(i))
i += 1
constant = "".join(constant)
return (
int(constant[0])
* int(constant[9])
* int(constant[99])
* int(constant[999])
* int(constant[9999])
* int(constant[99999])
* int(constant[999999])
)
if __name__ == "__main__":
print(solution())
| []
| []
| []
|
archives/1098994933_python.zip | project_euler/problem_48/__init__.py | []
| []
| []
|
|
archives/1098994933_python.zip | project_euler/problem_48/sol1.py | """
Self Powers
Problem 48
The series, 11 + 22 + 33 + ... + 1010 = 10405071317.
Find the last ten digits of the series, 11 + 22 + 33 + ... + 10001000.
"""
def solution():
"""Returns the last 10 digits of the series, 11 + 22 + 33 + ... + 10001000.
>>> solution()
'9110846700'
"""
total = 0
for i in range(1, 1001):
total += i ** i
return str(total)[-10:]
if __name__ == "__main__":
print(solution())
| []
| []
| []
|
archives/1098994933_python.zip | project_euler/problem_52/__init__.py | []
| []
| []
|
|
archives/1098994933_python.zip | project_euler/problem_52/sol1.py | """
Permuted multiples
Problem 52
It can be seen that the number, 125874, and its double, 251748, contain exactly
the same digits, but in a different order.
Find the smallest positive integer, x, such that 2x, 3x, 4x, 5x, and 6x,
contain the same digits.
"""
def solution():
"""Returns the smallest positive integer, x, such that 2x, 3x, 4x, 5x, and
6x, contain the same digits.
>>> solution()
142857
"""
i = 1
while True:
if (
sorted(list(str(i)))
== sorted(list(str(2 * i)))
== sorted(list(str(3 * i)))
== sorted(list(str(4 * i)))
== sorted(list(str(5 * i)))
== sorted(list(str(6 * i)))
):
return i
i += 1
if __name__ == "__main__":
print(solution())
| []
| []
| []
|
archives/1098994933_python.zip | project_euler/problem_53/__init__.py | []
| []
| []
|
|
archives/1098994933_python.zip | project_euler/problem_53/sol1.py | # -.- coding: latin-1 -.-
"""
Combinatoric selections
Problem 53
There are exactly ten ways of selecting three from five, 12345:
123, 124, 125, 134, 135, 145, 234, 235, 245, and 345
In combinatorics, we use the notation, 5C3 = 10.
In general,
nCr = n!/(r!(n−r)!),where r ≤ n, n! = n×(n−1)×...×3×2×1, and 0! = 1.
It is not until n = 23, that a value exceeds one-million: 23C10 = 1144066.
How many, not necessarily distinct, values of nCr, for 1 ≤ n ≤ 100, are greater
than one-million?
"""
from math import factorial
def combinations(n, r):
return factorial(n) / (factorial(r) * factorial(n - r))
def solution():
"""Returns the number of values of nCr, for 1 ≤ n ≤ 100, are greater than
one-million
>>> solution()
4075
"""
total = 0
for i in range(1, 101):
for j in range(1, i + 1):
if combinations(i, j) > 1e6:
total += 1
return total
if __name__ == "__main__":
print(solution())
| []
| []
| []
|
archives/1098994933_python.zip | project_euler/problem_551/__init__.py | []
| []
| []
|
|
archives/1098994933_python.zip | project_euler/problem_551/sol1.py | """
Sum of digits sequence
Problem 551
Let a(0), a(1),... be an interger sequence defined by:
a(0) = 1
for n >= 1, a(n) is the sum of the digits of all preceding terms
The sequence starts with 1, 1, 2, 4, 8, ...
You are given a(10^6) = 31054319.
Find a(10^15)
"""
ks = [k for k in range(2, 20+1)]
base = [10 ** k for k in range(ks[-1] + 1)]
memo = {}
def next_term(a_i, k, i, n):
"""
Calculates and updates a_i in-place to either the n-th term or the
smallest term for which c > 10^k when the terms are written in the form:
a(i) = b * 10^k + c
For any a(i), if digitsum(b) and c have the same value, the difference
between subsequent terms will be the same until c >= 10^k. This difference
is cached to greatly speed up the computation.
Arguments:
a_i -- array of digits starting from the one's place that represent
the i-th term in the sequence
k -- k when terms are written in the from a(i) = b*10^k + c.
Term are calulcated until c > 10^k or the n-th term is reached.
i -- position along the sequence
n -- term to caluclate up to if k is large enough
Return: a tuple of difference between ending term and starting term, and
the number of terms calculated. ex. if starting term is a_0=1, and
ending term is a_10=62, then (61, 9) is returned.
"""
# ds_b - digitsum(b)
ds_b = 0
for j in range(k, len(a_i)):
ds_b += a_i[j]
c = 0
for j in range(min(len(a_i), k)):
c += a_i[j] * base[j]
diff, dn = 0, 0
max_dn = n - i
sub_memo = memo.get(ds_b)
if sub_memo != None:
jumps = sub_memo.get(c)
if jumps != None and len(jumps) > 0:
# find and make the largest jump without going over
max_jump = -1
for _k in range(len(jumps) - 1, -1, -1):
if jumps[_k][2] <= k and jumps[_k][1] <= max_dn:
max_jump = _k
break
if max_jump >= 0:
diff, dn, _kk = jumps[max_jump]
# since the difference between jumps is cached, add c
new_c = diff + c
for j in range(min(k, len(a_i))):
new_c, a_i[j] = divmod(new_c, 10)
if new_c > 0:
add(a_i, k, new_c)
else:
sub_memo[c] = []
else:
sub_memo = {c: []}
memo[ds_b] = sub_memo
if dn >= max_dn or c + diff >= base[k]:
return diff, dn
if k > ks[0]:
while True:
# keep doing smaller jumps
_diff, terms_jumped = next_term(a_i, k - 1, i + dn, n)
diff += _diff
dn += terms_jumped
if dn >= max_dn or c + diff >= base[k]:
break
else:
# would be too small a jump, just compute sequential terms instead
_diff, terms_jumped = compute(a_i, k, i + dn, n)
diff += _diff
dn += terms_jumped
jumps = sub_memo[c]
# keep jumps sorted by # of terms skipped
j = 0
while j < len(jumps):
if jumps[j][1] > dn:
break
j += 1
# cache the jump for this value digitsum(b) and c
sub_memo[c].insert(j, (diff, dn, k))
return (diff, dn)
def compute(a_i, k, i, n):
"""
same as next_term(a_i, k, i, n) but computes terms without memoizing results.
"""
if i >= n:
return 0, i
if k > len(a_i):
a_i.extend([0 for _ in range(k - len(a_i))])
# note: a_i -> b * 10^k + c
# ds_b -> digitsum(b)
# ds_c -> digitsum(c)
start_i = i
ds_b, ds_c, diff = 0, 0, 0
for j in range(len(a_i)):
if j >= k:
ds_b += a_i[j]
else:
ds_c += a_i[j]
while i < n:
i += 1
addend = ds_c + ds_b
diff += addend
ds_c = 0
for j in range(k):
s = a_i[j] + addend
addend, a_i[j] = divmod(s, 10)
ds_c += a_i[j]
if addend > 0:
break
if addend > 0:
add(a_i, k, addend)
return diff, i - start_i
def add(digits, k, addend):
"""
adds addend to digit array given in digits
starting at index k
"""
for j in range(k, len(digits)):
s = digits[j] + addend
if s >= 10:
quotient, digits[j] = divmod(s, 10)
addend = addend // 10 + quotient
else:
digits[j] = s
addend = addend // 10
if addend == 0:
break
while addend > 0:
addend, digit = divmod(addend, 10)
digits.append(digit)
def solution(n):
"""
returns n-th term of sequence
>>> solution(10)
62
>>> solution(10**6)
31054319
>>> solution(10**15)
73597483551591773
"""
digits = [1]
i = 1
dn = 0
while True:
diff, terms_jumped = next_term(digits, 20, i + dn, n)
dn += terms_jumped
if dn == n - i:
break
a_n = 0
for j in range(len(digits)):
a_n += digits[j] * 10 ** j
return a_n
if __name__ == "__main__":
print(solution(10 ** 15))
| []
| []
| []
|
archives/1098994933_python.zip | project_euler/problem_56/__init__.py | []
| []
| []
|
|
archives/1098994933_python.zip | project_euler/problem_56/sol1.py |
def maximum_digital_sum(a: int, b: int) -> int:
"""
Considering natural numbers of the form, a**b, where a, b < 100,
what is the maximum digital sum?
:param a:
:param b:
:return:
>>> maximum_digital_sum(10,10)
45
>>> maximum_digital_sum(100,100)
972
>>> maximum_digital_sum(100,200)
1872
"""
# RETURN the MAXIMUM from the list of SUMs of the list of INT converted from STR of BASE raised to the POWER
return max([sum([int(x) for x in str(base**power)]) for base in range(a) for power in range(b)])
#Tests
if __name__ == "__main__":
import doctest
doctest.testmod()
| [
"int",
"int"
]
| [
29,
37
]
| [
32,
40
]
|
archives/1098994933_python.zip | project_euler/problem_67/__init__.py | []
| []
| []
|
|
archives/1098994933_python.zip | project_euler/problem_67/sol1.py | """
Problem Statement:
By starting at the top of the triangle below and moving to adjacent numbers on
the row below, the maximum total from top to bottom is 23.
3
7 4
2 4 6
8 5 9 3
That is, 3 + 7 + 4 + 9 = 23.
Find the maximum total from top to bottom in triangle.txt (right click and
'Save Link/Target As...'), a 15K text file containing a triangle with
one-hundred rows.
"""
import os
def solution():
"""
Finds the maximum total in a triangle as described by the problem statement
above.
>>> solution()
7273
"""
script_dir = os.path.dirname(os.path.realpath(__file__))
triangle = os.path.join(script_dir, 'triangle.txt')
with open(triangle, 'r') as f:
triangle = f.readlines()
a = map(lambda x: x.rstrip('\r\n').split(' '), triangle)
a = list(map(lambda x: list(map(lambda y: int(y), x)), a))
for i in range(1, len(a)):
for j in range(len(a[i])):
if j != len(a[i - 1]):
number1 = a[i - 1][j]
else:
number1 = 0
if j > 0:
number2 = a[i - 1][j - 1]
else:
number2 = 0
a[i][j] += max(number1, number2)
return max(a[-1])
if __name__ == "__main__":
print(solution())
| []
| []
| []
|
archives/1098994933_python.zip | project_euler/problem_76/__init__.py | []
| []
| []
|
|
archives/1098994933_python.zip | project_euler/problem_76/sol1.py | """
Counting Summations
Problem 76
It is possible to write five as a sum in exactly six different ways:
4 + 1
3 + 2
3 + 1 + 1
2 + 2 + 1
2 + 1 + 1 + 1
1 + 1 + 1 + 1 + 1
How many different ways can one hundred be written as a sum of at least two
positive integers?
"""
def partition(m):
"""Returns the number of different ways one hundred can be written as a sum
of at least two positive integers.
>>> partition(100)
190569291
>>> partition(50)
204225
>>> partition(30)
5603
>>> partition(10)
41
>>> partition(5)
6
>>> partition(3)
2
>>> partition(2)
1
>>> partition(1)
0
"""
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:
memo[n][k] += memo[n - k - 1][k]
return memo[m][m - 1] - 1
if __name__ == "__main__":
print(partition(int(str(input()).strip())))
| []
| []
| []
|
archives/1098994933_python.zip | scripts/build_directory_md.py | #!/usr/bin/env python3
import os
from typing import Iterator
URL_BASE = "https://github.com/TheAlgorithms/Python/blob/master"
def good_filepaths(top_dir: str = ".") -> Iterator[str]:
for dirpath, dirnames, filenames in os.walk(top_dir):
dirnames[:] = [d for d in dirnames if d != "scripts" and d[0] not in "._"]
for filename in filenames:
if filename == "__init__.py":
continue
if os.path.splitext(filename)[1] in (".py", ".ipynb"):
yield os.path.join(dirpath, filename).lstrip("./")
def md_prefix(i):
return f"{i * ' '}*" if i else "##"
def print_path(old_path: str, new_path: str) -> str:
old_parts = old_path.split(os.sep)
for i, new_part in enumerate(new_path.split(os.sep)):
if i + 1 > len(old_parts) or old_parts[i] != new_part:
if new_part:
print(f"{md_prefix(i-1)} {new_part.replace('_', ' ').title()}")
return new_path
def print_directory_md(top_dir: str = ".") -> None:
old_path = ""
for filepath in sorted(good_filepaths()):
filepath, filename = os.path.split(filepath)
if filepath != old_path:
old_path = print_path(old_path, filepath)
indent = (filepath.count(os.sep) + 1) if filepath else 0
url = "/".join((URL_BASE, filepath.split(os.sep)[1], filename)).replace(" ", "%20")
filename = os.path.splitext(filename.replace("_", " "))[0]
print(f"{md_prefix(indent)} [{filename}]({url})")
if __name__ == "__main__":
print_directory_md(".")
| [
"str",
"str"
]
| [
668,
683
]
| [
671,
686
]
|
archives/1098994933_python.zip | scripts/validate_filenames.py | #!/usr/bin/env python3
import os
from build_directory_md import good_filepaths
filepaths = list(good_filepaths())
assert filepaths, "good_filepaths() failed!"
upper_files = [file for file in filepaths if file != file.lower()]
if upper_files:
print(f"{len(upper_files)} files contain uppercase characters:")
print("\n".join(upper_files) + "\n")
space_files = [file for file in filepaths if " " in file]
if space_files:
print(f"{len(space_files)} files contain space characters:")
print("\n".join(space_files) + "\n")
nodir_files = [file for file in filepaths if os.sep not in file]
if nodir_files:
print(f"{len(nodir_files)} files are not in a directory:")
print("\n".join(nodir_files) + "\n")
bad_files = len(upper_files + space_files + nodir_files)
if bad_files:
import sys
sys.exit(bad_files)
| []
| []
| []
|
archives/1098994933_python.zip | searches/binary_search.py | """
This is pure python implementation of binary search algorithm
For doctests run following command:
python -m doctest -v binary_search.py
or
python3 -m doctest -v binary_search.py
For manual testing run:
python binary_search.py
"""
import bisect
def binary_search(sorted_collection, item):
"""Pure implementation of binary search algorithm in Python
Be careful collection must be ascending sorted, otherwise result will be
unpredictable
:param sorted_collection: some ascending sorted collection with comparable items
:param item: item value to search
:return: index of found item or None if item is not found
Examples:
>>> binary_search([0, 5, 7, 10, 15], 0)
0
>>> binary_search([0, 5, 7, 10, 15], 15)
4
>>> binary_search([0, 5, 7, 10, 15], 5)
1
>>> binary_search([0, 5, 7, 10, 15], 6)
"""
left = 0
right = len(sorted_collection) - 1
while left <= right:
midpoint = left + (right - left) // 2
current_item = sorted_collection[midpoint]
if current_item == item:
return midpoint
else:
if item < current_item:
right = midpoint - 1
else:
left = midpoint + 1
return None
def binary_search_std_lib(sorted_collection, item):
"""Pure implementation of binary search algorithm in Python using stdlib
Be careful collection must be ascending sorted, otherwise result will be
unpredictable
:param sorted_collection: some ascending sorted collection with comparable items
:param item: item value to search
:return: index of found item or None if item is not found
Examples:
>>> binary_search_std_lib([0, 5, 7, 10, 15], 0)
0
>>> binary_search_std_lib([0, 5, 7, 10, 15], 15)
4
>>> binary_search_std_lib([0, 5, 7, 10, 15], 5)
1
>>> binary_search_std_lib([0, 5, 7, 10, 15], 6)
"""
index = bisect.bisect_left(sorted_collection, item)
if index != len(sorted_collection) and sorted_collection[index] == item:
return index
return None
def binary_search_by_recursion(sorted_collection, item, left, right):
"""Pure implementation of binary search algorithm in Python by recursion
Be careful collection must be ascending sorted, otherwise result will be
unpredictable
First recursion should be started with left=0 and right=(len(sorted_collection)-1)
:param sorted_collection: some ascending sorted collection with comparable items
:param item: item value to search
:return: index of found item or None if item is not found
Examples:
>>> binary_search_std_lib([0, 5, 7, 10, 15], 0)
0
>>> binary_search_std_lib([0, 5, 7, 10, 15], 15)
4
>>> binary_search_std_lib([0, 5, 7, 10, 15], 5)
1
>>> binary_search_std_lib([0, 5, 7, 10, 15], 6)
"""
if (right < left):
return None
midpoint = left + (right - left) // 2
if sorted_collection[midpoint] == item:
return midpoint
elif sorted_collection[midpoint] > item:
return binary_search_by_recursion(sorted_collection, item, left, midpoint-1)
else:
return binary_search_by_recursion(sorted_collection, item, midpoint+1, right)
def __assert_sorted(collection):
"""Check if collection is ascending sorted, if not - raises :py:class:`ValueError`
:param collection: collection
:return: True if collection is ascending sorted
:raise: :py:class:`ValueError` if collection is not ascending sorted
Examples:
>>> __assert_sorted([0, 1, 2, 4])
True
>>> __assert_sorted([10, -1, 5])
Traceback (most recent call last):
...
ValueError: Collection must be ascending sorted
"""
if collection != sorted(collection):
raise ValueError('Collection must be ascending sorted')
return True
if __name__ == '__main__':
import sys
user_input = input('Enter numbers separated by comma:\n').strip()
collection = [int(item) for item in user_input.split(',')]
try:
__assert_sorted(collection)
except ValueError:
sys.exit('Sequence must be ascending sorted to apply binary search')
target_input = input('Enter a single number to be found in the list:\n')
target = int(target_input)
result = binary_search(collection, target)
if result is not None:
print('{} found at positions: {}'.format(target, result))
else:
print('Not found')
| []
| []
| []
|
archives/1098994933_python.zip | searches/interpolation_search.py | """
This is pure python implementation of interpolation search algorithm
"""
def interpolation_search(sorted_collection, item):
"""Pure implementation of interpolation search algorithm in Python
Be careful collection must be ascending sorted, otherwise result will be
unpredictable
:param sorted_collection: some ascending sorted collection with comparable items
:param item: item value to search
:return: index of found item or None if item is not found
"""
left = 0
right = len(sorted_collection) - 1
while left <= right:
#avoid devided by 0 during interpolation
if sorted_collection[left]==sorted_collection[right]:
if sorted_collection[left]==item:
return left
else:
return None
point = left + ((item - sorted_collection[left]) * (right - left)) // (sorted_collection[right] - sorted_collection[left])
#out of range check
if point<0 or point>=len(sorted_collection):
return None
current_item = sorted_collection[point]
if current_item == item:
return point
else:
if point<left:
right = left
left = point
elif point>right:
left = right
right = point
else:
if item < current_item:
right = point - 1
else:
left = point + 1
return None
def interpolation_search_by_recursion(sorted_collection, item, left, right):
"""Pure implementation of interpolation search algorithm in Python by recursion
Be careful collection must be ascending sorted, otherwise result will be
unpredictable
First recursion should be started with left=0 and right=(len(sorted_collection)-1)
:param sorted_collection: some ascending sorted collection with comparable items
:param item: item value to search
:return: index of found item or None if item is not found
"""
#avoid devided by 0 during interpolation
if sorted_collection[left]==sorted_collection[right]:
if sorted_collection[left]==item:
return left
else:
return None
point = left + ((item - sorted_collection[left]) * (right - left)) // (sorted_collection[right] - sorted_collection[left])
#out of range check
if point<0 or point>=len(sorted_collection):
return None
if sorted_collection[point] == item:
return point
elif point<left:
return interpolation_search_by_recursion(sorted_collection, item, point, left)
elif point>right:
return interpolation_search_by_recursion(sorted_collection, item, right, left)
else:
if sorted_collection[point] > item:
return interpolation_search_by_recursion(sorted_collection, item, left, point-1)
else:
return interpolation_search_by_recursion(sorted_collection, item, point+1, right)
def __assert_sorted(collection):
"""Check if collection is ascending sorted, if not - raises :py:class:`ValueError`
:param collection: collection
:return: True if collection is ascending sorted
:raise: :py:class:`ValueError` if collection is not ascending sorted
Examples:
>>> __assert_sorted([0, 1, 2, 4])
True
>>> __assert_sorted([10, -1, 5])
Traceback (most recent call last):
...
ValueError: Collection must be ascending sorted
"""
if collection != sorted(collection):
raise ValueError('Collection must be ascending sorted')
return True
if __name__ == '__main__':
import sys
"""
user_input = input('Enter numbers separated by comma:\n').strip()
collection = [int(item) for item in user_input.split(',')]
try:
__assert_sorted(collection)
except ValueError:
sys.exit('Sequence must be ascending sorted to apply interpolation search')
target_input = input('Enter a single number to be found in the list:\n')
target = int(target_input)
"""
debug = 0
if debug == 1:
collection = [10,30,40,45,50,66,77,93]
try:
__assert_sorted(collection)
except ValueError:
sys.exit('Sequence must be ascending sorted to apply interpolation search')
target = 67
result = interpolation_search(collection, target)
if result is not None:
print('{} found at positions: {}'.format(target, result))
else:
print('Not found')
| []
| []
| []
|
archives/1098994933_python.zip | searches/jump_search.py | import math
def jump_search(arr, x):
n = len(arr)
step = int(math.floor(math.sqrt(n)))
prev = 0
while arr[min(step, n)-1] < x:
prev = step
step += int(math.floor(math.sqrt(n)))
if prev >= n:
return -1
while arr[prev] < x:
prev = prev + 1
if prev == min(step, n):
return -1
if arr[prev] == x:
return prev
return -1
arr = [ 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610]
x = 55
index = jump_search(arr, x)
print("\nNumber " + str(x) +" is at index " + str(index));
| []
| []
| []
|
archives/1098994933_python.zip | searches/linear_search.py | """
This is pure python implementation of linear search algorithm
For doctests run following command:
python -m doctest -v linear_search.py
or
python3 -m doctest -v linear_search.py
For manual testing run:
python linear_search.py
"""
def linear_search(sequence, target):
"""Pure implementation of linear search algorithm in Python
:param sequence: some sorted collection with comparable items
:param target: item value to search
:return: index of found item or None if item is not found
Examples:
>>> linear_search([0, 5, 7, 10, 15], 0)
0
>>> linear_search([0, 5, 7, 10, 15], 15)
4
>>> linear_search([0, 5, 7, 10, 15], 5)
1
>>> linear_search([0, 5, 7, 10, 15], 6)
"""
for index, item in enumerate(sequence):
if item == target:
return index
return None
if __name__ == '__main__':
user_input = input('Enter numbers separated by comma:\n').strip()
sequence = [int(item) for item in user_input.split(',')]
target_input = input('Enter a single number to be found in the list:\n')
target = int(target_input)
result = linear_search(sequence, target)
if result is not None:
print('{} found at positions: {}'.format(target, result))
else:
print('Not found')
| []
| []
| []
|
archives/1098994933_python.zip | searches/quick_select.py | import random
"""
A python implementation of the quick select algorithm, which is efficient for calculating the value that would appear in the index of a list if it would be sorted, even if it is not already sorted
https://en.wikipedia.org/wiki/Quickselect
"""
def _partition(data, pivot):
"""
Three way partition the data into smaller, equal and greater lists,
in relationship to the pivot
:param data: The data to be sorted (a list)
:param pivot: The value to partition the data on
:return: Three list: smaller, equal and greater
"""
less, equal, greater = [], [], []
for element in data:
if element < pivot:
less.append(element)
elif element > pivot:
greater.append(element)
else:
equal.append(element)
return less, equal, greater
def quickSelect(list, k):
#k = len(list) // 2 when trying to find the median (index that value would be when list is sorted)
#invalid input
if k>=len(list) or k<0:
return None
smaller = []
larger = []
pivot = random.randint(0, len(list) - 1)
pivot = list[pivot]
count = 0
smaller, equal, larger =_partition(list, pivot)
count = len(equal)
m = len(smaller)
#k is the pivot
if m <= k < m + count:
return pivot
# must be in smaller
elif m > k:
return quickSelect(smaller, k)
#must be in larger
else:
return quickSelect(larger, k - (m + count)) | []
| []
| []
|
archives/1098994933_python.zip | searches/sentinel_linear_search.py | """
This is pure python implementation of sentinel linear search algorithm
For doctests run following command:
python -m doctest -v sentinel_linear_search.py
or
python3 -m doctest -v sentinel_linear_search.py
For manual testing run:
python sentinel_linear_search.py
"""
def sentinel_linear_search(sequence, target):
"""Pure implementation of sentinel linear search algorithm in Python
:param sequence: some sequence with comparable items
:param target: item value to search
:return: index of found item or None if item is not found
Examples:
>>> sentinel_linear_search([0, 5, 7, 10, 15], 0)
0
>>> sentinel_linear_search([0, 5, 7, 10, 15], 15)
4
>>> sentinel_linear_search([0, 5, 7, 10, 15], 5)
1
>>> sentinel_linear_search([0, 5, 7, 10, 15], 6)
"""
sequence.append(target)
index = 0
while sequence[index] != target:
index += 1
sequence.pop()
if index == len(sequence):
return None
return index
if __name__ == '__main__':
user_input = input('Enter numbers separated by comma:\n').strip()
sequence = [int(item) for item in user_input.split(',')]
target_input = input('Enter a single number to be found in the list:\n')
target = int(target_input)
result = sentinel_linear_search(sequence, target)
if result is not None:
print('{} found at positions: {}'.format(target, result))
else:
print('Not found') | []
| []
| []
|
archives/1098994933_python.zip | searches/tabu_search.py | """
This is pure python implementation of Tabu search algorithm for a Travelling Salesman Problem, that the distances
between the cities are symmetric (the distance between city 'a' and city 'b' is the same between city 'b' and city 'a').
The TSP can be represented into a graph. The cities are represented by nodes and the distance between them is
represented by the weight of the ark between the nodes.
The .txt file with the graph has the form:
node1 node2 distance_between_node1_and_node2
node1 node3 distance_between_node1_and_node3
...
Be careful node1, node2 and the distance between them, must exist only once. This means in the .txt file
should not exist:
node1 node2 distance_between_node1_and_node2
node2 node1 distance_between_node2_and_node1
For pytests run following command:
pytest
For manual testing run:
python tabu_search.py -f your_file_name.txt -number_of_iterations_of_tabu_search -s size_of_tabu_search
e.g. python tabu_search.py -f tabudata2.txt -i 4 -s 3
"""
import copy
import argparse
import sys
def generate_neighbours(path):
"""
Pure implementation of generating a dictionary of neighbors and the cost with each
neighbor, given a path file that includes a graph.
:param path: The path to the .txt file that includes the graph (e.g.tabudata2.txt)
:return dict_of_neighbours: Dictionary with key each node and value a list of lists with the neighbors of the node
and the cost (distance) for each neighbor.
Example of dict_of_neighbours:
>>) dict_of_neighbours[a]
[[b,20],[c,18],[d,22],[e,26]]
This indicates the neighbors of node (city) 'a', which has neighbor the node 'b' with distance 20,
the node 'c' with distance 18, the node 'd' with distance 22 and the node 'e' with distance 26.
"""
dict_of_neighbours = {}
with open(path) as f:
for line in f:
if line.split()[0] not in dict_of_neighbours:
_list = list()
_list.append([line.split()[1], line.split()[2]])
dict_of_neighbours[line.split()[0]] = _list
else:
dict_of_neighbours[line.split()[0]].append([line.split()[1], line.split()[2]])
if line.split()[1] not in dict_of_neighbours:
_list = list()
_list.append([line.split()[0], line.split()[2]])
dict_of_neighbours[line.split()[1]] = _list
else:
dict_of_neighbours[line.split()[1]].append([line.split()[0], line.split()[2]])
return dict_of_neighbours
def generate_first_solution(path, dict_of_neighbours):
"""
Pure implementation of generating the first solution for the Tabu search to start, with the redundant resolution
strategy. That means that we start from the starting node (e.g. node 'a'), then we go to the city nearest (lowest
distance) to this node (let's assume is node 'c'), then we go to the nearest city of the node 'c', etc
till we have visited all cities and return to the starting node.
:param path: The path to the .txt file that includes the graph (e.g.tabudata2.txt)
:param dict_of_neighbours: Dictionary with key each node and value a list of lists with the neighbors of the node
and the cost (distance) for each neighbor.
:return first_solution: The solution for the first iteration of Tabu search using the redundant resolution strategy
in a list.
:return distance_of_first_solution: The total distance that Travelling Salesman will travel, if he follows the path
in first_solution.
"""
with open(path) as f:
start_node = f.read(1)
end_node = start_node
first_solution = []
visiting = start_node
distance_of_first_solution = 0
while visiting not in first_solution:
minim = 10000
for k in dict_of_neighbours[visiting]:
if int(k[1]) < int(minim) and k[0] not in first_solution:
minim = k[1]
best_node = k[0]
first_solution.append(visiting)
distance_of_first_solution = distance_of_first_solution + int(minim)
visiting = best_node
first_solution.append(end_node)
position = 0
for k in dict_of_neighbours[first_solution[-2]]:
if k[0] == start_node:
break
position += 1
distance_of_first_solution = distance_of_first_solution + int(
dict_of_neighbours[first_solution[-2]][position][1]) - 10000
return first_solution, distance_of_first_solution
def find_neighborhood(solution, dict_of_neighbours):
"""
Pure implementation of generating the neighborhood (sorted by total distance of each solution from
lowest to highest) of a solution with 1-1 exchange method, that means we exchange each node in a solution with each
other node and generating a number of solution named neighborhood.
:param solution: The solution in which we want to find the neighborhood.
:param dict_of_neighbours: Dictionary with key each node and value a list of lists with the neighbors of the node
and the cost (distance) for each neighbor.
:return neighborhood_of_solution: A list that includes the solutions and the total distance of each solution
(in form of list) that are produced with 1-1 exchange from the solution that the method took as an input
Example:
>>) find_neighborhood(['a','c','b','d','e','a'])
[['a','e','b','d','c','a',90], [['a','c','d','b','e','a',90],['a','d','b','c','e','a',93],
['a','c','b','e','d','a',102], ['a','c','e','d','b','a',113], ['a','b','c','d','e','a',93]]
"""
neighborhood_of_solution = []
for n in solution[1:-1]:
idx1 = solution.index(n)
for kn in solution[1:-1]:
idx2 = solution.index(kn)
if n == kn:
continue
_tmp = copy.deepcopy(solution)
_tmp[idx1] = kn
_tmp[idx2] = n
distance = 0
for k in _tmp[:-1]:
next_node = _tmp[_tmp.index(k) + 1]
for i in dict_of_neighbours[k]:
if i[0] == next_node:
distance = distance + int(i[1])
_tmp.append(distance)
if _tmp not in neighborhood_of_solution:
neighborhood_of_solution.append(_tmp)
indexOfLastItemInTheList = len(neighborhood_of_solution[0]) - 1
neighborhood_of_solution.sort(key=lambda x: x[indexOfLastItemInTheList])
return neighborhood_of_solution
def tabu_search(first_solution, distance_of_first_solution, dict_of_neighbours, iters, size):
"""
Pure implementation of Tabu search algorithm for a Travelling Salesman Problem in Python.
:param first_solution: The solution for the first iteration of Tabu search using the redundant resolution strategy
in a list.
:param distance_of_first_solution: The total distance that Travelling Salesman will travel, if he follows the path
in first_solution.
:param dict_of_neighbours: Dictionary with key each node and value a list of lists with the neighbors of the node
and the cost (distance) for each neighbor.
:param iters: The number of iterations that Tabu search will execute.
:param size: The size of Tabu List.
:return best_solution_ever: The solution with the lowest distance that occured during the execution of Tabu search.
:return best_cost: The total distance that Travelling Salesman will travel, if he follows the path in best_solution
ever.
"""
count = 1
solution = first_solution
tabu_list = list()
best_cost = distance_of_first_solution
best_solution_ever = solution
while count <= iters:
neighborhood = find_neighborhood(solution, dict_of_neighbours)
index_of_best_solution = 0
best_solution = neighborhood[index_of_best_solution]
best_cost_index = len(best_solution) - 1
found = False
while found is False:
i = 0
while i < len(best_solution):
if best_solution[i] != solution[i]:
first_exchange_node = best_solution[i]
second_exchange_node = solution[i]
break
i = i + 1
if [first_exchange_node, second_exchange_node] not in tabu_list and [second_exchange_node,
first_exchange_node] not in tabu_list:
tabu_list.append([first_exchange_node, second_exchange_node])
found = True
solution = best_solution[:-1]
cost = neighborhood[index_of_best_solution][best_cost_index]
if cost < best_cost:
best_cost = cost
best_solution_ever = solution
else:
index_of_best_solution = index_of_best_solution + 1
best_solution = neighborhood[index_of_best_solution]
if len(tabu_list) >= size:
tabu_list.pop(0)
count = count + 1
return best_solution_ever, best_cost
def main(args=None):
dict_of_neighbours = generate_neighbours(args.File)
first_solution, distance_of_first_solution = generate_first_solution(args.File, dict_of_neighbours)
best_sol, best_cost = tabu_search(first_solution, distance_of_first_solution, dict_of_neighbours, args.Iterations,
args.Size)
print("Best solution: {0}, with total distance: {1}.".format(best_sol, best_cost))
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Tabu Search")
parser.add_argument(
"-f", "--File", type=str, help="Path to the file containing the data", required=True)
parser.add_argument(
"-i", "--Iterations", type=int, help="How many iterations the algorithm should perform", required=True)
parser.add_argument(
"-s", "--Size", type=int, help="Size of the tabu list", required=True)
# Pass the arguments to main method
sys.exit(main(parser.parse_args()))
| []
| []
| []
|
archives/1098994933_python.zip | searches/ternary_search.py | '''
This is a type of divide and conquer algorithm which divides the search space into
3 parts and finds the target value based on the property of the array or list
(usually monotonic property).
Time Complexity : O(log3 N)
Space Complexity : O(1)
'''
import sys
# This is the precision for this function which can be altered.
# It is recommended for users to keep this number greater than or equal to 10.
precision = 10
# This is the linear search that will occur after the search space has become smaller.
def lin_search(left, right, A, target):
for i in range(left, right+1):
if(A[i] == target):
return i
# This is the iterative method of the ternary search algorithm.
def ite_ternary_search(A, target):
left = 0
right = len(A) - 1;
while(True):
if(left<right):
if(right-left < precision):
return lin_search(left,right,A,target)
oneThird = (left+right)/3+1;
twoThird = 2*(left+right)/3+1;
if(A[oneThird] == target):
return oneThird
elif(A[twoThird] == target):
return twoThird
elif(target < A[oneThird]):
right = oneThird-1
elif(A[twoThird] < target):
left = twoThird+1
else:
left = oneThird+1
right = twoThird-1
else:
return None
# This is the recursive method of the ternary search algorithm.
def rec_ternary_search(left, right, A, target):
if(left<right):
if(right-left < precision):
return lin_search(left,right,A,target)
oneThird = (left+right)/3+1;
twoThird = 2*(left+right)/3+1;
if(A[oneThird] == target):
return oneThird
elif(A[twoThird] == target):
return twoThird
elif(target < A[oneThird]):
return rec_ternary_search(left, oneThird-1, A, target)
elif(A[twoThird] < target):
return rec_ternary_search(twoThird+1, right, A, target)
else:
return rec_ternary_search(oneThird+1, twoThird-1, A, target)
else:
return None
# This function is to check if the array is sorted.
def __assert_sorted(collection):
if collection != sorted(collection):
raise ValueError('Collection must be sorted')
return True
if __name__ == '__main__':
user_input = input('Enter numbers separated by coma:\n').strip()
collection = [int(item) for item in user_input.split(',')]
try:
__assert_sorted(collection)
except ValueError:
sys.exit('Sequence must be sorted to apply the ternary search')
target_input = input('Enter a single number to be found in the list:\n')
target = int(target_input)
result1 = ite_ternary_search(collection, target)
result2 = rec_ternary_search(0, len(collection)-1, collection, target)
if result2 is not None:
print('Iterative search: {} found at positions: {}'.format(target, result1))
print('Recursive search: {} found at positions: {}'.format(target, result2))
else:
print('Not found')
| []
| []
| []
|
archives/1098994933_python.zip | sorts/bitonic_sort.py | # Python program for Bitonic Sort. Note that this program
# works only when size of input is a power of 2.
# The parameter dir indicates the sorting direction, ASCENDING
# or DESCENDING; if (a[i] > a[j]) agrees with the direction,
# then a[i] and a[j] are interchanged.*/
def compAndSwap(a, i, j, dire):
if (dire == 1 and a[i] > a[j]) or (dire == 0 and a[i] < a[j]):
a[i], a[j] = a[j], a[i]
# It recursively sorts a bitonic sequence in ascending order,
# if dir = 1, and in descending order otherwise (means dir=0).
# The sequence to be sorted starts at index position low,
# the parameter cnt is the number of elements to be sorted.
def bitonicMerge(a, low, cnt, dire):
if cnt > 1:
k = int(cnt / 2)
for i in range(low, low + k):
compAndSwap(a, i, i + k, dire)
bitonicMerge(a, low, k, dire)
bitonicMerge(a, low + k, k, dire)
# This funcion first produces a bitonic sequence by recursively
# sorting its two halves in opposite sorting orders, and then
# calls bitonicMerge to make them in the same order
def bitonicSort(a, low, cnt, dire):
if cnt > 1:
k = int(cnt / 2)
bitonicSort(a, low, k, 1)
bitonicSort(a, low + k, k, 0)
bitonicMerge(a, low, cnt, dire)
# Caller of bitonicSort for sorting the entire array of length N
# in ASCENDING order
def sort(a, N, up):
bitonicSort(a, 0, N, up)
if __name__ == "__main__":
# Driver code to test above
a = []
n = int(input().strip())
for i in range(n):
a.append(int(input().strip()))
up = 1
sort(a, n, up)
print("\n\nSorted array is")
for i in range(n):
print("%d" % a[i])
| []
| []
| []
|
archives/1098994933_python.zip | sorts/bogo_sort.py | """
This is a pure python implementation of the bogosort algorithm
For doctests run following command:
python -m doctest -v bogo_sort.py
or
python3 -m doctest -v bogo_sort.py
For manual testing run:
python bogo_sort.py
"""
import random
def bogo_sort(collection):
"""Pure implementation of the bogosort algorithm in Python
:param collection: some mutable ordered collection with heterogeneous
comparable items inside
:return: the same collection ordered by ascending
Examples:
>>> bogo_sort([0, 5, 3, 2, 2])
[0, 2, 2, 3, 5]
>>> bogo_sort([])
[]
>>> bogo_sort([-2, -5, -45])
[-45, -5, -2]
"""
def isSorted(collection):
if len(collection) < 2:
return True
for i in range(len(collection) - 1):
if collection[i] > collection[i + 1]:
return False
return True
while not isSorted(collection):
random.shuffle(collection)
return collection
if __name__ == '__main__':
user_input = input('Enter numbers separated by a comma:\n').strip()
unsorted = [int(item) for item in user_input.split(',')]
print(bogo_sort(unsorted))
| []
| []
| []
|
archives/1098994933_python.zip | sorts/bubble_sort.py | def bubble_sort(collection):
"""Pure implementation of bubble sort algorithm in Python
:param collection: some mutable ordered collection with heterogeneous
comparable items inside
:return: the same collection ordered by ascending
Examples:
>>> bubble_sort([0, 5, 3, 2, 2])
[0, 2, 2, 3, 5]
>>> bubble_sort([])
[]
>>> bubble_sort([-2, -5, -45])
[-45, -5, -2]
>>> bubble_sort([-23, 0, 6, -4, 34])
[-23, -4, 0, 6, 34]
>>> bubble_sort([-23, 0, 6, -4, 34]) == sorted([-23, 0, 6, -4, 34])
True
"""
length = len(collection)
for i in range(length-1):
swapped = False
for j in range(length-1-i):
if collection[j] > collection[j+1]:
swapped = True
collection[j], collection[j+1] = collection[j+1], collection[j]
if not swapped:
break # Stop iteration if the collection is sorted.
return collection
if __name__ == '__main__':
user_input = input('Enter numbers separated by a comma:').strip()
unsorted = [int(item) for item in user_input.split(',')]
print(*bubble_sort(unsorted), sep=',')
| []
| []
| []
|
archives/1098994933_python.zip | sorts/bucket_sort.py | #!/usr/bin/env python
"""Illustrate how to implement bucket sort algorithm."""
# Author: OMKAR PATHAK
# This program will illustrate how to implement bucket sort algorithm
# Wikipedia says: Bucket sort, or bin sort, is a sorting algorithm that works
# by distributing the elements of an array into a number of buckets.
# Each bucket is then sorted individually, either using a different sorting
# algorithm, or by recursively applying the bucket sorting algorithm. It is a
# distribution sort, and is a cousin of radix sort in the most to least
# significant digit flavour.
# Bucket sort is a generalization of pigeonhole sort. Bucket sort can be
# implemented with comparisons and therefore can also be considered a
# comparison sort algorithm. The computational complexity estimates involve the
# number of buckets.
# Time Complexity of Solution:
# Worst case scenario occurs when all the elements are placed in a single bucket. The overall performance
# would then be dominated by the algorithm used to sort each bucket. In this case, O(n log n), because of TimSort
#
# Average Case O(n + (n^2)/k + k), where k is the number of buckets
#
# If k = O(n), time complexity is O(n)
DEFAULT_BUCKET_SIZE = 5
def bucket_sort(my_list, bucket_size=DEFAULT_BUCKET_SIZE):
if len(my_list) == 0:
raise Exception("Please add some elements in the array.")
min_value, max_value = (min(my_list), max(my_list))
bucket_count = ((max_value - min_value) // bucket_size + 1)
buckets = [[] for _ in range(int(bucket_count))]
for i in range(len(my_list)):
buckets[int((my_list[i] - min_value) // bucket_size)
].append(my_list[i])
return sorted([buckets[i][j] for i in range(len(buckets))
for j in range(len(buckets[i]))])
if __name__ == "__main__":
user_input = input('Enter numbers separated by a comma:').strip()
unsorted = [float(n) for n in user_input.split(',') if len(user_input) > 0]
print(bucket_sort(unsorted))
| []
| []
| []
|
archives/1098994933_python.zip | sorts/cocktail_shaker_sort.py | def cocktail_shaker_sort(unsorted):
"""
Pure implementation of the cocktail shaker sort algorithm in Python.
"""
for i in range(len(unsorted)-1, 0, -1):
swapped = False
for j in range(i, 0, -1):
if unsorted[j] < unsorted[j-1]:
unsorted[j], unsorted[j-1] = unsorted[j-1], unsorted[j]
swapped = True
for j in range(i):
if unsorted[j] > unsorted[j+1]:
unsorted[j], unsorted[j+1] = unsorted[j+1], unsorted[j]
swapped = True
if not swapped:
return unsorted
if __name__ == '__main__':
user_input = input('Enter numbers separated by a comma:\n').strip()
unsorted = [int(item) for item in user_input.split(',')]
cocktail_shaker_sort(unsorted)
print(unsorted)
| []
| []
| []
|
archives/1098994933_python.zip | sorts/comb_sort.py | """
Comb sort is a relatively simple sorting algorithm originally designed by Wlodzimierz Dobosiewicz in 1980.
Later it was rediscovered by Stephen Lacey and Richard Box in 1991. Comb sort improves on bubble sort.
This is pure python implementation of comb sort algorithm
For doctests run following command:
python -m doctest -v comb_sort.py
or
python3 -m doctest -v comb_sort.py
For manual testing run:
python comb_sort.py
"""
def comb_sort(data):
"""Pure implementation of comb sort algorithm in Python
:param collection: some mutable ordered collection with heterogeneous
comparable items inside
:return: the same collection ordered by ascending
Examples:
>>> comb_sort([0, 5, 3, 2, 2])
[0, 2, 2, 3, 5]
>>> comb_sort([])
[]
>>> comb_sort([-2, -5, -45])
[-45, -5, -2]
"""
shrink_factor = 1.3
gap = len(data)
swapped = True
i = 0
while gap > 1 or swapped:
# Update the gap value for a next comb
gap = int(float(gap) / shrink_factor)
swapped = False
i = 0
while gap + i < len(data):
if data[i] > data[i+gap]:
# Swap values
data[i], data[i+gap] = data[i+gap], data[i]
swapped = True
i += 1
return data
if __name__ == '__main__':
user_input = input('Enter numbers separated by a comma:\n').strip()
unsorted = [int(item) for item in user_input.split(',')]
print(comb_sort(unsorted))
| []
| []
| []
|
archives/1098994933_python.zip | sorts/counting_sort.py | """
This is pure python implementation of counting sort algorithm
For doctests run following command:
python -m doctest -v counting_sort.py
or
python3 -m doctest -v counting_sort.py
For manual testing run:
python counting_sort.py
"""
def counting_sort(collection):
"""Pure implementation of counting sort algorithm in Python
:param collection: some mutable ordered collection with heterogeneous
comparable items inside
:return: the same collection ordered by ascending
Examples:
>>> counting_sort([0, 5, 3, 2, 2])
[0, 2, 2, 3, 5]
>>> counting_sort([])
[]
>>> counting_sort([-2, -5, -45])
[-45, -5, -2]
"""
# if the collection is empty, returns empty
if collection == []:
return []
# get some information about the collection
coll_len = len(collection)
coll_max = max(collection)
coll_min = min(collection)
# create the counting array
counting_arr_length = coll_max + 1 - coll_min
counting_arr = [0] * counting_arr_length
# count how much a number appears in the collection
for number in collection:
counting_arr[number - coll_min] += 1
# sum each position with it's predecessors. now, counting_arr[i] tells
# us how many elements <= i has in the collection
for i in range(1, counting_arr_length):
counting_arr[i] = counting_arr[i] + counting_arr[i-1]
# create the output collection
ordered = [0] * coll_len
# place the elements in the output, respecting the original order (stable
# sort) from end to begin, updating counting_arr
for i in reversed(range(0, coll_len)):
ordered[counting_arr[collection[i] - coll_min]-1] = collection[i]
counting_arr[collection[i] - coll_min] -= 1
return ordered
def counting_sort_string(string):
"""
>>> counting_sort_string("thisisthestring")
'eghhiiinrsssttt'
"""
return ''.join([chr(i) for i in counting_sort([ord(c) for c in string])])
if __name__ == '__main__':
# Test string sort
assert "eghhiiinrsssttt" == counting_sort_string("thisisthestring")
user_input = input('Enter numbers separated by a comma:\n').strip()
unsorted = [int(item) for item in user_input.split(',')]
print(counting_sort(unsorted))
| []
| []
| []
|
archives/1098994933_python.zip | sorts/cycle_sort.py | # Code contributed by Honey Sharma
def cycle_sort(array):
ans = 0
# Pass through the array to find cycles to rotate.
for cycleStart in range(0, len(array) - 1):
item = array[cycleStart]
# finding the position for putting the item.
pos = cycleStart
for i in range(cycleStart + 1, len(array)):
if array[i] < item:
pos += 1
# If the item is already present-not a cycle.
if pos == cycleStart:
continue
# Otherwise, put the item there or right after any duplicates.
while item == array[pos]:
pos += 1
array[pos], item = item, array[pos]
ans += 1
# Rotate the rest of the cycle.
while pos != cycleStart:
# Find where to put the item.
pos = cycleStart
for i in range(cycleStart + 1, len(array)):
if array[i] < item:
pos += 1
# Put the item there or right after any duplicates.
while item == array[pos]:
pos += 1
array[pos], item = item, array[pos]
ans += 1
return ans
# Main Code starts here
if __name__ == '__main__':
user_input = input('Enter numbers separated by a comma:\n')
unsorted = [int(item) for item in user_input.split(',')]
n = len(unsorted)
cycle_sort(unsorted)
print("After sort : ")
for i in range(0, n):
print(unsorted[i], end=' ')
| []
| []
| []
|
archives/1098994933_python.zip | sorts/external_sort.py | #!/usr/bin/env python
#
# Sort large text files in a minimum amount of memory
#
import os
import argparse
class FileSplitter(object):
BLOCK_FILENAME_FORMAT = 'block_{0}.dat'
def __init__(self, filename):
self.filename = filename
self.block_filenames = []
def write_block(self, data, block_number):
filename = self.BLOCK_FILENAME_FORMAT.format(block_number)
with open(filename, 'w') as file:
file.write(data)
self.block_filenames.append(filename)
def get_block_filenames(self):
return self.block_filenames
def split(self, block_size, sort_key=None):
i = 0
with open(self.filename) as file:
while True:
lines = file.readlines(block_size)
if lines == []:
break
if sort_key is None:
lines.sort()
else:
lines.sort(key=sort_key)
self.write_block(''.join(lines), i)
i += 1
def cleanup(self):
map(lambda f: os.remove(f), self.block_filenames)
class NWayMerge(object):
def select(self, choices):
min_index = -1
min_str = None
for i in range(len(choices)):
if min_str is None or choices[i] < min_str:
min_index = i
return min_index
class FilesArray(object):
def __init__(self, files):
self.files = files
self.empty = set()
self.num_buffers = len(files)
self.buffers = {i: None for i in range(self.num_buffers)}
def get_dict(self):
return {i: self.buffers[i] for i in range(self.num_buffers) if i not in self.empty}
def refresh(self):
for i in range(self.num_buffers):
if self.buffers[i] is None and i not in self.empty:
self.buffers[i] = self.files[i].readline()
if self.buffers[i] == '':
self.empty.add(i)
self.files[i].close()
if len(self.empty) == self.num_buffers:
return False
return True
def unshift(self, index):
value = self.buffers[index]
self.buffers[index] = None
return value
class FileMerger(object):
def __init__(self, merge_strategy):
self.merge_strategy = merge_strategy
def merge(self, filenames, outfilename, buffer_size):
buffers = FilesArray(self.get_file_handles(filenames, buffer_size))
with open(outfilename, 'w', buffer_size) as outfile:
while buffers.refresh():
min_index = self.merge_strategy.select(buffers.get_dict())
outfile.write(buffers.unshift(min_index))
def get_file_handles(self, filenames, buffer_size):
files = {}
for i in range(len(filenames)):
files[i] = open(filenames[i], 'r', buffer_size)
return files
class ExternalSort(object):
def __init__(self, block_size):
self.block_size = block_size
def sort(self, filename, sort_key=None):
num_blocks = self.get_number_blocks(filename, self.block_size)
splitter = FileSplitter(filename)
splitter.split(self.block_size, sort_key)
merger = FileMerger(NWayMerge())
buffer_size = self.block_size / (num_blocks + 1)
merger.merge(splitter.get_block_filenames(), filename + '.out', buffer_size)
splitter.cleanup()
def get_number_blocks(self, filename, block_size):
return (os.stat(filename).st_size / block_size) + 1
def parse_memory(string):
if string[-1].lower() == 'k':
return int(string[:-1]) * 1024
elif string[-1].lower() == 'm':
return int(string[:-1]) * 1024 * 1024
elif string[-1].lower() == 'g':
return int(string[:-1]) * 1024 * 1024 * 1024
else:
return int(string)
def main():
parser = argparse.ArgumentParser()
parser.add_argument('-m',
'--mem',
help='amount of memory to use for sorting',
default='100M')
parser.add_argument('filename',
metavar='<filename>',
nargs=1,
help='name of file to sort')
args = parser.parse_args()
sorter = ExternalSort(parse_memory(args.mem))
sorter.sort(args.filename[0])
if __name__ == '__main__':
main()
| []
| []
| []
|
archives/1098994933_python.zip | sorts/gnome_sort.py | """Gnome Sort Algorithm."""
def gnome_sort(unsorted):
"""Pure implementation of the gnome sort algorithm in Python."""
if len(unsorted) <= 1:
return unsorted
i = 1
while i < len(unsorted):
if unsorted[i - 1] <= unsorted[i]:
i += 1
else:
unsorted[i - 1], unsorted[i] = unsorted[i], unsorted[i - 1]
i -= 1
if (i == 0):
i = 1
if __name__ == '__main__':
user_input = input('Enter numbers separated by a comma:\n').strip()
unsorted = [int(item) for item in user_input.split(',')]
gnome_sort(unsorted)
print(unsorted)
| []
| []
| []
|
archives/1098994933_python.zip | sorts/heap_sort.py | '''
This is a pure python implementation of the heap sort algorithm.
For doctests run following command:
python -m doctest -v heap_sort.py
or
python3 -m doctest -v heap_sort.py
For manual testing run:
python heap_sort.py
'''
def heapify(unsorted, index, heap_size):
largest = index
left_index = 2 * index + 1
right_index = 2 * index + 2
if left_index < heap_size and unsorted[left_index] > unsorted[largest]:
largest = left_index
if right_index < heap_size and unsorted[right_index] > unsorted[largest]:
largest = right_index
if largest != index:
unsorted[largest], unsorted[index] = unsorted[index], unsorted[largest]
heapify(unsorted, largest, heap_size)
def heap_sort(unsorted):
'''
Pure implementation of the heap sort algorithm in Python
:param collection: some mutable ordered collection with heterogeneous
comparable items inside
:return: the same collection ordered by ascending
Examples:
>>> heap_sort([0, 5, 3, 2, 2])
[0, 2, 2, 3, 5]
>>> heap_sort([])
[]
>>> heap_sort([-2, -5, -45])
[-45, -5, -2]
'''
n = len(unsorted)
for i in range(n // 2 - 1, -1, -1):
heapify(unsorted, i, n)
for i in range(n - 1, 0, -1):
unsorted[0], unsorted[i] = unsorted[i], unsorted[0]
heapify(unsorted, 0, i)
return unsorted
if __name__ == '__main__':
user_input = input('Enter numbers separated by a comma:\n').strip()
unsorted = [int(item) for item in user_input.split(',')]
print(heap_sort(unsorted))
| []
| []
| []
|
archives/1098994933_python.zip | sorts/insertion_sort.py | """
This is a pure python implementation of the insertion sort algorithm
For doctests run following command:
python -m doctest -v insertion_sort.py
or
python3 -m doctest -v insertion_sort.py
For manual testing run:
python insertion_sort.py
"""
def insertion_sort(collection):
"""Pure implementation of the insertion sort algorithm in Python
:param collection: some mutable ordered collection with heterogeneous
comparable items inside
:return: the same collection ordered by ascending
Examples:
>>> insertion_sort([0, 5, 3, 2, 2])
[0, 2, 2, 3, 5]
>>> insertion_sort([])
[]
>>> insertion_sort([-2, -5, -45])
[-45, -5, -2]
"""
for loop_index in range(1, len(collection)):
insertion_index = loop_index
while insertion_index > 0 and collection[insertion_index - 1] > collection[insertion_index]:
collection[insertion_index], collection[insertion_index - 1] = collection[insertion_index - 1], collection[insertion_index]
insertion_index -= 1
return collection
if __name__ == '__main__':
user_input = input('Enter numbers separated by a comma:\n').strip()
unsorted = [int(item) for item in user_input.split(',')]
print(insertion_sort(unsorted))
| []
| []
| []
|
archives/1098994933_python.zip | sorts/merge_sort.py | """
This is a pure python implementation of the merge sort algorithm
For doctests run following command:
python -m doctest -v merge_sort.py
or
python3 -m doctest -v merge_sort.py
For manual testing run:
python merge_sort.py
"""
def merge_sort(collection):
"""Pure implementation of the merge sort algorithm in Python
:param collection: some mutable ordered collection with heterogeneous
comparable items inside
:return: the same collection ordered by ascending
Examples:
>>> merge_sort([0, 5, 3, 2, 2])
[0, 2, 2, 3, 5]
>>> merge_sort([])
[]
>>> merge_sort([-2, -5, -45])
[-45, -5, -2]
"""
def merge(left, right):
'''merge left and right
:param left: left collection
:param right: right collection
:return: merge result
'''
result = []
while left and right:
result.append((left if left[0] <= right[0] else right).pop(0))
return result + left + right
if len(collection) <= 1:
return collection
mid = len(collection) // 2
return merge(merge_sort(collection[:mid]), merge_sort(collection[mid:]))
if __name__ == '__main__':
user_input = input('Enter numbers separated by a comma:\n').strip()
unsorted = [int(item) for item in user_input.split(',')]
print(*merge_sort(unsorted), sep=',')
| []
| []
| []
|
archives/1098994933_python.zip | sorts/merge_sort_fastest.py | '''
Python implementation of the fastest merge sort algorithm.
Takes an average of 0.6 microseconds to sort a list of length 1000 items.
Best Case Scenario : O(n)
Worst Case Scenario : O(n^2) because native python functions:min, max and remove are already O(n)
'''
def merge_sort(collection):
"""Pure implementation of the fastest merge sort algorithm in Python
:param collection: some mutable ordered collection with heterogeneous
comparable items inside
:return: a collection ordered by ascending
Examples:
>>> merge_sort([0, 5, 3, 2, 2])
[0, 2, 2, 3, 5]
>>> merge_sort([])
[]
>>> merge_sort([-2, -5, -45])
[-45, -5, -2]
"""
start, end = [], []
while len(collection) > 1:
min_one, max_one = min(collection), max(collection)
start.append(min_one)
end.append(max_one)
collection.remove(min_one)
collection.remove(max_one)
end.reverse()
return start + collection + end
if __name__ == '__main__':
user_input = input('Enter numbers separated by a comma:\n').strip()
unsorted = [int(item) for item in user_input.split(',')]
print(*merge_sort(unsorted), sep=',')
| []
| []
| []
|
archives/1098994933_python.zip | sorts/odd_even_transposition_parallel.py | """
This is an implementation of odd-even transposition sort.
It works by performing a series of parallel swaps between odd and even pairs of
variables in the list.
This implementation represents each variable in the list with a process and
each process communicates with its neighboring processes in the list to perform
comparisons.
They are synchronized with locks and message passing but other forms of
synchronization could be used.
"""
from multiprocessing import Process, Pipe, Lock
#lock used to ensure that two processes do not access a pipe at the same time
processLock = Lock()
"""
The function run by the processes that sorts the list
position = the position in the list the prcoess represents, used to know which
neighbor we pass our value to
value = the initial value at list[position]
LSend, RSend = the pipes we use to send to our left and right neighbors
LRcv, RRcv = the pipes we use to receive from our left and right neighbors
resultPipe = the pipe used to send results back to main
"""
def oeProcess(position, value, LSend, RSend, LRcv, RRcv, resultPipe):
global processLock
#we perform n swaps since after n swaps we know we are sorted
#we *could* stop early if we are sorted already, but it takes as long to
#find out we are sorted as it does to sort the list with this algorithm
for i in range(0, 10):
if( (i + position) % 2 == 0 and RSend != None):
#send your value to your right neighbor
processLock.acquire()
RSend[1].send(value)
processLock.release()
#receive your right neighbor's value
processLock.acquire()
temp = RRcv[0].recv()
processLock.release()
#take the lower value since you are on the left
value = min(value, temp)
elif( (i + position) % 2 != 0 and LSend != None):
#send your value to your left neighbor
processLock.acquire()
LSend[1].send(value)
processLock.release()
#receive your left neighbor's value
processLock.acquire()
temp = LRcv[0].recv()
processLock.release()
#take the higher value since you are on the right
value = max(value, temp)
#after all swaps are performed, send the values back to main
resultPipe[1].send(value)
"""
the function which creates the processes that perform the parallel swaps
arr = the list to be sorted
"""
def OddEvenTransposition(arr):
processArray = []
resultPipe = []
#initialize the list of pipes where the values will be retrieved
for _ in arr:
resultPipe.append(Pipe())
#creates the processes
#the first and last process only have one neighbor so they are made outside
#of the loop
tempRs = Pipe()
tempRr = Pipe()
processArray.append(Process(target = oeProcess, args = (0, arr[0], None, tempRs, None, tempRr, resultPipe[0])))
tempLr = tempRs
tempLs = tempRr
for i in range(1, len(arr) - 1):
tempRs = Pipe()
tempRr = Pipe()
processArray.append(Process(target = oeProcess, args = (i, arr[i], tempLs, tempRs, tempLr, tempRr, resultPipe[i])))
tempLr = tempRs
tempLs = tempRr
processArray.append(Process(target = oeProcess, args = (len(arr) - 1, arr[len(arr) - 1], tempLs, None, tempLr, None, resultPipe[len(arr) - 1])))
#start the processes
for p in processArray:
p.start()
#wait for the processes to end and write their values to the list
for p in range(0, len(resultPipe)):
arr[p] = resultPipe[p][0].recv()
processArray[p].join()
return(arr)
#creates a reverse sorted list and sorts it
def main():
arr = []
for i in range(10, 0, -1):
arr.append(i)
print("Initial List")
print(*arr)
list = OddEvenTransposition(arr)
print("Sorted List\n")
print(*arr)
if __name__ == "__main__":
main()
| []
| []
| []
|
archives/1098994933_python.zip | sorts/odd_even_transposition_single_threaded.py | """
This is a non-parallelized implementation of odd-even transpostiion sort.
Normally the swaps in each set happen simultaneously, without that the algorithm
is no better than bubble sort.
"""
def OddEvenTransposition(arr):
for i in range(0, len(arr)):
for i in range(i % 2, len(arr) - 1, 2):
if arr[i + 1] < arr[i]:
arr[i], arr[i + 1] = arr[i + 1], arr[i]
print(*arr)
return arr
#creates a list and sorts it
def main():
list = []
for i in range(10, 0, -1):
list.append(i)
print("Initial List")
print(*list)
list = OddEvenTransposition(list)
print("Sorted List\n")
print(*list)
if __name__ == "__main__":
main()
| []
| []
| []
|
archives/1098994933_python.zip | sorts/pancake_sort.py | """Pancake Sort Algorithm."""
# Only can reverse array from 0 to i
def pancake_sort(arr):
"""Sort Array with Pancake Sort."""
cur = len(arr)
while cur > 1:
# Find the maximum number in arr
mi = arr.index(max(arr[0:cur]))
# Reverse from 0 to mi
arr = arr[mi::-1] + arr[mi + 1:len(arr)]
# Reverse whole list
arr = arr[cur - 1::-1] + arr[cur:len(arr)]
cur -= 1
return arr
if __name__ == '__main__':
print(pancake_sort([0, 10, 15, 3, 2, 9, 14, 13]))
| []
| []
| []
|
archives/1098994933_python.zip | sorts/pigeon_sort.py | '''
This is an implementation of Pigeon Hole Sort.
'''
def pigeon_sort(array):
# Manually finds the minimum and maximum of the array.
min = array[0]
max = array[0]
for i in range(len(array)):
if(array[i] < min): min = array[i]
elif(array[i] > max): max = array[i]
# Compute the variables
holes_range = max-min + 1
holes = [0 for _ in range(holes_range)]
holes_repeat = [0 for _ in range(holes_range)]
# Make the sorting.
for i in range(len(array)):
index = array[i] - min
if(holes[index] != array[i]):
holes[index] = array[i]
holes_repeat[index] += 1
else: holes_repeat[index] += 1
# Makes the array back by replacing the numbers.
index = 0
for i in range(holes_range):
while(holes_repeat[i] > 0):
array[index] = holes[i]
index += 1
holes_repeat[i] -= 1
# Returns the sorted array.
return array
if __name__ == '__main__':
user_input = input('Enter numbers separated by comma:\n')
unsorted = [int(x) for x in user_input.split(',')]
sorted = pigeon_sort(unsorted)
print(sorted)
| []
| []
| []
|
archives/1098994933_python.zip | sorts/quick_sort.py | """
This is a pure python implementation of the quick sort algorithm
For doctests run following command:
python -m doctest -v quick_sort.py
or
python3 -m doctest -v quick_sort.py
For manual testing run:
python quick_sort.py
"""
def quick_sort(collection):
"""Pure implementation of quick sort algorithm in Python
:param collection: some mutable ordered collection with heterogeneous
comparable items inside
:return: the same collection ordered by ascending
Examples:
>>> quick_sort([0, 5, 3, 2, 2])
[0, 2, 2, 3, 5]
>>> quick_sort([])
[]
>>> quick_sort([-2, -5, -45])
[-45, -5, -2]
"""
length = len(collection)
if length <= 1:
return collection
else:
# Use the last element as the first pivot
pivot = collection.pop()
# Put elements greater than pivot in greater list
# Put elements lesser than pivot in lesser list
greater, lesser = [], []
for element in collection:
if element > pivot:
greater.append(element)
else:
lesser.append(element)
return quick_sort(lesser) + [pivot] + quick_sort(greater)
if __name__ == '__main__':
user_input = input('Enter numbers separated by a comma:\n').strip()
unsorted = [ int(item) for item in user_input.split(',') ]
print( quick_sort(unsorted) )
| []
| []
| []
|
archives/1098994933_python.zip | sorts/quick_sort_3_partition.py | def quick_sort_3partition(sorting, left, right):
if right <= left:
return
a = i = left
b = right
pivot = sorting[left]
while i <= b:
if sorting[i] < pivot:
sorting[a], sorting[i] = sorting[i], sorting[a]
a += 1
i += 1
elif sorting[i] > pivot:
sorting[b], sorting[i] = sorting[i], sorting[b]
b -= 1
else:
i += 1
quick_sort_3partition(sorting, left, a - 1)
quick_sort_3partition(sorting, b + 1, right)
if __name__ == '__main__':
user_input = input('Enter numbers separated by a comma:\n').strip()
unsorted = [ int(item) for item in user_input.split(',') ]
quick_sort_3partition(unsorted,0,len(unsorted)-1)
print(unsorted)
| []
| []
| []
|
archives/1098994933_python.zip | sorts/radix_sort.py | def radix_sort(lst):
RADIX = 10
placement = 1
# get the maximum number
max_digit = max(lst)
while placement < max_digit:
# declare and initialize buckets
buckets = [list() for _ in range( RADIX )]
# split lst between lists
for i in lst:
tmp = int((i / placement) % RADIX)
buckets[tmp].append(i)
# empty lists into lst array
a = 0
for b in range( RADIX ):
buck = buckets[b]
for i in buck:
lst[a] = i
a += 1
# move to next
placement *= RADIX
| []
| []
| []
|
archives/1098994933_python.zip | sorts/random_normal_distribution_quicksort.py | from random import randint
from tempfile import TemporaryFile
import numpy as np
def _inPlaceQuickSort(A,start,end):
count = 0
if start<end:
pivot=randint(start,end)
temp=A[end]
A[end]=A[pivot]
A[pivot]=temp
p,count= _inPlacePartition(A,start,end)
count += _inPlaceQuickSort(A,start,p-1)
count += _inPlaceQuickSort(A,p+1,end)
return count
def _inPlacePartition(A,start,end):
count = 0
pivot= randint(start,end)
temp=A[end]
A[end]=A[pivot]
A[pivot]=temp
newPivotIndex=start-1
for index in range(start,end):
count += 1
if A[index]<A[end]:#check if current val is less than pivot value
newPivotIndex=newPivotIndex+1
temp=A[newPivotIndex]
A[newPivotIndex]=A[index]
A[index]=temp
temp=A[newPivotIndex+1]
A[newPivotIndex+1]=A[end]
A[end]=temp
return newPivotIndex+1,count
outfile = TemporaryFile()
p = 100 # 1000 elements are to be sorted
mu, sigma = 0, 1 # mean and standard deviation
X = np.random.normal(mu, sigma, p)
np.save(outfile, X)
print('The array is')
print(X)
outfile.seek(0) # using the same array
M = np.load(outfile)
r = (len(M)-1)
z = _inPlaceQuickSort(M,0,r)
print("No of Comparisons for 100 elements selected from a standard normal distribution is :")
print(z)
| []
| []
| []
|
archives/1098994933_python.zip | sorts/random_pivot_quick_sort.py | """
Picks the random index as the pivot
"""
import random
def partition(A, left_index, right_index):
pivot = A[left_index]
i = left_index + 1
for j in range(left_index + 1, right_index):
if A[j] < pivot:
A[j], A[i] = A[i], A[j]
i += 1
A[left_index], A[i - 1] = A[i - 1], A[left_index]
return i - 1
def quick_sort_random(A, left, right):
if left < right:
pivot = random.randint(left, right - 1)
A[pivot], A[left] = A[left], A[pivot] #switches the pivot with the left most bound
pivot_index = partition(A, left, right)
quick_sort_random(A, left, pivot_index) #recursive quicksort to the left of the pivot point
quick_sort_random(A, pivot_index + 1, right) #recursive quicksort to the right of the pivot point
def main():
user_input = input('Enter numbers separated by a comma:\n').strip()
arr = [int(item) for item in user_input.split(',')]
quick_sort_random(arr, 0, len(arr))
print(arr)
if __name__ == "__main__":
main() | []
| []
| []
|
archives/1098994933_python.zip | sorts/selection_sort.py | """
This is a pure python implementation of the selection sort algorithm
For doctests run following command:
python -m doctest -v selection_sort.py
or
python3 -m doctest -v selection_sort.py
For manual testing run:
python selection_sort.py
"""
def selection_sort(collection):
"""Pure implementation of the selection sort algorithm in Python
:param collection: some mutable ordered collection with heterogeneous
comparable items inside
:return: the same collection ordered by ascending
Examples:
>>> selection_sort([0, 5, 3, 2, 2])
[0, 2, 2, 3, 5]
>>> selection_sort([])
[]
>>> selection_sort([-2, -5, -45])
[-45, -5, -2]
"""
length = len(collection)
for i in range(length - 1):
least = i
for k in range(i + 1, length):
if collection[k] < collection[least]:
least = k
collection[least], collection[i] = (
collection[i], collection[least]
)
return collection
if __name__ == '__main__':
user_input = input('Enter numbers separated by a comma:\n').strip()
unsorted = [int(item) for item in user_input.split(',')]
print(selection_sort(unsorted))
| []
| []
| []
|
archives/1098994933_python.zip | sorts/shell_sort.py | """
This is a pure python implementation of the shell sort algorithm
For doctests run following command:
python -m doctest -v shell_sort.py
or
python3 -m doctest -v shell_sort.py
For manual testing run:
python shell_sort.py
"""
def shell_sort(collection):
"""Pure implementation of shell sort algorithm in Python
:param collection: Some mutable ordered collection with heterogeneous
comparable items inside
:return: the same collection ordered by ascending
>>> shell_sort([0, 5, 3, 2, 2])
[0, 2, 2, 3, 5]
>>> shell_sort([])
[]
>>> shell_sort([-2, -5, -45])
[-45, -5, -2]
"""
# Marcin Ciura's gap sequence
gaps = [701, 301, 132, 57, 23, 10, 4, 1]
for gap in gaps:
i = gap
while i < len(collection):
temp = collection[i]
j = i
while j >= gap and collection[j - gap] > temp:
collection[j] = collection[j - gap]
j -= gap
collection[j] = temp
i += 1
return collection
if __name__ == '__main__':
user_input = input('Enter numbers separated by a comma:\n').strip()
unsorted = [int(item) for item in user_input.split(',')]
print(shell_sort(unsorted))
| []
| []
| []
|
archives/1098994933_python.zip | sorts/tim_sort.py | def binary_search(lst, item, start, end):
if start == end:
return start if lst[start] > item else start + 1
if start > end:
return start
mid = (start + end) // 2
if lst[mid] < item:
return binary_search(lst, item, mid + 1, end)
elif lst[mid] > item:
return binary_search(lst, item, start, mid - 1)
else:
return mid
def insertion_sort(lst):
length = len(lst)
for index in range(1, length):
value = lst[index]
pos = binary_search(lst, value, 0, index - 1)
lst = lst[:pos] + [value] + lst[pos:index] + lst[index + 1 :]
return lst
def merge(left, right):
if not left:
return right
if not right:
return left
if left[0] < right[0]:
return [left[0]] + merge(left[1:], right)
return [right[0]] + merge(left, right[1:])
def tim_sort(lst):
"""
>>> tim_sort("Python")
['P', 'h', 'n', 'o', 't', 'y']
>>> tim_sort((1.1, 1, 0, -1, -1.1))
[-1.1, -1, 0, 1, 1.1]
>>> tim_sort(list(reversed(list(range(7)))))
[0, 1, 2, 3, 4, 5, 6]
>>> tim_sort([3, 2, 1]) == insertion_sort([3, 2, 1])
True
>>> tim_sort([3, 2, 1]) == sorted([3, 2, 1])
True
"""
length = len(lst)
runs, sorted_runs = [], []
new_run = [lst[0]]
sorted_array = []
i = 1
while i < length:
if lst[i] < lst[i - 1]:
runs.append(new_run)
new_run = [lst[i]]
else:
new_run.append(lst[i])
i += 1
runs.append(new_run)
for run in runs:
sorted_runs.append(insertion_sort(run))
for run in sorted_runs:
sorted_array = merge(sorted_array, run)
return sorted_array
def main():
lst = [5, 9, 10, 3, -4, 5, 178, 92, 46, -18, 0, 7]
sorted_lst = tim_sort(lst)
print(sorted_lst)
if __name__ == "__main__":
main()
| []
| []
| []
|
archives/1098994933_python.zip | sorts/topological_sort.py | """Topological Sort."""
# a
# / \
# b c
# / \
# d e
edges = {'a': ['c', 'b'], 'b': ['d', 'e'], 'c': [], 'd': [], 'e': []}
vertices = ['a', 'b', 'c', 'd', 'e']
def topological_sort(start, visited, sort):
"""Perform topolical sort on a directed acyclic graph."""
current = start
# add current to visited
visited.append(current)
neighbors = edges[current]
for neighbor in neighbors:
# if neighbor not in visited, visit
if neighbor not in visited:
sort = topological_sort(neighbor, visited, sort)
# if all neighbors visited add current to sort
sort.append(current)
# if all vertices haven't been visited select a new one to visit
if len(visited) != len(vertices):
for vertice in vertices:
if vertice not in visited:
sort = topological_sort(vertice, visited, sort)
# return sort
return sort
if __name__ == '__main__':
sort = topological_sort('a', [], [])
print(sort)
| []
| []
| []
|
archives/1098994933_python.zip | sorts/tree_sort.py | """
Tree_sort algorithm.
Build a BST and in order traverse.
"""
class node():
# BST data structure
def __init__(self, val):
self.val = val
self.left = None
self.right = None
def insert(self, val):
if self.val:
if val < self.val:
if self.left is None:
self.left = node(val)
else:
self.left.insert(val)
elif val > self.val:
if self.right is None:
self.right = node(val)
else:
self.right.insert(val)
else:
self.val = val
def inorder(root, res):
# Recursive travesal
if root:
inorder(root.left, res)
res.append(root.val)
inorder(root.right, res)
def tree_sort(arr):
# Build BST
if len(arr) == 0:
return arr
root = node(arr[0])
for i in range(1, len(arr)):
root.insert(arr[i])
# Traverse BST in order.
res = []
inorder(root, res)
return res
if __name__ == '__main__':
print(tree_sort([10, 1, 3, 2, 9, 14, 13]))
| []
| []
| []
|
archives/1098994933_python.zip | sorts/wiggle_sort.py | """
Wiggle Sort.
Given an unsorted array nums, reorder it such
that nums[0] < nums[1] > nums[2] < nums[3]....
For example:
if input numbers = [3, 5, 2, 1, 6, 4]
one possible Wiggle Sorted answer is [3, 5, 1, 6, 2, 4].
"""
def wiggle_sort(nums):
"""Perform Wiggle Sort."""
for i in range(len(nums)):
if (i % 2 == 1) == (nums[i - 1] > nums[i]):
nums[i - 1], nums[i] = nums[i], nums[i - 1]
if __name__ == '__main__':
print("Enter the array elements:\n")
array = list(map(int, input().split()))
print("The unsorted array is:\n")
print(array)
wiggle_sort(array)
print("Array after Wiggle sort:\n")
print(array)
| []
| []
| []
|
archives/1098994933_python.zip | strings/boyer_moore_search.py | """
The algorithm finds the pattern in given text using following rule.
The bad-character rule considers the mismatched character in Text.
The next occurrence of that character to the left in Pattern is found,
If the mismatched character occurs to the left in Pattern,
a shift is proposed that aligns text block and pattern.
If the mismatched character does not occur to the left in Pattern,
a shift is proposed that moves the entirety of Pattern past
the point of mismatch in the text.
If there no mismatch then the pattern matches with text block.
Time Complexity : O(n/m)
n=length of main string
m=length of pattern string
"""
class BoyerMooreSearch:
def __init__(self, text, pattern):
self.text, self.pattern = text, pattern
self.textLen, self.patLen = len(text), len(pattern)
def match_in_pattern(self, char):
""" finds the index of char in pattern in reverse order
Paremeters :
char (chr): character to be searched
Returns :
i (int): index of char from last in pattern
-1 (int): if char is not found in pattern
"""
for i in range(self.patLen-1, -1, -1):
if char == self.pattern[i]:
return i
return -1
def mismatch_in_text(self, currentPos):
""" finds the index of mis-matched character in text when compared with pattern from last
Paremeters :
currentPos (int): current index position of text
Returns :
i (int): index of mismatched char from last in text
-1 (int): if there is no mis-match between pattern and text block
"""
for i in range(self.patLen-1, -1, -1):
if self.pattern[i] != self.text[currentPos + i]:
return currentPos + i
return -1
def bad_character_heuristic(self):
# searches pattern in text and returns index positions
positions = []
for i in range(self.textLen - self.patLen + 1):
mismatch_index = self.mismatch_in_text(i)
if mismatch_index == -1:
positions.append(i)
else:
match_index = self.match_in_pattern(self.text[mismatch_index])
i = mismatch_index - match_index #shifting index
return positions
text = "ABAABA"
pattern = "AB"
bms = BoyerMooreSearch(text, pattern)
positions = bms.bad_character_heuristic()
if len(positions) == 0:
print("No match found")
else:
print("Pattern found in following positions: ")
print(positions)
| []
| []
| []
|
archives/1098994933_python.zip | strings/knuth_morris_pratt.py | def kmp(pattern, text):
"""
The Knuth-Morris-Pratt Algorithm for finding a pattern within a piece of text
with complexity O(n + m)
1) Preprocess pattern to identify any suffixes that are identical to prefixes
This tells us where to continue from if we get a mismatch between a character in our pattern
and the text.
2) Step through the text one character at a time and compare it to a character in the pattern
updating our location within the pattern if necessary
"""
# 1) Construct the failure array
failure = get_failure_array(pattern)
# 2) Step through text searching for pattern
i, j = 0, 0 # index into text, pattern
while i < len(text):
if pattern[j] == text[i]:
if j == (len(pattern) - 1):
return True
j += 1
# if this is a prefix in our pattern
# just go back far enough to continue
elif j > 0:
j = failure[j - 1]
continue
i += 1
return False
def get_failure_array(pattern):
"""
Calculates the new index we should go to if we fail a comparison
:param pattern:
:return:
"""
failure = [0]
i = 0
j = 1
while j < len(pattern):
if pattern[i] == pattern[j]:
i += 1
elif i > 0:
i = failure[i-1]
continue
j += 1
failure.append(i)
return failure
if __name__ == '__main__':
# Test 1)
pattern = "abc1abc12"
text1 = "alskfjaldsabc1abc1abc12k23adsfabcabc"
text2 = "alskfjaldsk23adsfabcabc"
assert kmp(pattern, text1) and not kmp(pattern, text2)
# Test 2)
pattern = "ABABX"
text = "ABABZABABYABABX"
assert kmp(pattern, text)
# Test 3)
pattern = "AAAB"
text = "ABAAAAAB"
assert kmp(pattern, text)
# Test 4)
pattern = "abcdabcy"
text = "abcxabcdabxabcdabcdabcy"
assert kmp(pattern, text)
# Test 5)
pattern = "aabaabaaa"
assert get_failure_array(pattern) == [0, 1, 0, 1, 2, 3, 4, 5, 2]
| []
| []
| []
|
archives/1098994933_python.zip | strings/levenshtein_distance.py | """
This is a Python implementation of the levenshtein distance.
Levenshtein distance is a string metric for measuring the
difference between two sequences.
For doctests run following command:
python -m doctest -v levenshtein-distance.py
or
python3 -m doctest -v levenshtein-distance.py
For manual testing run:
python levenshtein-distance.py
"""
def levenshtein_distance(first_word, second_word):
"""Implementation of the levenshtein distance in Python.
:param first_word: the first word to measure the difference.
:param second_word: the second word to measure the difference.
:return: the levenshtein distance between the two words.
Examples:
>>> levenshtein_distance("planet", "planetary")
3
>>> levenshtein_distance("", "test")
4
>>> levenshtein_distance("book", "back")
2
>>> levenshtein_distance("book", "book")
0
>>> levenshtein_distance("test", "")
4
>>> levenshtein_distance("", "")
0
>>> levenshtein_distance("orchestration", "container")
10
"""
# The longer word should come first
if len(first_word) < len(second_word):
return levenshtein_distance(second_word, first_word)
if len(second_word) == 0:
return len(first_word)
previous_row = range(len(second_word) + 1)
for i, c1 in enumerate(first_word):
current_row = [i + 1]
for j, c2 in enumerate(second_word):
# Calculate insertions, deletions and substitutions
insertions = previous_row[j + 1] + 1
deletions = current_row[j] + 1
substitutions = previous_row[j] + (c1 != c2)
# Get the minimum to append to the current row
current_row.append(min(insertions, deletions, substitutions))
# Store the previous row
previous_row = current_row
# Returns the last element (distance)
return previous_row[-1]
if __name__ == '__main__':
first_word = input('Enter the first word:\n').strip()
second_word = input('Enter the second word:\n').strip()
result = levenshtein_distance(first_word, second_word)
print('Levenshtein distance between {} and {} is {}'.format(
first_word, second_word, result))
| []
| []
| []
|
archives/1098994933_python.zip | strings/manacher.py | # calculate palindromic length from center with incrementing difference
def palindromic_length( center, diff, string):
if center-diff == -1 or center+diff == len(string) or string[center-diff] != string[center+diff] :
return 0
return 1 + palindromic_length(center, diff+1, string)
def palindromic_string( input_string ):
"""
Manacher’s algorithm which finds Longest Palindromic Substring in linear time.
1. first this conver input_string("xyx") into new_string("x|y|x") where odd positions are actual input
characters.
2. for each character in new_string it find corresponding length and store,
a. max_length
b. max_length's center
3. return output_string from center - max_length to center + max_length and remove all "|"
"""
max_length = 0
# if input_string is "aba" than new_input_string become "a|b|a"
new_input_string = ""
output_string = ""
# append each character + "|" in new_string for range(0, length-1)
for i in input_string[:len(input_string)-1] :
new_input_string += i + "|"
#append last character
new_input_string += input_string[-1]
# for each character in new_string find corresponding palindromic string
for i in range(len(new_input_string)) :
# get palindromic length from ith position
length = palindromic_length(i, 1, new_input_string)
# update max_length and start position
if max_length < length :
max_length = length
start = i
#create that string
for i in new_input_string[start-max_length:start+max_length+1] :
if i != "|":
output_string += i
return output_string
if __name__ == '__main__':
n = input()
print(palindromic_string(n))
| []
| []
| []
|
archives/1098994933_python.zip | strings/min_cost_string_conversion.py | '''
Algorithm for calculating the most cost-efficient sequence for converting one string into another.
The only allowed operations are
---Copy character with cost cC
---Replace character with cost cR
---Delete character with cost cD
---Insert character with cost cI
'''
def compute_transform_tables(X, Y, cC, cR, cD, cI):
X = list(X)
Y = list(Y)
m = len(X)
n = len(Y)
costs = [[0 for _ in range(n+1)] for _ in range(m+1)]
ops = [[0 for _ in range(n+1)] for _ in range(m+1)]
for i in range(1, m+1):
costs[i][0] = i*cD
ops[i][0] = 'D%c' % X[i-1]
for i in range(1, n+1):
costs[0][i] = i*cI
ops[0][i] = 'I%c' % Y[i-1]
for i in range(1, m+1):
for j in range(1, n+1):
if X[i-1] == Y[j-1]:
costs[i][j] = costs[i-1][j-1] + cC
ops[i][j] = 'C%c' % X[i-1]
else:
costs[i][j] = costs[i-1][j-1] + cR
ops[i][j] = 'R%c' % X[i-1] + str(Y[j-1])
if costs[i-1][j] + cD < costs[i][j]:
costs[i][j] = costs[i-1][j] + cD
ops[i][j] = 'D%c' % X[i-1]
if costs[i][j-1] + cI < costs[i][j]:
costs[i][j] = costs[i][j-1] + cI
ops[i][j] = 'I%c' % Y[j-1]
return costs, ops
def assemble_transformation(ops, i, j):
if i == 0 and j == 0:
seq = []
return seq
else:
if ops[i][j][0] == 'C' or ops[i][j][0] == 'R':
seq = assemble_transformation(ops, i-1, j-1)
seq.append(ops[i][j])
return seq
elif ops[i][j][0] == 'D':
seq = assemble_transformation(ops, i-1, j)
seq.append(ops[i][j])
return seq
else:
seq = assemble_transformation(ops, i, j-1)
seq.append(ops[i][j])
return seq
if __name__ == '__main__':
_, operations = compute_transform_tables('Python', 'Algorithms', -1, 1, 2, 2)
m = len(operations)
n = len(operations[0])
sequence = assemble_transformation(operations, m-1, n-1)
string = list('Python')
i = 0
cost = 0
with open('min_cost.txt', 'w') as file:
for op in sequence:
print(''.join(string))
if op[0] == 'C':
file.write('%-16s' % 'Copy %c' % op[1])
file.write('\t\t\t' + ''.join(string))
file.write('\r\n')
cost -= 1
elif op[0] == 'R':
string[i] = op[2]
file.write('%-16s' % ('Replace %c' % op[1] + ' with ' + str(op[2])))
file.write('\t\t' + ''.join(string))
file.write('\r\n')
cost += 1
elif op[0] == 'D':
string.pop(i)
file.write('%-16s' % 'Delete %c' % op[1])
file.write('\t\t\t' + ''.join(string))
file.write('\r\n')
cost += 2
else:
string.insert(i, op[1])
file.write('%-16s' % 'Insert %c' % op[1])
file.write('\t\t\t' + ''.join(string))
file.write('\r\n')
cost += 2
i += 1
print(''.join(string))
print('Cost: ', cost)
file.write('\r\nMinimum cost: ' + str(cost))
| []
| []
| []
|
archives/1098994933_python.zip | strings/naive_string_search.py | """
this algorithm tries to find the pattern from every position of
the mainString if pattern is found from position i it add it to
the answer and does the same for position i+1
Complexity : O(n*m)
n=length of main string
m=length of pattern string
"""
def naivePatternSearch(mainString,pattern):
patLen=len(pattern)
strLen=len(mainString)
position=[]
for i in range(strLen-patLen+1):
match_found=True
for j in range(patLen):
if mainString[i+j]!=pattern[j]:
match_found=False
break
if match_found:
position.append(i)
return position
mainString="ABAAABCDBBABCDDEBCABC"
pattern="ABC"
position=naivePatternSearch(mainString,pattern)
print("Pattern found in position ")
for x in position:
print(x) | []
| []
| []
|
archives/1098994933_python.zip | strings/rabin_karp.py | # Numbers of alphabet which we call base
alphabet_size = 256
# Modulus to hash a string
modulus = 1000003
def rabin_karp(pattern, text):
"""
The Rabin-Karp Algorithm for finding a pattern within a piece of text
with complexity O(nm), most efficient when it is used with multiple patterns
as it is able to check if any of a set of patterns match a section of text in o(1) given the precomputed hashes.
This will be the simple version which only assumes one pattern is being searched for but it's not hard to modify
1) Calculate pattern hash
2) Step through the text one character at a time passing a window with the same length as the pattern
calculating the hash of the text within the window compare it with the hash of the pattern. Only testing
equality if the hashes match
"""
p_len = len(pattern)
t_len = len(text)
if p_len > t_len:
return False
p_hash = 0
text_hash = 0
modulus_power = 1
# Calculating the hash of pattern and substring of text
for i in range(p_len):
p_hash = (ord(pattern[i]) + p_hash * alphabet_size) % modulus
text_hash = (ord(text[i]) + text_hash * alphabet_size) % modulus
if i == p_len - 1:
continue
modulus_power = (modulus_power * alphabet_size) % modulus
for i in range(0, t_len - p_len + 1):
if text_hash == p_hash and text[i : i + p_len] == pattern:
return True
if i == t_len - p_len:
continue
# Calculating the ruling hash
text_hash = (
(text_hash - ord(text[i]) * modulus_power) * alphabet_size
+ ord(text[i + p_len])
) % modulus
return False
def test_rabin_karp():
"""
>>> test_rabin_karp()
Success.
"""
# Test 1)
pattern = "abc1abc12"
text1 = "alskfjaldsabc1abc1abc12k23adsfabcabc"
text2 = "alskfjaldsk23adsfabcabc"
assert rabin_karp(pattern, text1) and not rabin_karp(pattern, text2)
# Test 2)
pattern = "ABABX"
text = "ABABZABABYABABX"
assert rabin_karp(pattern, text)
# Test 3)
pattern = "AAAB"
text = "ABAAAAAB"
assert rabin_karp(pattern, text)
# Test 4)
pattern = "abcdabcy"
text = "abcxabcdabxabcdabcdabcy"
assert rabin_karp(pattern, text)
# Test 5)
pattern = "Lü"
text = "Lüsai"
assert rabin_karp(pattern, text)
pattern = "Lue"
assert not rabin_karp(pattern, text)
print("Success.")
if __name__ == "__main__":
test_rabin_karp()
| []
| []
| []
|
archives/1098994933_python.zip | traversals/binary_tree_traversals.py | """
This is pure python implementation of tree traversal algorithms
"""
import queue
from typing import List
class TreeNode:
def __init__(self, data):
self.data = data
self.right = None
self.left = None
def build_tree():
print("\n********Press N to stop entering at any point of time********\n")
check = input("Enter the value of the root node: ").strip().lower() or "n"
if check == "n":
return None
q: queue.Queue = queue.Queue()
tree_node = TreeNode(int(check))
q.put(tree_node)
while not q.empty():
node_found = q.get()
msg = "Enter the left node of %s: " % node_found.data
check = input(msg).strip().lower() or "n"
if check == "n":
return tree_node
left_node = TreeNode(int(check))
node_found.left = left_node
q.put(left_node)
msg = "Enter the right node of %s: " % node_found.data
check = input(msg).strip().lower() or "n"
if check == "n":
return tree_node
right_node = TreeNode(int(check))
node_found.right = right_node
q.put(right_node)
def pre_order(node: TreeNode) -> None:
"""
>>> root = TreeNode(1)
>>> tree_node2 = TreeNode(2)
>>> tree_node3 = TreeNode(3)
>>> tree_node4 = TreeNode(4)
>>> tree_node5 = TreeNode(5)
>>> tree_node6 = TreeNode(6)
>>> tree_node7 = TreeNode(7)
>>> root.left, root.right = tree_node2, tree_node3
>>> tree_node2.left, tree_node2.right = tree_node4 , tree_node5
>>> tree_node3.left, tree_node3.right = tree_node6 , tree_node7
>>> pre_order(root)
1 2 4 5 3 6 7
"""
if not isinstance(node, TreeNode) or not node:
return
print(node.data, end=" ")
pre_order(node.left)
pre_order(node.right)
def in_order(node: TreeNode) -> None:
"""
>>> root = TreeNode(1)
>>> tree_node2 = TreeNode(2)
>>> tree_node3 = TreeNode(3)
>>> tree_node4 = TreeNode(4)
>>> tree_node5 = TreeNode(5)
>>> tree_node6 = TreeNode(6)
>>> tree_node7 = TreeNode(7)
>>> root.left, root.right = tree_node2, tree_node3
>>> tree_node2.left, tree_node2.right = tree_node4 , tree_node5
>>> tree_node3.left, tree_node3.right = tree_node6 , tree_node7
>>> in_order(root)
4 2 5 1 6 3 7
"""
if not isinstance(node, TreeNode) or not node:
return
in_order(node.left)
print(node.data, end=" ")
in_order(node.right)
def post_order(node: TreeNode) -> None:
"""
>>> root = TreeNode(1)
>>> tree_node2 = TreeNode(2)
>>> tree_node3 = TreeNode(3)
>>> tree_node4 = TreeNode(4)
>>> tree_node5 = TreeNode(5)
>>> tree_node6 = TreeNode(6)
>>> tree_node7 = TreeNode(7)
>>> root.left, root.right = tree_node2, tree_node3
>>> tree_node2.left, tree_node2.right = tree_node4 , tree_node5
>>> tree_node3.left, tree_node3.right = tree_node6 , tree_node7
>>> post_order(root)
4 5 2 6 7 3 1
"""
if not isinstance(node, TreeNode) or not node:
return
post_order(node.left)
post_order(node.right)
print(node.data, end=" ")
def level_order(node: TreeNode) -> None:
"""
>>> root = TreeNode(1)
>>> tree_node2 = TreeNode(2)
>>> tree_node3 = TreeNode(3)
>>> tree_node4 = TreeNode(4)
>>> tree_node5 = TreeNode(5)
>>> tree_node6 = TreeNode(6)
>>> tree_node7 = TreeNode(7)
>>> root.left, root.right = tree_node2, tree_node3
>>> tree_node2.left, tree_node2.right = tree_node4 , tree_node5
>>> tree_node3.left, tree_node3.right = tree_node6 , tree_node7
>>> level_order(root)
1 2 3 4 5 6 7
"""
if not isinstance(node, TreeNode) or not node:
return
q: queue.Queue = queue.Queue()
q.put(node)
while not q.empty():
node_dequeued = q.get()
print(node_dequeued.data, end=" ")
if node_dequeued.left:
q.put(node_dequeued.left)
if node_dequeued.right:
q.put(node_dequeued.right)
def level_order_actual(node: TreeNode) -> None:
"""
>>> root = TreeNode(1)
>>> tree_node2 = TreeNode(2)
>>> tree_node3 = TreeNode(3)
>>> tree_node4 = TreeNode(4)
>>> tree_node5 = TreeNode(5)
>>> tree_node6 = TreeNode(6)
>>> tree_node7 = TreeNode(7)
>>> root.left, root.right = tree_node2, tree_node3
>>> tree_node2.left, tree_node2.right = tree_node4 , tree_node5
>>> tree_node3.left, tree_node3.right = tree_node6 , tree_node7
>>> level_order_actual(root)
1
2 3
4 5 6 7
"""
if not isinstance(node, TreeNode) or not node:
return
q: queue.Queue = queue.Queue()
q.put(node)
while not q.empty():
list = []
while not q.empty():
node_dequeued = q.get()
print(node_dequeued.data, end=" ")
if node_dequeued.left:
list.append(node_dequeued.left)
if node_dequeued.right:
list.append(node_dequeued.right)
print()
for node in list:
q.put(node)
# iteration version
def pre_order_iter(node: TreeNode) -> None:
"""
>>> root = TreeNode(1)
>>> tree_node2 = TreeNode(2)
>>> tree_node3 = TreeNode(3)
>>> tree_node4 = TreeNode(4)
>>> tree_node5 = TreeNode(5)
>>> tree_node6 = TreeNode(6)
>>> tree_node7 = TreeNode(7)
>>> root.left, root.right = tree_node2, tree_node3
>>> tree_node2.left, tree_node2.right = tree_node4 , tree_node5
>>> tree_node3.left, tree_node3.right = tree_node6 , tree_node7
>>> pre_order_iter(root)
1 2 4 5 3 6 7
"""
if not isinstance(node, TreeNode) or not node:
return
stack: List[TreeNode] = []
n = node
while n or stack:
while n: # start from root node, find its left child
print(n.data, end=" ")
stack.append(n)
n = n.left
# end of while means current node doesn't have left child
n = stack.pop()
# start to traverse its right child
n = n.right
def in_order_iter(node: TreeNode) -> None:
"""
>>> root = TreeNode(1)
>>> tree_node2 = TreeNode(2)
>>> tree_node3 = TreeNode(3)
>>> tree_node4 = TreeNode(4)
>>> tree_node5 = TreeNode(5)
>>> tree_node6 = TreeNode(6)
>>> tree_node7 = TreeNode(7)
>>> root.left, root.right = tree_node2, tree_node3
>>> tree_node2.left, tree_node2.right = tree_node4 , tree_node5
>>> tree_node3.left, tree_node3.right = tree_node6 , tree_node7
>>> in_order_iter(root)
4 2 5 1 6 3 7
"""
if not isinstance(node, TreeNode) or not node:
return
stack: List[TreeNode] = []
n = node
while n or stack:
while n:
stack.append(n)
n = n.left
n = stack.pop()
print(n.data, end=" ")
n = n.right
def post_order_iter(node: TreeNode) -> None:
"""
>>> root = TreeNode(1)
>>> tree_node2 = TreeNode(2)
>>> tree_node3 = TreeNode(3)
>>> tree_node4 = TreeNode(4)
>>> tree_node5 = TreeNode(5)
>>> tree_node6 = TreeNode(6)
>>> tree_node7 = TreeNode(7)
>>> root.left, root.right = tree_node2, tree_node3
>>> tree_node2.left, tree_node2.right = tree_node4 , tree_node5
>>> tree_node3.left, tree_node3.right = tree_node6 , tree_node7
>>> post_order_iter(root)
4 5 2 6 7 3 1
"""
if not isinstance(node, TreeNode) or not node:
return
stack1, stack2 = [], []
n = node
stack1.append(n)
while stack1: # to find the reversed order of post order, store it in stack2
n = stack1.pop()
if n.left:
stack1.append(n.left)
if n.right:
stack1.append(n.right)
stack2.append(n)
while stack2: # pop up from stack2 will be the post order
print(stack2.pop().data, end=" ")
def prompt(s: str = "", width=50, char="*") -> str:
if not s:
return "\n" + width * char
left, extra = divmod(width - len(s) - 2, 2)
return f"{left * char} {s} {(left + extra) * char}"
if __name__ == "__main__":
import doctest
doctest.testmod()
print(prompt("Binary Tree Traversals"))
node = build_tree()
print(prompt("Pre Order Traversal"))
pre_order(node)
print(prompt() + "\n")
print(prompt("In Order Traversal"))
in_order(node)
print(prompt() + "\n")
print(prompt("Post Order Traversal"))
post_order(node)
print(prompt() + "\n")
print(prompt("Level Order Traversal"))
level_order(node)
print(prompt() + "\n")
print(prompt("Actual Level Order Traversal"))
level_order_actual(node)
print("*" * 50 + "\n")
print(prompt("Pre Order Traversal - Iteration Version"))
pre_order_iter(node)
print(prompt() + "\n")
print(prompt("In Order Traversal - Iteration Version"))
in_order_iter(node)
print(prompt() + "\n")
print(prompt("Post Order Traversal - Iteration Version"))
post_order_iter(node)
print(prompt())
| [
"TreeNode",
"TreeNode",
"TreeNode",
"TreeNode",
"TreeNode",
"TreeNode",
"TreeNode",
"TreeNode"
]
| [
1162,
1824,
2485,
3153,
4037,
5103,
6062,
6863
]
| [
1170,
1832,
2493,
3161,
4045,
5111,
6070,
6871
]
|
archives/10sr_trigger.zip | manage.py | #!/usr/bin/env python3
"""Trigger manage.py ."""
import os
import sys
from django.core.management import execute_from_command_line
# TODO: How to check if going to run tests?
if sys.argv[1] == "test":
os.environ["TRIGGER_ENV"] = "test"
os.environ["DJANGO_SETTINGS_MODULE"] = "tests.settings"
else:
os.environ["DJANGO_SETTINGS_MODULE"] = f"proj.settings"
execute_from_command_line(sys.argv)
| []
| []
| []
|
archives/10sr_trigger.zip | proj/__init__.py | []
| []
| []
|
|
archives/10sr_trigger.zip | proj/manageproj/__init__.py | []
| []
| []
|
|
archives/10sr_trigger.zip | proj/manageproj/apps.py | import django.apps
class AppConfig(django.apps.AppConfig): # type: ignore # disallow_subclassing_any
name = "proj.manageproj"
lavel = "manageproj"
| []
| []
| []
|
archives/10sr_trigger.zip | proj/manageproj/management/__init__.py | []
| []
| []
|
|
archives/10sr_trigger.zip | proj/manageproj/management/commands/__init__.py | []
| []
| []
|
|
archives/10sr_trigger.zip | proj/manageproj/management/commands/create_superuser.py | import os
from typing import List, Mapping
from django.conf import settings
from django.contrib.auth.management.commands import createsuperuser
from django.core.management.base import BaseCommand, CommandError
# https://stackoverflow.com/questions/6244382/how-to-automate-createsuperuser-on-django
# https://jumpyoshim.hatenablog.com/entry/how-to-automate-createsuperuser-on-django
class Command(createsuperuser.Command): # type: ignore # disallow_subclassing_any
help = "Create admin user"
# def add_arguments(self, parser):
# return
def handle(self, *args: List[str], **kargs: Mapping[str, str]) -> None:
username = kargs.get("username") or "admin"
password = settings.TRIGGER_SUPERUSER_PASSWORD
email = kargs.get("email")
database = kargs.get("database")
if not password:
raise CommandError("Aborting: TRIGGER_SUPERUSER_PASSWORD is empty")
mgr = self.UserModel._default_manager.db_manager(database)
user = mgr.filter(username=username).first()
if user:
self.stdout.write(f"User {username} already exists.")
self.stdout.write(f"Updating password")
user.set_password(password)
user.save()
else:
self.stdout.write(f"Creating user {username}")
mgr.create_superuser(username=username, password=password, email=email)
return
| [
"List[str]",
"Mapping[str, str]"
]
| [
589,
609
]
| [
598,
626
]
|
archives/10sr_trigger.zip | proj/settings.py | """
Django settings for proj project.
Generated by 'django-admin startproject' using Django 2.2.
For more information on this file, see
https://docs.djangoproject.com/en/2.2/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.2/ref/settings/
"""
import logging
import os
from typing import List
import dj_database_url
import toml
class _Config:
def __init__(self, path):
with open(path) as f:
self.toml = toml.load(f)
return
def __getattr__(self, name):
return self.toml["trigger"][name]
def get(self, name, default=None):
try:
return getattr(self, name)
except KeyError:
return default
_logger = logging.getLogger(__name__)
_c = _Config(os.environ.get("TRIGGER_SETTINGS_TOML", "settings.toml"))
is_prod = _c.ENV == "prod"
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = not is_prod
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/
SECRET_KEY = _c.SECRET_KEY
ALLOWED_HOSTS = [_c.ALLOWED_HOST]
USE_X_FORWARDED_HOST = _c.get("USE_X_FORWARDED_HOST", False)
# Named URL Pattern
LOGIN_URL = "login"
SESSION_COOKIE_NAME = "trigger_sessionid"
# TODO: Add config like IS_HTTPS?
SESSION_COOKIE_SECURE = is_prod
CSRF_COOKIE_NAME = "trigger_csrftoken"
CSRF_COOKIE_SECURE = is_prod
# Application definition
INSTALLED_APPS = [
# Do not forget to add app or django cannot find templates!
"trigger.apps.TriggerConfig",
"proj.manageproj.apps.AppConfig",
"django.contrib.admin",
"django.contrib.auth",
"django.contrib.contenttypes",
"django.contrib.sessions",
"django.contrib.messages",
"django.contrib.staticfiles",
]
MIDDLEWARE = [
"django.middleware.security.SecurityMiddleware",
"django.contrib.sessions.middleware.SessionMiddleware",
"django.middleware.common.CommonMiddleware",
"django.middleware.csrf.CsrfViewMiddleware",
"django.contrib.auth.middleware.AuthenticationMiddleware",
"django.contrib.messages.middleware.MessageMiddleware",
"django.middleware.clickjacking.XFrameOptionsMiddleware",
]
ROOT_URLCONF = "proj.urls"
TEMPLATES = [
{
"BACKEND": "django.template.backends.django.DjangoTemplates",
"DIRS": [],
"APP_DIRS": True,
"OPTIONS": {
"context_processors": [
"django.template.context_processors.debug",
"django.template.context_processors.request",
"django.contrib.auth.context_processors.auth",
"django.contrib.messages.context_processors.messages",
]
},
}
]
WSGI_APPLICATION = "proj.wsgi.application"
# Database
# https://docs.djangoproject.com/en/2.2/ref/settings/#databases
DATABASES = {"default": dj_database_url.parse(_c.DATABASE_URL)}
# Password validation
# https://docs.djangoproject.com/en/2.2/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
"NAME": "django.contrib.auth.password_validation.UserAttributeSimilarityValidator"
},
{"NAME": "django.contrib.auth.password_validation.MinimumLengthValidator"},
{"NAME": "django.contrib.auth.password_validation.CommonPasswordValidator"},
{"NAME": "django.contrib.auth.password_validation.NumericPasswordValidator"},
]
# Internationalization
# https://docs.djangoproject.com/en/2.2/topics/i18n/
LANGUAGE_CODE = "en-us"
TIME_ZONE = "UTC"
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.2/howto/static-files/
STATIC_URL = "/static/"
# trigger specific
TRIGGER_PUSHBULLET_TOKEN = _c.PUSHBULLET_TOKEN
# Is it good???
TRIGGER_SUPERUSER_PASSWORD = _c.SUPERUSER_PASSWORD
globals()["HANIHO"] = 1
| []
| []
| []
|
archives/10sr_trigger.zip | proj/urls.py | """proj URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.2/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import include, path
from django.views.generic.base import RedirectView
urlpatterns = [
path("trigger/admin/", admin.site.urls),
path("trigger/", include("django.contrib.auth.urls")),
path("trigger/", include("trigger.urls")),
path("", RedirectView.as_view(url="/trigger/")),
]
| []
| []
| []
|
archives/10sr_trigger.zip | proj/wsgi.py | """
WSGI config for proj project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/2.2/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "proj.settings")
application = get_wsgi_application()
| []
| []
| []
|
archives/10sr_trigger.zip | tests/__init__.py | []
| []
| []
|
|
archives/10sr_trigger.zip | tests/settings.py | from proj.settings import *
SECRET_KEY = "fake-key"
# INSTALLED_APPS = INSTALLED_APPS + ["tests"]
| []
| []
| []
|
archives/10sr_trigger.zip | tests/tests.py | import unittest
from django.utils import timezone
from django.test import TestCase
from django.urls import reverse
from trigger import models
class TestFailure(TestCase): # type: ignore # disallow_subclassing_any
@unittest.skip("demonstrating failing and skipping")
def test_failure(self) -> None:
self.assertEqual(True, False)
return
| []
| []
| []
|
archives/10sr_trigger.zip | trigger/__init__.py | []
| []
| []
|
|
archives/10sr_trigger.zip | trigger/admin.py | from django.contrib import admin
# Register your models here.
| []
| []
| []
|
archives/10sr_trigger.zip | trigger/apps.py | from django.apps import AppConfig
class TriggerConfig(AppConfig): # type: ignore # disallow_subclassing_any
name = "trigger"
label = "trigger"
| []
| []
| []
|
archives/10sr_trigger.zip | trigger/migrations/__init__.py | []
| []
| []
|
|
archives/10sr_trigger.zip | trigger/models.py | from django.db import models
# Create your models here.
| []
| []
| []
|
archives/10sr_trigger.zip | trigger/pushbullet.py | from typing import Any, Optional
import pushbullet as pb
from django.conf import LazySettings
class PushBullet:
_token: str
__pushbullet: Optional[pb.Pushbullet] = None
@property
def pushbullet(self) -> pb.Pushbullet:
if self.__pushbullet is None:
# pushbullet.Pushbullet sends a request on initialization,
# so delay it
self.__pushbullet = pb.Pushbullet(self._token)
assert isinstance(self.__pushbullet, pb.Pushbullet)
return self.__pushbullet
def __init__(self, settings: LazySettings) -> None:
self._token = settings.TRIGGER_PUSHBULLET_TOKEN
assert self._token
return
def push_note(self, body: str, title: str = "") -> Any:
# TODO: Handle errors
return self.pushbullet.push_note(title, body)
| [
"LazySettings",
"str"
]
| [
560,
712
]
| [
572,
715
]
|
archives/10sr_trigger.zip | trigger/urls.py | from django.urls import path
from django.views.generic.base import RedirectView
from . import views
app_name = "trigger"
urlpatterns = [
path("", views.index, name="index"),
path("note/", RedirectView.as_view(url="from/web"), name="note"),
path("note/from/web", views.note_from_web, name="note_from_web"),
path("note/from/web/post", views.note_from_web_post, name="note_from_web_post"),
]
| []
| []
| []
|
archives/10sr_trigger.zip | trigger/views.py | import html
from pprint import pformat
from django.conf import settings
from django.contrib.auth.decorators import login_required
from django.http import (
HttpRequest,
HttpResponse,
HttpResponseBadRequest,
HttpResponseRedirect,
)
from django.template import loader
from django.urls import reverse
from .pushbullet import PushBullet
def index(req: HttpRequest) -> HttpResponse:
# print(settings.HANIHO)
meta = ""
if req.user.is_authenticated:
meta = pformat(req.META)
return HttpResponse(
f"""
hello
<a href="note">note</a>
<pre><code>{html.escape(meta)}</code></pre>
"""
)
@login_required # type: ignore # disallow_untyped_decorators
def note_from_web(req: HttpRequest) -> HttpResponse:
tpl = loader.get_template("trigger/note_from_web.html.dtl")
return HttpResponse(tpl.render({}, req))
@login_required # type: ignore # disallow_untyped_decorators
def note_from_web_post(req: HttpRequest) -> HttpResponse:
try:
body = req.POST["body"]
except KeyError:
return HttpResponseBadRequest("Body not given")
pb = PushBullet(settings)
ret = pb.push_note(body)
# print(ret)
return HttpResponseRedirect(reverse("trigger:note_from_web"))
| [
"HttpRequest",
"HttpRequest",
"HttpRequest"
]
| [
369,
736,
969
]
| [
380,
747,
980
]
|
archives/10sr_webtools.zip | docs/conf.py | # Configuration file for the Sphinx documentation builder.
#
# This file only contains a selection of the most common options. For a full
# list see the documentation:
# https://www.sphinx-doc.org/en/master/usage/configuration.html
# -- Path setup --------------------------------------------------------------
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
#
import os
import sys
sys.path.insert(0, os.path.abspath('..'))
os.environ["DJANGO_SETTINGS_MODULE"] = "webtools.settings"
os.environ["WEBTOOLS_SETTINGS_TOML"] = "../settings_insecure.toml"
# -- Project information -----------------------------------------------------
project = 'webtools'
copyright = '2020, 10sr'
author = '10sr'
import webtools
# -- General configuration ---------------------------------------------------
# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = [
'sphinx.ext.autodoc',
'sphinx.ext.autosummary',
'sphinx.ext.viewcode',
'sphinx.ext.todo',
]
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#
# This is also used if you do content translation via gettext catalogs.
# Usually you set "language" from the command line for these cases.
language = 'en'
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
# This pattern also affects html_static_path and html_extra_path.
exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store']
# -- Options for HTML output -------------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
#
import sphinx_rtd_theme
html_theme = "sphinx_rtd_theme"
html_theme_path = [sphinx_rtd_theme.get_html_theme_path()]
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']
# -- Extension configuration -------------------------------------------------
autosummary_generate = True
# -- Options for todo extension ----------------------------------------------
# If true, `todo` and `todoList` produce output, else they produce nothing.
todo_include_todos = True
| []
| []
| []
|
archives/10sr_webtools.zip | export_as_bookmark/__init__.py | """Export urls into Netscape Bookmark file."""
| []
| []
| []
|
archives/10sr_webtools.zip | export_as_bookmark/admin.py | """Admin code."""
from django.contrib import admin
# Register your models here.
| []
| []
| []
|
archives/10sr_webtools.zip | export_as_bookmark/apps.py | """export_as_bookmark app definition."""
from django.apps import AppConfig
from django.conf import settings
from .redis import Redis
class ExportAsBookmarkConfig(AppConfig): # type: ignore # disallow_subclassing_any
"""export_as_bookmark app definition."""
name = "export_as_bookmark"
label = "export_as_bookmark"
def ready(self) -> None:
"""Initialize app."""
Redis.get_instance().ready(settings.EXPORT_AS_BOOKMARK_REDIS_URL)
return
| []
| []
| []
|
archives/10sr_webtools.zip | export_as_bookmark/bookmark_exporter.py | """Bookmark exporter."""
from __future__ import annotations
import html
from typing import List
class BookmarkExporter:
"""Export bookmark into Netscape Bookmark file."""
_TEMPLATE = """<!DOCTYPE NETSCAPE-Bookmark-file-1>
<META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=UTF-8">
<TITLE>Bookmarks</TITLE>
<H1>ExportAsBookmark</H1>
<DL><p>
<DT><H3>{name}</H3>
<DL><p>
{bookmarks}
</DL><p>
</DL><p>
"""
_TEMPLATE_A = """<DT><A HREF="{url}">{title}</A>\n"""
urls: List[str]
def __init__(self, urls: List[str]) -> None:
"""Initialize.
:param urls: List of urls
"""
self.urls = list(urls)
return
@classmethod
def from_lines(cls, urls: str) -> BookmarkExporter:
"""Create bookmark exporter from list of urls.
:param urls: Newline separated list or urls
:returns: BookmarkExporter instance
"""
return cls([url.strip() for url in urls.split("\n") if url.strip()])
def export(self, name: str) -> str:
"""Export bookmark HTML.
:param name: Folder name
:returns: HTML string
"""
return self._TEMPLATE.format(
name=name,
bookmarks="".join(
self._TEMPLATE_A.format(title=html.escape(url), url=html.escape(url))
for url in self.urls
),
)
| [
"List[str]",
"str",
"str"
]
| [
539,
723,
1019
]
| [
548,
726,
1022
]
|
archives/10sr_webtools.zip | export_as_bookmark/migrations/__init__.py | """export_as_bookmark migration script."""
| []
| []
| []
|
archives/10sr_webtools.zip | export_as_bookmark/models.py | """export_as_bookmark model definitions."""
from django.db import models
# Create your models here.
| []
| []
| []
|
archives/10sr_webtools.zip | export_as_bookmark/redis.py | """Redis."""
from __future__ import annotations
from typing import Any, ClassVar, Optional, Union, cast
from urllib.parse import urlparse
import redis
# TODO: Use costum storage system?
# https://docs.djangoproject.com/en/2.2/howto/custom-file-storage/
class Redis:
"""Communicate with redis server."""
__singleton_instance: ClassVar[Optional[Redis]] = None
def __init__(self) -> None:
"""Raise error because this is singleton.
Use get_instance() instead.
:raises RuntimeError: Instanciation is not allowed
"""
raise RuntimeError("Cannot initialize via Constructor")
@classmethod
def get_instance(cls) -> Redis:
"""Get Redis instance.
:returns: Instance
"""
if cls.__singleton_instance is None:
cls.__singleton_instance = cls.__new__(cls)
return cls.__singleton_instance
_client: redis.Redis
url: str
def ready(self, url: str) -> None:
"""Initialize (reset) redis client..
:param url: Redis URL
"""
self.url = url
# Call to untyped function "from_url" of "Redis" in typed context
self._client = redis.Redis.from_url(self.url)
return
def set(self, k: str, v: bytes, **kargs: Any) -> Any:
"""Set key-value pair.
:param k: Key
:param v: Value
:param **kargs: Additional parameters passed to Redis.set method
:returns: Return from Redis.set
"""
return self._client.set(k, v, **kargs)
def get(self, k: str) -> Optional[bytes]:
"""Get value of key.
If key does not eixst or expired, return None.
:param k: Key
:returns: Value of k
"""
ret = self._client.get(k)
# S101 Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
assert ret is None or isinstance(ret, bytes) # noqa: S101
return ret
def pttl(self, k: str) -> int:
"""Get the remaining time to live of a key.
:param k: Key
:returns: TTL in millisec
"""
# Call to untyped function "pttl" in typed context
return self._client.pttl(k) # type: ignore
| [
"str",
"str",
"bytes",
"Any",
"str",
"str"
]
| [
960,
1250,
1258,
1274,
1559,
1988
]
| [
963,
1253,
1263,
1277,
1562,
1991
]
|
archives/10sr_webtools.zip | export_as_bookmark/urls.py | """Urls for export_as_bookmark app."""
from django.urls import path
from . import views
from .apps import ExportAsBookmarkConfig
app_name = ExportAsBookmarkConfig.label
urlpatterns = [
path("", views.index, name="index"),
path("post", views.post, name="post"),
path("done/<id>/<name>", views.done, name="done"),
path("download/<id>/<name>.html", views.download, name="download"),
]
| []
| []
| []
|
archives/10sr_webtools.zip | export_as_bookmark/views.py | """View definitions of export_as_bookmark."""
# from pprint import pformat
import html
from hashlib import sha512
from django.http import (
HttpRequest,
HttpResponse,
HttpResponseBadRequest,
HttpResponseNotFound,
HttpResponseRedirect,
)
from django.template import loader
from django.urls import reverse
from .bookmark_exporter import BookmarkExporter
from .redis import Redis
def index(req: HttpRequest) -> HttpResponse:
"""Return index.
:param req: Request object
:returns: Index page
"""
tpl = loader.get_template("export_as_bookmark/index.html.dtl")
return HttpResponse(tpl.render({}, req))
def post(req: HttpRequest) -> HttpResponse:
"""Receive post request and redirect to download page.
:param req: Request object
:returns: Redirect to done page
"""
try:
body = req.POST["body"]
except KeyError:
return HttpResponseBadRequest("Body not given")
redis = Redis.get_instance()
request_id = id(req)
name = f"ExportAsBookmark-{request_id}"
exporter = BookmarkExporter.from_lines(body)
exported_bytes = exporter.export(name).encode("utf-8")
key = sha512(exported_bytes).hexdigest()
redis.set(key, exported_bytes, ex=6000)
return HttpResponseRedirect(reverse("export_as_bookmark:done", args=(key, name)))
def done(req: HttpRequest, id: str, name: str) -> HttpResponse:
"""Return link to download exported html file.
:param req: Request object
:param id: Result id
:param name: Bookmark name
:returns: Download page
"""
redis = Redis.get_instance()
ttl_millisec = redis.pttl(id)
if ttl_millisec >= 0:
ttl_display = f"Expire in {ttl_millisec} millisec"
expired = False
elif ttl_millisec == -1:
# Will not happen. raise error?
ttl_display = "Never expire"
expired = False
elif ttl_millisec == -2:
ttl_display = "Expired"
expired = True
tpl = loader.get_template("export_as_bookmark/done.html.dtl")
return HttpResponse(
tpl.render(
{
"id": id,
"name": name,
"ttl_millisec": ttl_millisec,
"ttl_display": ttl_display,
"expired": expired,
},
req,
)
)
def download(req: HttpRequest, id: str, name: str) -> HttpResponse:
"""Return exported bookmark content.
:param req: Request object
:param id: Result id
:param name: Bookmark name
:return: Exported html content
"""
# TODO: Use req.session?
# https://docs.djangoproject.com/en/2.1/ref/request-response/#django.http.HttpRequest.session
redis = Redis.get_instance()
val = redis.get(id)
if val is None:
return HttpResponseNotFound(f"Content of id {id[:24]} not found. Expired?")
res = HttpResponse(val.decode("utf-8"))
res["Referrer-Policy"] = "origin"
return res
| [
"HttpRequest",
"HttpRequest",
"HttpRequest",
"str",
"str",
"HttpRequest",
"str",
"str"
]
| [
419,
663,
1349,
1366,
1377,
2340,
2357,
2368
]
| [
430,
674,
1360,
1369,
1380,
2351,
2360,
2371
]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.