Skip to content
Open
Show file tree
Hide file tree
Changes from 9 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
Empty file.
96 changes: 96 additions & 0 deletions logic_building_problems/array_traversal.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
"""Array Traversal.

This module contains functions for common array traversal operations,
including finding maximum, minimum, and sum of elements.
"""


def find_max(arr: list[int | float]) -> int | float:
"""
Find the maximum element in an array.

Args:
arr: List of numbers

Returns:
The maximum value in the array

Raises:
ValueError: If the array is empty

Examples:
>>> find_max([1, 5, 3, 9, 2])
9
>>> find_max([-1, -5, -3])
-1
>>> find_max([42])
42
>>> find_max([1.5, 2.7, 1.2])
2.7
>>> find_max([])
Traceback (most recent call last):
...
ValueError: Array cannot be empty
"""
if not arr:
raise ValueError("Array cannot be empty")
return max(arr)


def find_min(arr: list[int | float]) -> int | float:
"""
Find the minimum element in an array.

Args:
arr: List of numbers

Returns:
The minimum value in the array

Raises:
ValueError: If the array is empty

Examples:
>>> find_min([1, 5, 3, 9, 2])
1
>>> find_min([-1, -5, -3])
-5
>>> find_min([42])
42
>>> find_min([])
Traceback (most recent call last):
...
ValueError: Array cannot be empty
"""
if not arr:
raise ValueError("Array cannot be empty")
return min(arr)


def array_sum(arr: list[int | float]) -> int | float:
"""
Calculate the sum of all elements in an array.

Args:
arr: List of numbers

Returns:
The sum of all values in the array

Examples:
>>> array_sum([1, 2, 3, 4, 5])
15
>>> array_sum([-1, 1, -2, 2])
0
>>> array_sum([1.5, 2.5, 3.0])
7.0
>>> array_sum([])
0
"""
return sum(arr)


if __name__ == "__main__":
import doctest

doctest.testmod()
64 changes: 64 additions & 0 deletions logic_building_problems/bubble_sort.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
"""Bubble Sort Algorithm.

This module implements the bubble sort algorithm, a simple sorting technique
that repeatedly steps through the list, compares adjacent elements and swaps
them if they are in the wrong order.
"""


def bubble_sort(arr: list[int | float]) -> list[int | float]:
"""
Sort an array using the bubble sort algorithm.

Bubble sort works by repeatedly swapping adjacent elements if they are
in the wrong order. This process continues until no more swaps are needed.

Args:
arr: List of numbers to be sorted

Returns:
The sorted list in ascending order

Examples:
>>> bubble_sort([64, 34, 25, 12, 22, 11, 90])
[11, 12, 22, 25, 34, 64, 90]
>>> bubble_sort([5, 2, 8, 1, 9])
[1, 2, 5, 8, 9]
>>> bubble_sort([1])
[1]
>>> bubble_sort([])
[]
>>> bubble_sort([3, 3, 3, 3])
[3, 3, 3, 3]
>>> bubble_sort([5, 4, 3, 2, 1])
[1, 2, 3, 4, 5]
>>> bubble_sort([1.5, 2.3, 0.8, 1.1])
[0.8, 1.1, 1.5, 2.3]
"""
# Create a copy to avoid modifying the original list
arr_copy = arr.copy()
n = len(arr_copy)

# Traverse through all array elements
for i in range(n):
# Flag to optimize by detecting if array is already sorted
swapped = False

# Last i elements are already in place
for j in range(n - i - 1):
# Swap if the element found is greater than the next element
if arr_copy[j] > arr_copy[j + 1]:
arr_copy[j], arr_copy[j + 1] = arr_copy[j + 1], arr_copy[j]
swapped = True

# If no swapping occurred, array is sorted
if not swapped:
break

return arr_copy


if __name__ == "__main__":
import doctest

doctest.testmod()
62 changes: 62 additions & 0 deletions logic_building_problems/fizz_buzz.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
"""FizzBuzz Problem.

This module contains a solution to the classic FizzBuzz problem.
For numbers 1 to n, print 'Fizz' for multiples of 3, 'Buzz' for
multiples of 5, and 'FizzBuzz' for multiples of both.
"""


def fizz_buzz(n: int) -> list[str]:
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please provide descriptive name for the parameter: n

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please provide descriptive name for the parameter: n

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please provide descriptive name for the parameter: n

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please provide descriptive name for the parameter: n

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please provide descriptive name for the parameter: n

"""
Return a list of FizzBuzz results for numbers from 1 to n.

For each number from 1 to n:
- Return 'FizzBuzz' if divisible by both 3 and 5
- Return 'Fizz' if divisible by 3
- Return 'Buzz' if divisible by 5
- Return the number as a string otherwise

Args:
n: Positive integer representing the range

Returns:
A list of strings containing FizzBuzz results

Raises:
ValueError: If n is not a positive integer

Examples:
>>> fizz_buzz(5)
['1', '2', 'Fizz', '4', 'Buzz']
>>> fizz_buzz(15)
['1', '2', 'Fizz', '4', 'Buzz', 'Fizz', '7', '8', 'Fizz', 'Buzz', '11', 'Fizz', '13', '14', 'FizzBuzz']

Check failure on line 32 in logic_building_problems/fizz_buzz.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (E501)

logic_building_problems/fizz_buzz.py:32:89: E501 Line too long (111 > 88)
>>> fizz_buzz(0)
Traceback (most recent call last):
...
ValueError: n must be a positive integer
>>> fizz_buzz(-5)
Traceback (most recent call last):
...
ValueError: n must be a positive integer
"""
if not isinstance(n, int) or n <= 0:
raise ValueError("n must be a positive integer")

result = []
for i in range(1, n + 1):
if i % 15 == 0:
result.append("FizzBuzz")
elif i % 3 == 0:
result.append("Fizz")
elif i % 5 == 0:
result.append("Buzz")
else:
result.append(str(i))

return result


if __name__ == "__main__":
import doctest

doctest.testmod()
46 changes: 46 additions & 0 deletions logic_building_problems/palindrome.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
"""Palindrome Checker.

This module contains functions to check if a string is a palindrome.
A palindrome is a word, phrase, or sequence that reads the same backward as forward.
"""


def is_palindrome(text: str) -> bool:
"""
Check if a given string is a palindrome.

A palindrome is a string that reads the same forward and backward,
ignoring case, spaces, and punctuation.

Args:
text: The string to check

Returns:
True if the string is a palindrome, False otherwise

Examples:
>>> is_palindrome("racecar")
True
>>> is_palindrome("hello")
False
>>> is_palindrome("A man a plan a canal Panama")
True
>>> is_palindrome("race a car")
False
>>> is_palindrome("")
True
>>> is_palindrome("a")
True
>>> is_palindrome("Madam")
True
"""
# Remove non-alphanumeric characters and convert to lowercase
cleaned = "".join(char.lower() for char in text if char.isalnum())
# Check if the cleaned string equals its reverse
return cleaned == cleaned[::-1]


if __name__ == "__main__":
import doctest

doctest.testmod()
46 changes: 46 additions & 0 deletions logic_building_problems/pangram.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
"""Pangram Checker.

This module contains functions to check if a string is a pangram.
A pangram is a sentence that contains every letter of the alphabet at least once.
"""

import string

Check failure on line 7 in logic_building_problems/pangram.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (F401)

logic_building_problems/pangram.py:7:8: F401 `string` imported but unused


def is_pangram(text: str) -> bool:
"""
Check if a given string is a pangram.

A pangram is a string that contains every letter of the alphabet
at least once, ignoring case and non-alphabetic characters.

Args:
text: The string to check

Returns:
True if the string is a pangram, False otherwise

Examples:
>>> is_pangram("The quick brown fox jumps over the lazy dog")
True
>>> is_pangram("Hello World")
False
>>> is_pangram("Pack my box with five dozen liquor jugs")
True
>>> is_pangram("abcdefghijklmnopqrstuvwxyz")
True
>>> is_pangram("")
False
>>> is_pangram("ABCDEFGHIJKLMNOPQRSTUVWXYZ")
True
"""
# Convert text to lowercase and get all unique letters
letters = set(char.lower() for char in text if char.isalpha())

Check failure on line 38 in logic_building_problems/pangram.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (C401)

logic_building_problems/pangram.py:38:15: C401 Unnecessary generator (rewrite as a set comprehension)
# Check if all 26 letters of the alphabet are present
return len(letters) == 26


if __name__ == "__main__":
import doctest

doctest.testmod()
Loading