Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -27,8 +27,8 @@
<a href="https://github.com/pre-commit/pre-commit">
<img src="https://img.shields.io/badge/pre--commit-enabled-brightgreen?logo=pre-commit&logoColor=white&style=flat-square" height="20" alt="pre-commit">
</a>
<a href="https://github.com/psf/black">
<img src="https://img.shields.io/static/v1?label=code%20style&message=black&color=black&style=flat-square" height="20" alt="code style: black">
<a href="https://docs.astral.sh/ruff/formatter/">
<img src="https://img.shields.io/static/v1?label=code%20style&message=ruff&color=black&style=flat-square" height="20" alt="code style: black">
</a>
<!-- Short description: -->
<h3>All algorithms implemented in Python - for education</h3>
Expand Down
62 changes: 31 additions & 31 deletions bit_manipulation/reverse_bits.py
Original file line number Diff line number Diff line change
@@ -1,83 +1,83 @@
def get_reverse_bit_string(number: int) -> str:
"""
return the bit string of an integer
Return the reverse bit string of a 32 bit integer

>>> get_reverse_bit_string(9)
'10010000000000000000000000000000'
>>> get_reverse_bit_string(43)
'11010100000000000000000000000000'
>>> get_reverse_bit_string(2873)
'10011100110100000000000000000000'
>>> get_reverse_bit_string(2550136832)
'00000000000000000000000000011001'
>>> get_reverse_bit_string("this is not a number")
Traceback (most recent call last):
...
TypeError: operation can not be conducted on a object of type str
TypeError: operation can not be conducted on an object of type str
"""
if not isinstance(number, int):
msg = (
"operation can not be conducted on a object of type "
"operation can not be conducted on an object of type "
f"{type(number).__name__}"
)
raise TypeError(msg)
bit_string = ""
for _ in range(32):
bit_string += str(number % 2)
number = number >> 1
number >>= 1
return bit_string


def reverse_bit(number: int) -> str:
def reverse_bit(number: int) -> int:
"""
Take in an 32 bit integer, reverse its bits,
return a string of reverse bits

result of a reverse_bit and operation on the integer provided.
Take in a 32 bit integer, reverse its bits, return a 32 bit integer result

>>> reverse_bit(25)
'00000000000000000000000000011001'
2550136832
>>> reverse_bit(37)
'00000000000000000000000000100101'
2751463424
>>> reverse_bit(21)
'00000000000000000000000000010101'
2818572288
>>> reverse_bit(58)
'00000000000000000000000000111010'
1543503872
>>> reverse_bit(0)
'00000000000000000000000000000000'
0
>>> reverse_bit(256)
'00000000000000000000000100000000'
8388608
>>> reverse_bit(2550136832)
25
>>> reverse_bit(-1)
Traceback (most recent call last):
...
ValueError: the value of input must be positive
ValueError: The value of input must be non-negative

>>> reverse_bit(1.1)
Traceback (most recent call last):
...
TypeError: Input value must be a 'int' type
TypeError: Input value must be an 'int' type

>>> reverse_bit("0")
Traceback (most recent call last):
...
TypeError: '<' not supported between instances of 'str' and 'int'
TypeError: Input value must be an 'int' type
"""
if not isinstance(number, int):
raise TypeError("Input value must be an 'int' type")
if number < 0:
raise ValueError("the value of input must be positive")
elif isinstance(number, float):
raise TypeError("Input value must be a 'int' type")
elif isinstance(number, str):
raise TypeError("'<' not supported between instances of 'str' and 'int'")
raise ValueError("The value of input must be non-negative")

result = 0
# iterator over [1 to 32],since we are dealing with 32 bit integer
for _ in range(1, 33):
# iterator over [0 to 31], since we are dealing with a 32 bit integer
for _ in range(32):
# left shift the bits by unity
result = result << 1
result <<= 1
# get the end bit
end_bit = number % 2
end_bit = number & 1
# right shift the bits by unity
number = number >> 1
# add that bit to our ans
result = result | end_bit
return get_reverse_bit_string(result)
number >>= 1
# add that bit to our answer
result |= end_bit
return result


if __name__ == "__main__":
Expand Down
52 changes: 52 additions & 0 deletions boolean_algebra/imply_gate.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,58 @@ def imply_gate(input_1: int, input_2: int) -> int:
return int(input_1 == 0 or input_2 == 1)


def recursive_imply_list(input_list: list[int]) -> int:
"""
Recursively calculates the implication of a list.
Strictly the implication is applied consecutively left to right:
( (a -> b) -> c ) -> d ...

>>> recursive_imply_list([])
Traceback (most recent call last):
...
ValueError: Input list must contain at least two elements
>>> recursive_imply_list([0])
Traceback (most recent call last):
...
ValueError: Input list must contain at least two elements
>>> recursive_imply_list([1])
Traceback (most recent call last):
...
ValueError: Input list must contain at least two elements
>>> recursive_imply_list([0, 0])
1
>>> recursive_imply_list([0, 1])
1
>>> recursive_imply_list([1, 0])
0
>>> recursive_imply_list([1, 1])
1
>>> recursive_imply_list([0, 0, 0])
0
>>> recursive_imply_list([0, 0, 1])
1
>>> recursive_imply_list([0, 1, 0])
0
>>> recursive_imply_list([0, 1, 1])
1
>>> recursive_imply_list([1, 0, 0])
1
>>> recursive_imply_list([1, 0, 1])
1
>>> recursive_imply_list([1, 1, 0])
0
>>> recursive_imply_list([1, 1, 1])
1
"""
if len(input_list) < 2:
raise ValueError("Input list must contain at least two elements")
first_implication = imply_gate(input_list[0], input_list[1])
if len(input_list) == 2:
return first_implication
new_list = [first_implication, *input_list[2:]]
return recursive_imply_list(new_list)


if __name__ == "__main__":
import doctest

Expand Down
41 changes: 27 additions & 14 deletions data_structures/linked_list/from_sequence.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
# Recursive Program to create a Linked List from a sequence and
# print a string representation of it.
"""
Recursive Program to create a Linked List from a sequence and
print a string representation of it.
"""


class Node:
Expand All @@ -18,13 +20,32 @@ def __repr__(self):
return string_rep


def make_linked_list(elements_list):
"""Creates a Linked List from the elements of the given sequence
(list/tuple) and returns the head of the Linked List."""
def make_linked_list(elements_list: list | tuple) -> Node:
"""
Creates a Linked List from the elements of the given sequence
(list/tuple) and returns the head of the Linked List.

>>> make_linked_list([])
Traceback (most recent call last):
...
ValueError: The Elements List is empty
>>> make_linked_list(())
Traceback (most recent call last):
...
ValueError: The Elements List is empty
>>> make_linked_list([1])
<1> ---> <END>
>>> make_linked_list((1,))
<1> ---> <END>
>>> make_linked_list([1, 3, 5, 32, 44, 12, 43])
<1> ---> <3> ---> <5> ---> <32> ---> <44> ---> <12> ---> <43> ---> <END>
>>> make_linked_list((1, 3, 5, 32, 44, 12, 43))
<1> ---> <3> ---> <5> ---> <32> ---> <44> ---> <12> ---> <43> ---> <END>
"""

# if elements_list is empty
if not elements_list:
raise Exception("The Elements List is empty")
raise ValueError("The Elements List is empty")

# Set first element as Head
head = Node(elements_list[0])
Expand All @@ -34,11 +55,3 @@ def make_linked_list(elements_list):
current.next = Node(data)
current = current.next
return head


list_data = [1, 3, 5, 32, 44, 12, 43]
print(f"List: {list_data}")
print("Creating Linked List from List.")
linked_list = make_linked_list(list_data)
print("Linked List:")
print(linked_list)
16 changes: 14 additions & 2 deletions scripts/build_directory_md.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,20 @@ def good_file_paths(top_dir: str = ".") -> Iterator[str]:
yield os.path.join(dir_path, filename).lstrip("./")


def md_prefix(i):
return f"{i * ' '}*" if i else "\n##"
def md_prefix(indent: int) -> str:
"""
Markdown prefix based on indent for bullet points
>>> md_prefix(0)
'\\n##'
>>> md_prefix(1)
' *'
>>> md_prefix(2)
' *'
>>> md_prefix(3)
' *'
"""
return f"{indent * ' '}*" if indent else "\n##"


def print_path(old_path: str, new_path: str) -> str:
Expand Down
21 changes: 14 additions & 7 deletions strings/anagrams.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,19 +6,26 @@


def signature(word: str) -> str:
"""Return a word sorted
"""
Return a word's frequency-based signature.

>>> signature("test")
'estt'
'e1s1t2'
>>> signature("this is a test")
' aehiisssttt'
' 3a1e1h1i2s3t3'
>>> signature("finaltest")
'aefilnstt'
'a1e1f1i1l1n1s1t2'
"""
return "".join(sorted(word))
frequencies = collections.Counter(word)
return "".join(
f"{char}{frequency}" for char, frequency in sorted(frequencies.items())
)


def anagram(my_word: str) -> list[str]:
"""Return every anagram of the given word
"""
Return every anagram of the given word from the dictionary.

>>> anagram('test')
['sett', 'stet', 'test']
>>> anagram('this is a test')
Expand All @@ -40,5 +47,5 @@ def anagram(my_word: str) -> list[str]:
all_anagrams = {word: anagram(word) for word in word_list if len(anagram(word)) > 1}

with open("anagrams.txt", "w") as file:
file.write("all_anagrams = \n ")
file.write("all_anagrams = \n")
file.write(pprint.pformat(all_anagrams))