mirror of
https://github.com/autistic-symposium/master-algorithms-py.git
synced 2025-11-24 07:53:15 -05:00
abstracted structures fixed
This commit is contained in:
parent
3fdbc2a605
commit
01703751f1
98 changed files with 305 additions and 856 deletions
0
src/builtin_structures/__init__.py
Normal file → Executable file
0
src/builtin_structures/__init__.py
Normal file → Executable file
0
src/builtin_structures/alpha_permutation.py
Normal file → Executable file
0
src/builtin_structures/alpha_permutation.py
Normal file → Executable file
0
src/builtin_structures/anagram.py
Normal file → Executable file
0
src/builtin_structures/anagram.py
Normal file → Executable file
0
src/builtin_structures/balance_symbols.py
Normal file → Executable file
0
src/builtin_structures/balance_symbols.py
Normal file → Executable file
0
src/builtin_structures/check_if_3_numbers_sum_to_zero.py
Normal file → Executable file
0
src/builtin_structures/check_if_3_numbers_sum_to_zero.py
Normal file → Executable file
0
src/builtin_structures/check_non_overlapping_intervals.py
Normal file → Executable file
0
src/builtin_structures/check_non_overlapping_intervals.py
Normal file → Executable file
64
src/builtin_structures/convert_numerical_bases.py
Executable file
64
src/builtin_structures/convert_numerical_bases.py
Executable file
|
|
@ -0,0 +1,64 @@
|
|||
#!/usr/bin/env python
|
||||
|
||||
__author__ = "bt3"
|
||||
|
||||
''' convert an integer to a string in any base'''
|
||||
|
||||
def convert_from_dec_to_any_base(number, base):
|
||||
'''
|
||||
>>> number, base = 9, 2
|
||||
>>> convert_from_dec_to_any_base(number, base)
|
||||
'1001'
|
||||
'''
|
||||
|
||||
convertString = '012345679ABCDEF'
|
||||
|
||||
if number < base:
|
||||
return convertString[number]
|
||||
|
||||
else:
|
||||
return convert_from_dec_to_any_base(number//base, base) + \
|
||||
convertString[number%base]
|
||||
|
||||
|
||||
|
||||
def convert_from_decimal_to_binary(number, base):
|
||||
'''
|
||||
>>> number, base = 9, 2
|
||||
>>> convert_from_decimal_to_binary(number, base)
|
||||
1001
|
||||
'''
|
||||
|
||||
multiplier, result = 1, 0
|
||||
|
||||
while number > 0:
|
||||
result += number%base*multiplier
|
||||
multiplier *= 10
|
||||
number = number//base
|
||||
|
||||
return result
|
||||
|
||||
|
||||
|
||||
def convert_from_decimal_larger_bases(number, base):
|
||||
'''
|
||||
>>> number, base = 31, 16
|
||||
>>> convert_from_decimal_larger_bases(number, base)
|
||||
'1F'
|
||||
'''
|
||||
strings = "0123456789ABCDEFGHIJ"
|
||||
result = ""
|
||||
|
||||
while number > 0:
|
||||
digit = number%base
|
||||
result = strings[digit] + result
|
||||
number = number//base
|
||||
|
||||
return result
|
||||
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
import doctest
|
||||
doctest.testmod()
|
||||
|
||||
0
src/builtin_structures/convert_str_2_int.py
Normal file → Executable file
0
src/builtin_structures/convert_str_2_int.py
Normal file → Executable file
0
src/builtin_structures/count_unique_words_On2.py
Normal file → Executable file
0
src/builtin_structures/count_unique_words_On2.py
Normal file → Executable file
16
src/builtin_structures/fibonacci.py
Normal file → Executable file
16
src/builtin_structures/fibonacci.py
Normal file → Executable file
|
|
@ -33,6 +33,22 @@ def fib(n):
|
|||
return b
|
||||
|
||||
|
||||
def fib_rec(n):
|
||||
'''
|
||||
>>> fib_rec(2)
|
||||
1
|
||||
>>> fib_rec(5)
|
||||
5
|
||||
>>> fib_rec(7)
|
||||
13
|
||||
'''
|
||||
if n < 3:
|
||||
return 1
|
||||
return fib_rec(n - 1) + fib_rec(n - 2)
|
||||
|
||||
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
import doctest
|
||||
doctest.testmod()
|
||||
|
|
|
|||
0
src/builtin_structures/find_0_MxN_replace_cols_rows.py
Normal file → Executable file
0
src/builtin_structures/find_0_MxN_replace_cols_rows.py
Normal file → Executable file
0
src/builtin_structures/find_dice_probabilities.py
Normal file → Executable file
0
src/builtin_structures/find_dice_probabilities.py
Normal file → Executable file
0
src/builtin_structures/find_edit_distance.py
Normal file → Executable file
0
src/builtin_structures/find_edit_distance.py
Normal file → Executable file
0
src/builtin_structures/find_first_non_repetead_char.py
Normal file → Executable file
0
src/builtin_structures/find_first_non_repetead_char.py
Normal file → Executable file
0
src/builtin_structures/find_if_is_substr.py
Normal file → Executable file
0
src/builtin_structures/find_if_is_substr.py
Normal file → Executable file
0
src/builtin_structures/find_if_unique_char.py
Normal file → Executable file
0
src/builtin_structures/find_if_unique_char.py
Normal file → Executable file
0
src/builtin_structures/find_long_con_inc_subseq.py
Normal file → Executable file
0
src/builtin_structures/find_long_con_inc_subseq.py
Normal file → Executable file
0
src/builtin_structures/find_longest_str_unique_chars.py
Normal file → Executable file
0
src/builtin_structures/find_longest_str_unique_chars.py
Normal file → Executable file
0
src/builtin_structures/find_product_without_division.py
Normal file → Executable file
0
src/builtin_structures/find_product_without_division.py
Normal file → Executable file
0
src/builtin_structures/find_top_N_recurring_words.py
Normal file → Executable file
0
src/builtin_structures/find_top_N_recurring_words.py
Normal file → Executable file
0
src/builtin_structures/find_two_missing_numbers_in_sequence.py
Normal file → Executable file
0
src/builtin_structures/find_two_missing_numbers_in_sequence.py
Normal file → Executable file
0
src/builtin_structures/longest_common_prefix.py
Normal file → Executable file
0
src/builtin_structures/longest_common_prefix.py
Normal file → Executable file
|
|
@ -1,27 +0,0 @@
|
|||
#!/usr/bin/python3
|
||||
# mari von steinkirch @2013
|
||||
# steinkirch at gmail
|
||||
|
||||
|
||||
def convert_dec_to_any_base_rec(number, base):
|
||||
''' convert an integer to a string in any base'''
|
||||
convertString = '012345679ABCDEF'
|
||||
if number < base: return convertString[number]
|
||||
else:
|
||||
return convert_dec_to_any_base_rec(number//base, base) + convertString[number%base]
|
||||
|
||||
|
||||
|
||||
|
||||
def test_convert_dec_to_any_base_rec(module_name='this module'):
|
||||
number = 9
|
||||
base = 2
|
||||
assert(convert_dec_to_any_base_rec(number, base) == '1001')
|
||||
|
||||
s = 'Tests in {name} have {con}!'
|
||||
print(s.format(name=module_name, con='passed'))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
test_convert_dec_to_any_base_rec()
|
||||
|
||||
|
|
@ -1,24 +0,0 @@
|
|||
#!/usr/bin/python3
|
||||
# mari von steinkirch @2013
|
||||
# steinkirch at gmail
|
||||
|
||||
def convert_from_decimal(number, base):
|
||||
''' convert any decimal number to another base. '''
|
||||
multiplier, result = 1, 0
|
||||
while number > 0:
|
||||
result += number%base*multiplier
|
||||
multiplier *= 10
|
||||
number = number//base
|
||||
return result
|
||||
|
||||
|
||||
def test_convert_from_decimal():
|
||||
number, base = 9, 2
|
||||
assert(convert_from_decimal(number, base) == 1001)
|
||||
print('Tests passed!')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
test_convert_from_decimal()
|
||||
|
||||
|
||||
|
|
@ -1,24 +0,0 @@
|
|||
#!/usr/bin/python3
|
||||
# mari von steinkirch @2013
|
||||
# steinkirch at gmail
|
||||
|
||||
|
||||
def convert_from_decimal_larger_bases(number, base):
|
||||
''' convert any decimal number to a number in a base up to 20'''
|
||||
strings = "0123456789ABCDEFGHIJ"
|
||||
result = ""
|
||||
while number > 0:
|
||||
digit = number%base
|
||||
result = strings[digit] + result
|
||||
number = number//base
|
||||
return result
|
||||
|
||||
def test_convert_from_decimal_larger_bases():
|
||||
number, base = 31, 16
|
||||
assert(convert_from_decimal_larger_bases(number, base) == '1F')
|
||||
print('Tests passed!')
|
||||
|
||||
if __name__ == '__main__':
|
||||
test_convert_from_decimal_larger_bases()
|
||||
|
||||
|
||||
|
|
@ -1,25 +0,0 @@
|
|||
#!/usr/bin/python3
|
||||
# mari von steinkirch @2013
|
||||
# steinkirch at gmail
|
||||
|
||||
|
||||
def convert_to_decimal(number, base):
|
||||
''' convert any number in another base to the decimal base'''
|
||||
multiplier, result = 1, 0
|
||||
while number > 0:
|
||||
result += number%10*multiplier
|
||||
multiplier *= base
|
||||
number = number//10
|
||||
return result
|
||||
|
||||
|
||||
def test_convert_to_decimal():
|
||||
number, base = 1001, 2
|
||||
assert(convert_to_decimal(number, base) == 9)
|
||||
print('Tests passed!')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
test_convert_to_decimal()
|
||||
|
||||
|
||||
|
|
@ -1,44 +0,0 @@
|
|||
#!/usr/bin/python3
|
||||
# mari von steinkirch @2013
|
||||
# steinkirch at gmail
|
||||
|
||||
import math
|
||||
|
||||
def find_fibonacci_seq_rec(n):
|
||||
''' implements the nth fibonacci value in a recursive exponential runtime '''
|
||||
if n < 2: return n
|
||||
return find_fibonacci_seq_rec(n - 1) + find_fibonacci_seq_rec(n - 2)
|
||||
|
||||
|
||||
|
||||
def find_fibonacci_seq_iter(n):
|
||||
''' return the nth fibonacci value in a iterative O(n^2) runtime '''
|
||||
if n < 2: return n
|
||||
a, b = 0, 1
|
||||
for i in range(n):
|
||||
a, b = b, a + b
|
||||
return a
|
||||
|
||||
|
||||
def find_fibonacci_seq_form(n):
|
||||
''' return the nth fibonacci value implemented by the formula, nearly constant-time algorithm,
|
||||
but, it has a poor precise (after 72 it starts to become wrong) '''
|
||||
sq5 = math.sqrt(5)
|
||||
phi = (1 + sq5) / 2
|
||||
return int(math.floor(phi ** n / sq5))
|
||||
|
||||
|
||||
|
||||
def test_find_fib():
|
||||
n = 10
|
||||
assert(find_fibonacci_seq_rec(n) == 55)
|
||||
assert(find_fibonacci_seq_iter(n) == 55)
|
||||
assert(find_fibonacci_seq_form(n) == 55)
|
||||
print('Tests passed!')
|
||||
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
test_find_fib()
|
||||
|
||||
|
||||
|
|
@ -1,28 +0,0 @@
|
|||
#!/usr/bin/python3
|
||||
# mari von steinkirch @2013
|
||||
# steinkirch at gmail
|
||||
|
||||
|
||||
def finding_gcd(a, b):
|
||||
''' implements the greatest common divider algorithm '''
|
||||
while(b != 0):
|
||||
result = b
|
||||
a, b = b, a % b
|
||||
return result
|
||||
|
||||
|
||||
def test_finding_gcd():
|
||||
number1 = 21
|
||||
number2 = 12
|
||||
assert(finding_gcd(number1, number2) == 3)
|
||||
print('Tests passed!')
|
||||
|
||||
if __name__ == '__main__':
|
||||
test_finding_gcd()
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
|
@ -1,59 +0,0 @@
|
|||
#!/usr/bin/python3
|
||||
# mari von steinkirch @2013
|
||||
# steinkirch at gmail
|
||||
|
||||
import math
|
||||
import random
|
||||
|
||||
def finding_prime(number):
|
||||
''' find whether a number is prime in a simple way'''
|
||||
num = abs(number)
|
||||
if num < 4 : return True
|
||||
for x in range(2, num):
|
||||
if num % x == 0:
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def finding_prime_sqrt(number):
|
||||
''' find whether a number is prime as soon as it rejects all candidates up to sqrt(n) '''
|
||||
num = abs(number)
|
||||
if num < 4 : return True
|
||||
for x in range(2, int(math.sqrt(num)) + 1):
|
||||
if number % x == 0:
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def finding_prime_fermat(number):
|
||||
''' find whether a number is prime with Fermat's theorem, using probabilistic tests '''
|
||||
if number <= 102:
|
||||
for a in range(2, number):
|
||||
if pow(a, number- 1, number) != 1:
|
||||
return False
|
||||
return True
|
||||
else:
|
||||
for i in range(100):
|
||||
a = random.randint(2, number - 1)
|
||||
if pow(a, number - 1, number) != 1:
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
|
||||
def test_finding_prime():
|
||||
number1 = 17
|
||||
number2 = 20
|
||||
assert(finding_prime(number1) == True)
|
||||
assert(finding_prime(number2) == False)
|
||||
assert(finding_prime_sqrt(number1) == True)
|
||||
assert(finding_prime_sqrt(number2) == False)
|
||||
assert(finding_prime_fermat(number1) == True)
|
||||
assert(finding_prime_fermat(number2) == False)
|
||||
print('Tests passed!')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
test_finding_prime()
|
||||
|
||||
|
||||
|
|
@ -1,35 +0,0 @@
|
|||
#!/usr/bin/python3
|
||||
# mari von steinkirch @2013
|
||||
# steinkirch at gmail
|
||||
|
||||
import math
|
||||
import random
|
||||
import sys
|
||||
from finding_prime import finding_prime_sqrt
|
||||
|
||||
|
||||
def generate_prime(number=3):
|
||||
''' return a n-bit prime '''
|
||||
while 1:
|
||||
p = random.randint(pow(2, number-2), pow(2, number-1)-1)
|
||||
p = 2 * p + 1
|
||||
if finding_prime_sqrt(p):
|
||||
return p
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
if len(sys.argv) < 2:
|
||||
print ("Usage: generate_prime.py number")
|
||||
sys.exit()
|
||||
else:
|
||||
number = int(sys.argv[1])
|
||||
print(generate_prime(number))
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
|
@ -1,45 +0,0 @@
|
|||
#!/usr/bin/python3
|
||||
# mari von steinkirch @2013
|
||||
# steinkirch at gmail
|
||||
|
||||
from fractions import Fraction
|
||||
|
||||
def rounding_floats(number1, places):
|
||||
''' some operations with float()'''
|
||||
return round(number1, places)
|
||||
|
||||
|
||||
def float_to_fractions(number):
|
||||
return Fraction(*number.as_integer_ratio())
|
||||
|
||||
|
||||
def get_denominator(number1, number2):
|
||||
a = Fraction(number1, number2)
|
||||
return a.denominator
|
||||
|
||||
|
||||
def get_numerator(number1, number2):
|
||||
a = Fraction(number1, number2)
|
||||
return a.numerator
|
||||
|
||||
|
||||
def test_testing_floats(module_name='this module'):
|
||||
number1 = 1.25
|
||||
number2 = 1
|
||||
number3 = -1
|
||||
number4 = 5/4
|
||||
number6 = 6
|
||||
assert(rounding_floats(number1, number2) == 1.2)
|
||||
assert(rounding_floats(number1*10, number3) == 10)
|
||||
assert(float_to_fractions(number1) == number4)
|
||||
assert(get_denominator(number2, number6) == number6)
|
||||
assert(get_numerator(number2, number6) == number2)
|
||||
|
||||
s = 'Tests in {name} have {con}!'
|
||||
print(s.format(name=module_name, con='passed'))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
test_testing_floats()
|
||||
|
||||
|
||||
|
|
@ -1,32 +0,0 @@
|
|||
#!/usr/bin/python
|
||||
# mari von steinkirch @2013
|
||||
# steinkirch at gmail
|
||||
|
||||
import numpy as np
|
||||
|
||||
def testing_numpy():
|
||||
''' tests many features of numpy '''
|
||||
ax = np.array([1,2,3])
|
||||
ay = np.array([3,4,5])
|
||||
print(ax)
|
||||
print(ax*2)
|
||||
print(ax+10)
|
||||
print(np.sqrt(ax))
|
||||
print(np.cos(ax))
|
||||
print(ax-ay)
|
||||
print(np.where(ax<2, ax, 10))
|
||||
|
||||
m = np.matrix([ax, ay, ax])
|
||||
print(m)
|
||||
print(m.T)
|
||||
|
||||
grid1 = np.zeros(shape=(10,10), dtype=float)
|
||||
grid2 = np.ones(shape=(10,10), dtype=float)
|
||||
print(grid1)
|
||||
print(grid2)
|
||||
print(grid1[1]+10)
|
||||
print(grid2[:,2]*2)
|
||||
|
||||
if __name__ == '__main__':
|
||||
testing_numpy()
|
||||
|
||||
|
|
@ -1,32 +0,0 @@
|
|||
#!/usr/bin/python
|
||||
# mari von steinkirch @2013
|
||||
# steinkirch at gmail
|
||||
|
||||
import numpy
|
||||
import time
|
||||
|
||||
def trad_version():
|
||||
t1 = time.time()
|
||||
X = range(10000000)
|
||||
Y = range(10000000)
|
||||
Z = []
|
||||
for i in range(len(X)):
|
||||
Z.append(X[i] + Y[i])
|
||||
return time.time() - t1
|
||||
|
||||
def numpy_version():
|
||||
t1 = time.time()
|
||||
X = numpy.arange(10000000)
|
||||
Y = numpy.arange(10000000)
|
||||
Z = X + Y
|
||||
return time.time() - t1
|
||||
|
||||
if __name__ == '__main__':
|
||||
print(trad_version())
|
||||
print(numpy_version())
|
||||
|
||||
|
||||
'''
|
||||
3.23564291
|
||||
0.0714290142059
|
||||
'''
|
||||
|
|
@ -1,27 +0,0 @@
|
|||
#!/usr/bin/python3
|
||||
# mari von steinkirch @2013
|
||||
# steinkirch at gmail
|
||||
|
||||
import random
|
||||
|
||||
def testing_random():
|
||||
''' testing the module random'''
|
||||
values = [1, 2, 3, 4]
|
||||
print(random.choice(values))
|
||||
print(random.choice(values))
|
||||
print(random.choice(values))
|
||||
print(random.sample(values, 2))
|
||||
print(random.sample(values, 3))
|
||||
|
||||
''' shuffle in place '''
|
||||
random.shuffle(values)
|
||||
print(values)
|
||||
|
||||
''' create random integers '''
|
||||
print(random.randint(0,10))
|
||||
print(random.randint(0,10))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
testing_random()
|
||||
|
||||
0
src/builtin_structures/palindrome.py
Normal file → Executable file
0
src/builtin_structures/palindrome.py
Normal file → Executable file
0
src/builtin_structures/permutations.py
Normal file → Executable file
0
src/builtin_structures/permutations.py
Normal file → Executable file
10
src/builtin_structures/find_prime_factors.py → src/builtin_structures/primes.py
Normal file → Executable file
10
src/builtin_structures/find_prime_factors.py → src/builtin_structures/primes.py
Normal file → Executable file
|
|
@ -8,6 +8,7 @@ find prime factors of a number.
|
|||
'''
|
||||
|
||||
import math
|
||||
import random
|
||||
|
||||
def find_prime_factors(n):
|
||||
'''
|
||||
|
|
@ -30,6 +31,15 @@ def is_prime(n):
|
|||
return True
|
||||
|
||||
|
||||
''' return a n-bit prime '''
|
||||
def generate_prime(number=3):
|
||||
while 1:
|
||||
p = random.randint(pow(2, number-2), pow(2, number-1)-1)
|
||||
p = 2 * p + 1
|
||||
if find_prime_factors(p):
|
||||
return p
|
||||
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
import doctest
|
||||
0
src/builtin_structures/prod_other_ints.py
Normal file → Executable file
0
src/builtin_structures/prod_other_ints.py
Normal file → Executable file
0
src/builtin_structures/reverse_string.py
Normal file → Executable file
0
src/builtin_structures/reverse_string.py
Normal file → Executable file
0
src/builtin_structures/reverse_words.py
Normal file → Executable file
0
src/builtin_structures/reverse_words.py
Normal file → Executable file
0
src/builtin_structures/rotate_NxN.py
Normal file → Executable file
0
src/builtin_structures/rotate_NxN.py
Normal file → Executable file
0
src/builtin_structures/runtime_dicts_with_timeit_module.py
Normal file → Executable file
0
src/builtin_structures/runtime_dicts_with_timeit_module.py
Normal file → Executable file
0
src/builtin_structures/runtime_lists_with_timeit_module.py
Normal file → Executable file
0
src/builtin_structures/runtime_lists_with_timeit_module.py
Normal file → Executable file
24
src/builtin_structures/numbers/search_entry_matrix.py → src/builtin_structures/search_entry_matrix.py
Normal file → Executable file
24
src/builtin_structures/numbers/search_entry_matrix.py → src/builtin_structures/search_entry_matrix.py
Normal file → Executable file
|
|
@ -1,18 +1,22 @@
|
|||
#!/usr/bin/python3
|
||||
# mari von steinkirch @2013
|
||||
# steinkirch at gmail
|
||||
#!/usr/bin/env python
|
||||
|
||||
__author__ = "bt3"
|
||||
|
||||
|
||||
''' Search an Entry in a Matrix where the Rows and columns are Sorted
|
||||
In this 2D matrix, every row is increasingly sorted from left to right,
|
||||
and every column is increasingly sorted from top to bottom.
|
||||
The runtime is O(m+n).
|
||||
'''
|
||||
|
||||
def find_elem_matrix_bool(m1, value):
|
||||
''' Search an Entry in a Matrix where the Rows and columns are Sorted
|
||||
In this 2D matrix, every row is increasingly sorted from left to right,
|
||||
and every column is increasingly sorted from top to bottom.
|
||||
The runtime is O(m+n). '''
|
||||
|
||||
found = False
|
||||
row = 0
|
||||
col = len(m1[0]) - 1
|
||||
|
||||
while row < len(m1) and col >= 0:
|
||||
|
||||
if m1[row][col] == value:
|
||||
found = True
|
||||
break
|
||||
|
|
@ -20,8 +24,9 @@ def find_elem_matrix_bool(m1, value):
|
|||
col-=1
|
||||
else:
|
||||
row+=1
|
||||
|
||||
return found
|
||||
|
||||
|
||||
|
||||
|
||||
def test_find_elem_matrix_bool(module_name='this module'):
|
||||
|
|
@ -30,9 +35,6 @@ def test_find_elem_matrix_bool(module_name='this module'):
|
|||
assert(find_elem_matrix_bool(m1,3) == False)
|
||||
m2 = [[0]]
|
||||
assert(find_elem_matrix_bool(m2,0) == True)
|
||||
|
||||
s = 'Tests in {name} have {con}!'
|
||||
print(s.format(name=module_name, con='passed'))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
|
|
@ -1,32 +0,0 @@
|
|||
#!/usr/bin/python3
|
||||
# mari von steinkirch @2013
|
||||
# steinkirch at gmail
|
||||
|
||||
''' Example of how to use a bit array in python as a "counter" dict:
|
||||
|
||||
>>> l1 = [0, 1, 2, 3, 4, 2, 6, 7, 8, 9]
|
||||
>>> print_dupl_ba(l1)
|
||||
2
|
||||
'''
|
||||
|
||||
|
||||
|
||||
def print_dupl_ba(l1):
|
||||
bs = bytearray(10)
|
||||
for i in range(len(l1)):
|
||||
if i == l1[i]:
|
||||
bs[i] = 1
|
||||
for index, bit in enumerate(bs):
|
||||
if bit == 0:
|
||||
return l1[index]
|
||||
return None
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
import doctest
|
||||
doctest.testmod()
|
||||
|
||||
|
|
@ -1,40 +0,0 @@
|
|||
#!/usr/bin/python3
|
||||
# mari von steinkirch @2013
|
||||
# steinkirch at gmail
|
||||
|
||||
''' Clear a bit in a binary number. It is almost like the reverse of set bit:
|
||||
1) first create a number filled of 1s, with 0 at i (can create 0001000 and ~)
|
||||
2) AND the number so it clears the ith bit
|
||||
|
||||
>>> num = int('10010000', 2)
|
||||
>>> clear_bit(num, 4)
|
||||
'0b10000000'
|
||||
>>> num = int('10010011', 2)
|
||||
>>> clear_all_bits_from_i_to_0(num, 2)
|
||||
'0b10010000'
|
||||
>>> num = int('1110011', 2)
|
||||
>>> clear_all_bits_from_most_sig_to_1(num, 2)
|
||||
'0b11'
|
||||
'''
|
||||
|
||||
|
||||
|
||||
def clear_bit(num, i):
|
||||
mask = ~ (1 << i) # -0b10001
|
||||
return bin(num & mask)
|
||||
|
||||
|
||||
def clear_all_bits_from_i_to_0(num, i):
|
||||
mask = ~ ( (1 << (i+1)) - 1)
|
||||
return bin(num & mask)
|
||||
|
||||
|
||||
def clear_all_bits_from_most_sig_to_1(num, i):
|
||||
mask = ( 1 << i) -1
|
||||
return bin(num & mask)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
import doctest
|
||||
doctest.testmod()
|
||||
|
||||
|
|
@ -1,28 +0,0 @@
|
|||
#!/usr/bin/python3
|
||||
# mari von steinkirch @2013
|
||||
# steinkirch at gmail
|
||||
|
||||
''' Find how many bits a int has:
|
||||
1) Start with a mask of 1
|
||||
2) Mask with AND
|
||||
3) if result (if true): count += 1
|
||||
(obs: to find the int of a bin do int('1001', 2)) and to show in bin do bin(int))
|
||||
|
||||
>>> for i in range(17): print(find_bit_len(i))
|
||||
'''
|
||||
|
||||
|
||||
|
||||
def find_bit_len(int_num):
|
||||
lenght = 0
|
||||
while int_num:
|
||||
int_num >>= 1
|
||||
lenght += 1
|
||||
return lenght
|
||||
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
import doctest
|
||||
doctest.testmod()
|
||||
|
||||
|
|
@ -1,34 +0,0 @@
|
|||
#!/usr/bin/python3
|
||||
# mari von steinkirch @2013
|
||||
# steinkirch at gmail
|
||||
|
||||
''' Find how many 1s in the binary:
|
||||
1) Start with a mask of 1
|
||||
2) Mask with AND
|
||||
3) if result (if true): count += 1
|
||||
(obs: to find the int of a bin do int('1001', 2)) and to show in bin do bin(int))
|
||||
|
||||
>>> find_how_many_1_in_a_binary(9)
|
||||
2
|
||||
|
||||
'''
|
||||
|
||||
|
||||
|
||||
def find_how_many_1_in_a_binary(n):
|
||||
counter = 0
|
||||
while n:
|
||||
if n & 1:
|
||||
counter += 1
|
||||
n >>= 1
|
||||
return counter
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
import doctest
|
||||
doctest.testmod()
|
||||
|
||||
|
|
@ -1,41 +0,0 @@
|
|||
#!/usr/bin/python3
|
||||
# mari von steinkirch @2013
|
||||
# steinkirch at gmail
|
||||
|
||||
''' Get a bit in a binary number:
|
||||
1) Shifts 1 over by i bits
|
||||
2) make an AND with the number
|
||||
3) all the other than the bit at i are clean, now compare to 0
|
||||
4) if the new value is not 0, bit i is 1
|
||||
>>> num = int('0100100', 2)
|
||||
>>> get_bit(num, 0)
|
||||
0
|
||||
>>> get_bit(num, 1)
|
||||
0
|
||||
>>> get_bit(num, 2)
|
||||
1
|
||||
>>> get_bit(num, 3)
|
||||
0
|
||||
>>> get_bit(num, 4)
|
||||
0
|
||||
>>> get_bit(num, 5)
|
||||
1
|
||||
>>> get_bit(num, 6)
|
||||
0
|
||||
'''
|
||||
|
||||
|
||||
|
||||
def get_bit(num, i):
|
||||
mask = 1 << i
|
||||
return num & mask != 0
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
import doctest
|
||||
doctest.testmod()
|
||||
|
||||
|
|
@ -1,35 +0,0 @@
|
|||
#!/usr/bin/python3
|
||||
# mari von steinkirch @2013
|
||||
# steinkirch at gmail
|
||||
|
||||
''' Given a real number between 0 and 1 (eg: 0.72), this method print the binary
|
||||
representation. If the Number cannot be represented accurately in binary, with at
|
||||
most 32 chars, print error:
|
||||
|
||||
>>> get_float_rep(0.72)
|
||||
('Error 2', '.1011100001010001111010111000010')
|
||||
>>> get_float_rep(0.1)
|
||||
('Error 2', '.0001100110011001100110011001100')
|
||||
>>> get_float_rep(0.5)
|
||||
'.1'
|
||||
'''
|
||||
|
||||
def get_float_rep(num):
|
||||
if num >= 1 or num <= 0: return 'Error 1'
|
||||
result = '.'
|
||||
while num:
|
||||
if len(result) >= 32: return 'Error 2', result
|
||||
r = num*2
|
||||
if r >= 1:
|
||||
result += '1'
|
||||
num = r - 1
|
||||
else:
|
||||
result += '0'
|
||||
num = r
|
||||
return result
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
import doctest
|
||||
doctest.testmod()
|
||||
|
||||
|
|
@ -1,35 +0,0 @@
|
|||
#!/usr/bin/python3
|
||||
# mari von steinkirch @2013
|
||||
# steinkirch at gmail
|
||||
|
||||
''' Given two 32-bit numbers, N and M, and two bit positions, i and j, this
|
||||
method insert M into N such that M starts at bit j and ends at bit i:
|
||||
1) clear the bits j thru i in N'
|
||||
2) shift M so that it lines up with bits j thru i
|
||||
3) merge M and N
|
||||
|
||||
>>> N = 0b10000000000
|
||||
>>> M = 0b10011
|
||||
>>> j = 6
|
||||
>>> i = 2
|
||||
>>> insert_small_bin_into_big_bin(M, N, i, j)
|
||||
'0b10001001100'
|
||||
'''
|
||||
|
||||
def insert_small_bin_into_big_bin(M, N, i, j):
|
||||
allOnes = ~0
|
||||
left = allOnes << (j+1) # 1110000
|
||||
right = ( (1 << i) - 1) # 0000111
|
||||
mask = left | right # 1110111
|
||||
N_cleared = N & mask
|
||||
M_shifted = M << i
|
||||
|
||||
return bin( N_cleared | M_shifted)
|
||||
|
||||
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
import doctest
|
||||
doctest.testmod()
|
||||
|
||||
|
|
@ -1,64 +0,0 @@
|
|||
#!/usr/bin/python3
|
||||
# mari von steinkirch @2013
|
||||
# steinkirch at gmail
|
||||
|
||||
''' Give a positive int, print the next smallest and next largest ints with
|
||||
same number of 1 bits.
|
||||
The brute force is:
|
||||
1) find number of 1 bits
|
||||
2) loop above and down until find same, checking for each
|
||||
|
||||
>>> num = 0b1001
|
||||
>>> next = '0b1010'
|
||||
>>> prev = '0b110'
|
||||
>>> print_prev_same_1s(num) == prev
|
||||
True
|
||||
>>> print_next_same_1s(num) == next
|
||||
True
|
||||
|
||||
'''
|
||||
|
||||
|
||||
|
||||
def print_prev_same_1s(num):
|
||||
n1s = find_num_1s(num)
|
||||
# find prev
|
||||
i = num-1
|
||||
while True:
|
||||
n1s_here = find_num_1s(i)
|
||||
if n1s_here == n1s:
|
||||
return bin(i)
|
||||
i -= 1
|
||||
if i < 0:
|
||||
return None
|
||||
|
||||
def print_next_same_1s(num):
|
||||
n1s = find_num_1s(num)
|
||||
# find next
|
||||
i = num+1
|
||||
while True:
|
||||
n1s_here = find_num_1s(i)
|
||||
if n1s_here == n1s:
|
||||
return bin(i)
|
||||
i += 1
|
||||
if i < 0:
|
||||
return None
|
||||
|
||||
|
||||
|
||||
def find_num_1s(num):
|
||||
counter = 0
|
||||
while num:
|
||||
if num & 1:
|
||||
counter += 1
|
||||
num >>= 1
|
||||
return counter
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
import doctest
|
||||
doctest.testmod()
|
||||
|
||||
|
|
@ -1,45 +0,0 @@
|
|||
#!/usr/bin/python3
|
||||
# mari von steinkirch @2013
|
||||
# steinkirch at gmail
|
||||
|
||||
''' This method returns the number of bits that are necessary to change to convert two
|
||||
numbers A and B:
|
||||
1) XOR
|
||||
2) count 1s
|
||||
|
||||
>>> a = int('10010000', 2)
|
||||
>>> b = int('01011010', 2)
|
||||
>>> count_bits_swap(a, b)
|
||||
4
|
||||
>>> count_bits_swap2(a, b)
|
||||
4
|
||||
'''
|
||||
|
||||
def count_bits_swap2(a, b):
|
||||
count = 0
|
||||
m = a^b
|
||||
while m:
|
||||
count +=1
|
||||
m = m & (m-1)
|
||||
return count
|
||||
|
||||
|
||||
|
||||
def count_bits_swap(a, b):
|
||||
m = a^b
|
||||
return count_1s(m)
|
||||
|
||||
|
||||
def count_1s(m):
|
||||
count = 0
|
||||
while m:
|
||||
if m& 1 :
|
||||
count +=1
|
||||
m >>= 1
|
||||
return count
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
import doctest
|
||||
doctest.testmod()
|
||||
|
||||
|
|
@ -1,38 +0,0 @@
|
|||
#!/usr/bin/python3
|
||||
# mari von steinkirch @2013
|
||||
# steinkirch at gmail
|
||||
|
||||
''' Set a bit in a binary number:
|
||||
1) Shifts 1 over by i bits
|
||||
2) make an OR with the number, only the value at bit i will change and all the others bit
|
||||
of the mask are zero so will not affect the num
|
||||
>>> num = int('0100100', 2)
|
||||
>>> set_bit(num, 0)
|
||||
'0b100101'
|
||||
>>> set_bit(num, 1)
|
||||
'0b100110'
|
||||
>>> set_bit(num, 2) # nothing change
|
||||
'0b100100'
|
||||
>>> set_bit(num, 3)
|
||||
'0b101100'
|
||||
>>> set_bit(num, 4)
|
||||
'0b110100'
|
||||
>>> set_bit(num, 5) # nothing change
|
||||
'0b100100'
|
||||
'''
|
||||
|
||||
|
||||
|
||||
def set_bit(num, i):
|
||||
mask = 1 << i
|
||||
return bin( num | mask )
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
import doctest
|
||||
doctest.testmod()
|
||||
|
||||
|
|
@ -1,38 +0,0 @@
|
|||
#!/usr/bin/python3
|
||||
# mari von steinkirch @2013
|
||||
# steinkirch at gmail
|
||||
|
||||
''' Swap odd and even bits in a smart way in a binary:
|
||||
1) first for odds, take n and move the odd:
|
||||
(a) Mask all odd bits with 10101010 (0xAA)
|
||||
(b) shift by right by 1
|
||||
2) do the same to ints with 01010101
|
||||
3) merge
|
||||
|
||||
>>> num = 0b11011101
|
||||
>>> result = '0b1101110'
|
||||
>>> swap_odd_even(num) == result
|
||||
True
|
||||
|
||||
'''
|
||||
|
||||
|
||||
|
||||
def swap_odd_even(num):
|
||||
mask_odd = 0xAA # 0b10101010
|
||||
mask_even = 0x55 # 0b1010101
|
||||
odd = num & mask_odd
|
||||
odd >>= 1
|
||||
even = num & mask_even
|
||||
even >>= 1
|
||||
return bin(odd | even)
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
import doctest
|
||||
doctest.testmod()
|
||||
|
||||
|
|
@ -1,26 +0,0 @@
|
|||
#!/usr/bin/python3
|
||||
# mari von steinkirch @2013
|
||||
# steinkirch at gmail
|
||||
|
||||
''' This method merges set bit and clean bit:
|
||||
1) first clear the bit at i using a mask such as 1110111
|
||||
2) then shift the intended value v by i bits
|
||||
3) this will create a number with bit i to v and all other to 0
|
||||
4) finally update the ith bit with or
|
||||
|
||||
>>> num = int('10010000', 2)
|
||||
>>> update_bit(num, 2, 1)
|
||||
'0b10010100'
|
||||
'''
|
||||
|
||||
|
||||
|
||||
def update_bit(num, i, v):
|
||||
mask = ~ (1 << i)
|
||||
return bin( (num & mask) | (v << i) )
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
import doctest
|
||||
doctest.testmod()
|
||||
|
||||
|
|
@ -1,37 +0,0 @@
|
|||
#!/usr/bin/python3
|
||||
# mari von steinkirch @2013
|
||||
# steinkirch at gmail
|
||||
|
||||
|
||||
def removing_duplicates_seq(seq):
|
||||
''' if the values are hashable, we can use set and generators to remove duplicates
|
||||
in a sequence '''
|
||||
seen = set()
|
||||
for item in seq:
|
||||
if item not in seen:
|
||||
yield item
|
||||
seen.add(item)
|
||||
|
||||
def removing_duplicates_seq_not_hash(seq, key= None):
|
||||
''' if the item is not hashable, such as dictionaries '''
|
||||
seen = set()
|
||||
for item in seq:
|
||||
val = item if key is None else key[item]
|
||||
if item not in seen:
|
||||
yield item
|
||||
seen.add(val)
|
||||
|
||||
|
||||
|
||||
def test_removing_duplicates_seq():
|
||||
seq = [1, 2, 2, 2, 3, 3, 4, 4, 4]
|
||||
dict = {'a':1, 'b':2, 'a':2, 'a':1}
|
||||
assert(list(removing_duplicates_seq(seq)) == [1,2,3,4])
|
||||
assert(list(removing_duplicates_seq_not_hash(dict)) == ['a', 'b'])
|
||||
print('Tests passed!'.center(20, '*'))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
test_removing_duplicates_seq()
|
||||
|
||||
|
||||
|
|
@ -1,39 +0,0 @@
|
|||
#!/usr/bin/python3
|
||||
# mari von steinkirch @2013
|
||||
# steinkirch at gmail
|
||||
|
||||
from collections import OrderedDict
|
||||
|
||||
def set_operations_with_dict():
|
||||
''' find common in 2 dictionaries '''
|
||||
''' values() do not support set operations!'''
|
||||
|
||||
pairs = [('a', 1), ('b',2), ('c',3)]
|
||||
d1 = OrderedDict(pairs)
|
||||
print(d1) # ('a', 1), ('b', 2), ('c', 3)
|
||||
|
||||
d2 = {'a':1, 'c':2, 'd':3, 'e':4}
|
||||
print(d2) # {'a': 1, 'c': 2, 'e': 4, 'd': 3}
|
||||
|
||||
union = d1.keys() & d2.keys()
|
||||
print(union) # {'a', 'c'}
|
||||
|
||||
union_items = d1.items() & d2.items()
|
||||
print(union_items) # {('a', 1)}
|
||||
|
||||
subtraction1 = d1.keys() - d2.keys()
|
||||
print(subtraction1) # {'b'}
|
||||
|
||||
subtraction2 = d2.keys() - d1.keys()
|
||||
print(subtraction2) # {'d', 'e'}
|
||||
|
||||
subtraction_items = d1.items() - d2.items()
|
||||
print(subtraction_items) # {('b', 2), ('c', 3)}
|
||||
|
||||
''' we can remove keys from a dict doing: '''
|
||||
d3 = {key:d2[key] for key in d2.keys() - {'c', 'd'}}
|
||||
print(d3) {'a': 1, 'e': 4}
|
||||
|
||||
if __name__ == '__main__':
|
||||
set_operations_with_dict()
|
||||
|
||||
|
|
@ -1,39 +0,0 @@
|
|||
#!/usr/bin/python3
|
||||
# mari von steinkirch @2013
|
||||
# steinkirch at gmail
|
||||
|
||||
from collections import OrderedDict
|
||||
|
||||
def set_operations_with_dict():
|
||||
''' find common in 2 dictionaries '''
|
||||
''' values() do not support set operations!'''
|
||||
|
||||
pairs = [('a', 1), ('b',2), ('c',3)]
|
||||
d1 = OrderedDict(pairs)
|
||||
print(d1) # ('a', 1), ('b', 2), ('c', 3)
|
||||
|
||||
d2 = {'a':1, 'c':2, 'd':3, 'e':4}
|
||||
print(d2) # {'a': 1, 'c': 2, 'e': 4, 'd': 3}
|
||||
|
||||
union = d1.keys() & d2.keys()
|
||||
print(union) # {'a', 'c'}
|
||||
|
||||
union_items = d1.items() & d2.items()
|
||||
print(union_items) # {('a', 1)}
|
||||
|
||||
subtraction1 = d1.keys() - d2.keys()
|
||||
print(subtraction1) # {'b'}
|
||||
|
||||
subtraction2 = d2.keys() - d1.keys()
|
||||
print(subtraction2) # {'d', 'e'}
|
||||
|
||||
subtraction_items = d1.items() - d2.items()
|
||||
print(subtraction_items) # {('b', 2), ('c', 3)}
|
||||
|
||||
''' we can remove keys from a dict doing: '''
|
||||
d3 = {key:d2[key] for key in d2.keys() - {'c', 'd'}}
|
||||
print(d3) {'a': 1, 'e': 4}
|
||||
|
||||
if __name__ == '__main__':
|
||||
set_operations_with_dict()
|
||||
|
||||
|
|
@ -1,37 +0,0 @@
|
|||
#!/usr/bin/python3
|
||||
# mari von steinkirch @2013
|
||||
# steinkirch at gmail
|
||||
|
||||
def difference(l1):
|
||||
""" return the list with duplicate elements removed """
|
||||
return list(set(l1))
|
||||
|
||||
def intersection(l1, l2):
|
||||
""" return the intersection of two lists """
|
||||
return list(set(l1) & set(l2))
|
||||
|
||||
def union(l1, l2):
|
||||
""" return the union of two lists """
|
||||
return list(set(l1) | set(l2))
|
||||
|
||||
|
||||
def test_sets_operations_with_lists():
|
||||
l1 = [1,2,3,4,5,9,11,15]
|
||||
l2 = [4,5,6,7,8]
|
||||
l3 = []
|
||||
assert(difference(l1) == [1, 2, 3, 4, 5, 9, 11, 15])
|
||||
assert(difference(l2) == [8, 4, 5, 6, 7])
|
||||
assert(intersection(l1, l2) == [4,5])
|
||||
assert(union(l1, l2) == [1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 15])
|
||||
assert(difference(l3) == [])
|
||||
assert(intersection(l3, l2) == l3)
|
||||
assert(sorted(union(l3, l2)) == sorted(l2))
|
||||
print('Tests passed!')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
test_sets_operations_with_lists()
|
||||
|
||||
|
||||
|
||||
|
||||
0
src/builtin_structures/simple_str_comprension.py
Normal file → Executable file
0
src/builtin_structures/simple_str_comprension.py
Normal file → Executable file
0
src/builtin_structures/sum_two_numbers_as_strings.py
Normal file → Executable file
0
src/builtin_structures/sum_two_numbers_as_strings.py
Normal file → Executable file
|
|
@ -1,17 +0,0 @@
|
|||
#!/usr/bin/python3
|
||||
# mari von steinkirch @2013
|
||||
# steinkirch at gmail
|
||||
|
||||
from collections import namedtuple
|
||||
|
||||
def namedtuple_example():
|
||||
''' show some examples for namedtuple '''
|
||||
sunnydale = namedtuple('name', ['job', 'age'])
|
||||
buffy = sunnydale('slayer', '17')
|
||||
print(buffy.job)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
namedtuple_example()
|
||||
|
||||
|
||||
Loading…
Add table
Add a link
Reference in a new issue