Skip to content

Commit

Permalink
Merge branch 'adding-gifs' of github.com:MIT-Emerging-Talent/ET6-foun…
Browse files Browse the repository at this point in the history
…dations-group-24 into adding-gifs
  • Loading branch information
linahKhayri committed Jan 9, 2025
2 parents 7bec521 + e64772a commit 0967bd3
Show file tree
Hide file tree
Showing 16 changed files with 823 additions and 42 deletions.
3 changes: 2 additions & 1 deletion .github/PULL_REQUEST_TEMPLATE.md
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@ about: A template PR for code review with a checklist

- [ ] The function's name describes it's behavior
- [ ] The function's name matches the file name
- _It's ok to have extra helper functions if necessary, like with mergesort_
- [ ] The function has correct type annotations
- [ ] The function is not called at the top level of the function file
- _Recursive solutions **can** call the function from **inside** the function body_
Expand All @@ -68,7 +69,7 @@ about: A template PR for code review with a checklist

### Don'ts

- [ ] The function's strategy _is not_ described in the documentation
- [ ] The function's strategy _is not_ described in any docstrings or tests
- [ ] Comments explain the _strategy_, **not** the _implementation_
- [ ] The function _does not_ have more comments than code
- If it does, consider finding a new strategy or a simpler implementation
Expand Down
2 changes: 1 addition & 1 deletion .vscode/settings.json
Original file line number Diff line number Diff line change
Expand Up @@ -84,4 +84,4 @@
"Khayri",
"Linah"
]
}
}
51 changes: 51 additions & 0 deletions solutions/binary_to_decimal.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
A module for converting binary numbers to decimal.
Module contents:
- binary_to_decimal: converts binary numbers to decimal.
Created on 29/12/2024
@author: Khusro Sakhi
"""


def binary_to_decimal(binary_str: str) -> int:
"""
Converts a binary number represented as a string into its decimal equivalent.
Parameters:
binary_str: A string representing the binary number (e.g., '1010')
Returns:
The decimal equivalent of the binary number as an integer
Raises:
TypeError: If the input is not a string or None.
ValueError: If the input contains non-binary characters.
>>> binary_to_decimal ("1010")
10
>>> binary_to_decimal ("1")
1
>>> binary_to_decimal ("100")
4
"""

if not isinstance(binary_str, str):
raise TypeError("Entered value is not a string.")
if not binary_str:
raise ValueError("Input binary string cannot be empty.")
if not all(bit in "01" for bit in binary_str):
raise ValueError("Entered string contains non-binary characters.")

decimal = 0
length = len(binary_str)
for i, bit in enumerate(binary_str):
bit_value = int(bit)

decimal += bit_value * (2 ** (length - i - 1))
return decimal
69 changes: 69 additions & 0 deletions solutions/count_digits.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Module to count the number of digits in a given number.
Module contents:
- count_digits: Counts the number of digits in a given number.
Created on Wednesday, 1st January, 2025.
@author: Gai Samuel
"""


def count_digits(number: int | float | str | bool) -> int:
"""
The count_digits function counts the number of digits in a given number.
Parameters:
number: an integer/string/ boolean or float number whose digits are to be counted.
Returns:
An integer representing the number of digits in the input number.
Note that the negative sign is not counted as a digit.
Raises:
ValueError:
If the input is empty.
If the input is not an integer, float, or numeric string.
TypeError:
if there is an invalid input.
Example:
>>> count_digits(34)
2
>>> count_digits(-17)
2
>>> count_digits(0)
1
>>> count_digits(19.5)
2
>>> count_digits("24")
2
"""
# Check for empty input
if number == "":
raise ValueError("The input cannot be empty.")

# Converts a boolean to an integer.
if isinstance(number, bool):
number = int(number)

# converts a float to an integer.
if isinstance(number, float):
number = int(number)

# Handles a string input but raises a ValueError if the string is not a number.
if isinstance(number, str):
try:
number = int(number)
except ValueError as exc:
raise ValueError("Input must be a valid number.") from exc

# Check for empty or invalid inputs
if not isinstance(number, (int, float, str, bool)):
raise TypeError("Input must be an integer, float, boolean or numeric string.")

# Convert the number to a string and remove the negative sign if present.
number_str = str(abs(int(number)))

return len(number_str)
104 changes: 104 additions & 0 deletions solutions/distinct_subsequences.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
A module for calculating the number of distinct subsequences of one
string (target_str) in another string (source_str).
(LeetCode problem copied from
https://leetcode.com/problems/distinct-subsequences/)
Module contents:
- distinct_subsequences: Computes the number of
distinct subsequences of target_str in source_str.
- _count_subsequences_recursive: A helper function to compute subsequences.
Dependencies:
- functools: Used for the `cache` decorator.
Created on 26 12 2024
@author: Mohamed-Elnageeb
"""

import sys
from functools import cache

sys.setrecursionlimit(10**6) # Increase the limit to support deep recursion


def distinct_subsequences(source_str: str, target_str: str) -> int:
"""
Computes the number of distinct subsequences of string target_str
in string source_str.
This function calculates the number of ways string target_str
can appear as a subsequence in source_str.
Parameters:
source_str: str
The source string in which to find subsequences.
target_str: str
The target string to match as a subsequence.
Returns:
int: The number of distinct subsequences of target_str in source_str.
Raises:
TypeError: If the inputs are not strings.
Examples:
>>> distinct_subsequences("rabbbit", "rabbit")
3
>>> distinct_subsequences("abc", "abc")
1
>>> distinct_subsequences("abc", "def")
0
>>> distinct_subsequences("aaa", "aa")
3
"""
# Validate input
if not isinstance(source_str, str):
raise TypeError("Input source_str must be a string.")
if not isinstance(target_str, str):
raise TypeError("Input target_str must be a string.")

@cache
def _count_subsequences_recursive(source_idx: int, target_idx: int) -> int:
"""
A helper function to compute the number of subsequences.
This function calculates how many distinct ways
the substring target_str[target_idx:] can appear as a subsequence
in the substring source_str[source_idx:].
Parameters:
source_idx: int
Current index in string source_str.
target_idx: int
Current index in string target_str.
Returns:
int: The number of ways target_str[target_idx:] can appear
as a subsequence in source_str[source_idx:].
"""
# Base case: All characters of target_str are matched
if target_idx == len(target_str):
return 1
# Base case: End of source_str reached without matching all
# characters of target_str
if source_idx == len(source_str):
return 0

# Recursive case: Exclude the current character of source_str
result = _count_subsequences_recursive(source_idx + 1, target_idx)

# Recursive case: Include the current character of source_str if it
# matches target_str[target_idx]
if source_str[source_idx] == target_str[target_idx]:
result += _count_subsequences_recursive(source_idx + 1, target_idx + 1)

return result

# Start the recursion from the beginning of both strings
return _count_subsequences_recursive(0, 0)
6 changes: 3 additions & 3 deletions solutions/factorial_calculator.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@
# -*- coding: utf-8 -*-
"""
Module Name: factorial_calculator
Description: This module provides a function to calculate the factorial of a given number.
It uses a recursive approach to compute the factorial.
The module includes: the following function:
- factorial_calculator(num): Returns the factorial of the input number num.
Expand All @@ -15,7 +15,7 @@

def factorial_calculator(num: int | float) -> int:
"""
This function calculates the factorial of a non-negative integer or whole float using recursion.
This function calculates the factorial of a non-negative integer or whole float.
The factorial of a non-negative integer n is the product of all positive integers
less than or equal to num until we reach one.
Expand Down Expand Up @@ -64,6 +64,6 @@ def factorial_calculator(num: int | float) -> int:
if num == 1: # Base case 2
return 1 # turn-around 2

# Recursive case: factorial(num) = num * factorial(num-1)
# Recursive case: factorial_calculator(num) = num * factorial_calculator(num-1)
# breaking-down num | Build-up by multiplying
return num * factorial_calculator(num - 1)
4 changes: 0 additions & 4 deletions solutions/intersection_of_two.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,10 +23,6 @@ def intersection_of_two(first_list: list, second_list: list) -> list:
can contain any type of items that are allowed in a list (e.g., integers,
strings, floats, special characters, etc.)
Note:
This function could be simplified using built-in functions like set(),
which automatically handle duplicates and set intersections.
However, I wanted to write the logic manually to demonstrate how it works step-by-step
Parameters:
first_list (list): The first list of items
Expand Down
45 changes: 45 additions & 0 deletions solutions/is_leap_year.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
A module for determining whether the given year is leap year or not
Module contents:
- is_leap: determines whether the given year is leap year or not.
Created on 29/12/2024
@author: Khusro Sakhi
"""


def is_leap_year(year: int) -> bool:
"""Determines if the given year is a leap year.
Parameters:
year (int): The year to test.
Returns:
bool: True if the year is a leap year, False otherwise.
Raises:
TypeError: If the input is not an integer.
ValueError: If the input is less than or equal to 0.
>>> is_leap_year(2000)
True
>>> is_leap_year(1990)
False
>>> is_leap_year(2100)
False
>>> is_leap_year(2004)
True
"""
if not isinstance(year, int):
raise TypeError("Entered year is not an integer.")
if year <= 0:
raise ValueError("Year must be greater than 0.")

# A leap year is divisible by 4, but not by 100 unless also divisible by 400
return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)
Loading

0 comments on commit 0967bd3

Please sign in to comment.