Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

names sorter completed #40

Open
wants to merge 10 commits into
base: main
Choose a base branch
from
30 changes: 30 additions & 0 deletions ls
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
14-sorting-strings-in-alphabetical-order
15-finding-the-prime-numbers
* 55-prime_num_generator
main
remotes/origin/11-upload-base-readme-file
remotes/origin/14-sorting-strings-in-alphabetical-order
remotes/origin/15-finding-the-prime-numbers
remotes/origin/32-checking-prime-numbers
remotes/origin/34-missing-number
remotes/origin/55-prime_num_generator
remotes/origin/6-longest-substring
remotes/origin/7-anagram-checker
remotes/origin/8-is-number-odd
remotes/origin/9-factorial
remotes/origin/GP25_Group-Norms
remotes/origin/HEAD -> origin/main
remotes/origin/Max-Integer
remotes/origin/Min-Integer
remotes/origin/binary-search
remotes/origin/communication
remotes/origin/constraints
remotes/origin/count-capitalized-words
remotes/origin/is-leap-year
remotes/origin/is-palindrome
remotes/origin/ka-branch
remotes/origin/learning-goals
remotes/origin/main
remotes/origin/missing-numbers
remotes/origin/multiplication-table
remotes/origin/revert-44-missing-numbers
75 changes: 75 additions & 0 deletions solutions/15-finding-the-prime-numbers.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
"""
A module for generating prime numbers up to a given limit.

Module contents:
- generate_primes(limit): Generates a list of prime numbers up to a given limit.
- get_valid_input(prompt): Prompts the user for valid input and validates it as a positive number.

Check failure on line 6 in solutions/15-finding-the-prime-numbers.py

View workflow job for this annotation

GitHub Actions / py_linting

Ruff (E501)

solutions/15-finding-the-prime-numbers.py:6:89: E501 Line too long (102 > 88)

Check failure on line 6 in solutions/15-finding-the-prime-numbers.py

View workflow job for this annotation

GitHub Actions / py_linting

Ruff (E501)

solutions/15-finding-the-prime-numbers.py:6:89: E501 Line too long (102 > 88)

Prime number generation rules:
- A prime number is a natural number greater than 1 that is not divisible by any number other than 1 and itself.

Check failure on line 9 in solutions/15-finding-the-prime-numbers.py

View workflow job for this annotation

GitHub Actions / py_linting

Ruff (E501)

solutions/15-finding-the-prime-numbers.py:9:89: E501 Line too long (116 > 88)

Check failure on line 9 in solutions/15-finding-the-prime-numbers.py

View workflow job for this annotation

GitHub Actions / py_linting

Ruff (E501)

solutions/15-finding-the-prime-numbers.py:9:89: E501 Line too long (116 > 88)
"""


def generate_primes(limit):
"""
Generate a series of prime numbers up to a given limit.

Args:
limit (float): The upper limit up to which prime numbers are generated.

Returns:
list: A list of prime numbers up to the specified limit.

Raises:
AssertionError:
- If 'limit' is not a float or integer.
- If 'limit' is less than 2.

Example:
>>> generate_primes(10)
[2, 3, 5, 7]
"""
# Input validation
assert isinstance(limit, (int, float)), "Limit must be a float or an integer"
assert limit >= 2, "Limit must be greater than or equal to 2"

primes = []
for num in range(2, int(limit) + 1):
if all(num % i != 0 for i in range(2, int(num**0.5) + 1)):
primes.append(num)
return primes


def get_valid_input(prompt):
"""
Prompt the user for input and validate it as a positive number (integer or float).

Args:
prompt (str): The message displayed to the user.

Returns:
float: A valid positive number input.

Raises:
AssertionError: If the prompt is not a string.

Example:
>>> get_valid_input("Enter a number: ")
# User enters 10
10.0
"""
assert isinstance(prompt, str), "Prompt must be a string"

while True:
try:
value = float(input(prompt)) # Accept input as float
if value > 0: # Ensure the value is positive
return value
print("The number must be greater than 0.")
except ValueError:
print("Invalid input. Please enter a valid number.")


if __name__ == "__main__":
user_limit = get_valid_input("Enter the limit for prime numbers: ")
print(f"Prime numbers up to {int(user_limit)}: {generate_primes(user_limit)}")
97 changes: 97 additions & 0 deletions solutions/names_sorter.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
"""
A module for sorting and displaying names from a dictionary based on
first names.
The names of the team's members (Group-25) are the data utilized to
run this program.

Module contents:
- extract_first_name(item):
Extracts the first name from a dictionary item.
- display_sorted_names(names_dict): Displays names sorted by first names.

Sorting rules:
- Names are sorted alphabetically by first names,
- then by last names if first names are identical.
"""

from typing import Dict, Tuple


def extract_first_name(item: Tuple[str, str]) -> str:
"""
Extract the first name from a dictionary item.

Args:
item (Tuple[str, str]): A tuple containing (last_name, first_name).
Returns:
str: The first name.
Raises:
TypeError: If 'item' is not a tuple.
ValueError: If 'item' does not contain exactly two elements.
"""
if not isinstance(item, tuple):
raise TypeError("Input item must be a tuple")
if len(item) != 2:
raise ValueError(
"Input tuple must contain exactly two elements "
"(last_name, first_name)"
)
return item[1]


def get_first_name(item: Tuple[str, str]) -> str:
"""
Get the first name from a tuple containing (last_name, first_name).

Args:
item (Tuple[str, str]): A tuple containing (last_name, first_name).
Returns:
str: The first name.
"""
return extract_first_name(item)


def display_sorted_names(names_dict: Dict[str, str]) -> None:
"""
Display names in alphabetical order of first names.

Args:
names_dict (Dict[str, str]): Dictionary with last names as keys and
first names as values.
"""
if not isinstance(names_dict, dict):
raise TypeError("names_dict must be a dictionary")
for key, value in names_dict.items():
if not isinstance(key, str) or not isinstance(value, str):
raise TypeError("Both keys and values must be strings")

if not names_dict:
print("No names to display.")
return

sorted_names = sorted(
names_dict.items(), key=lambda item: (item[1].lower(), item[0].lower())
)

for i, (last_name, first_name) in enumerate(sorted_names, 1):
print(f"{i}. {first_name} {last_name}")


# Define group names, then main block
group_names = {
# spell-checker: disable
"Abd Elraheem": "Amin",
"Mohammed": "Razan",
"Seedahmed": "Abdalrahman",
"Solomon": "Alexander",
"Ibrahim": "Azza",
"El-Waleed": "Tamir",
"Saeed": "Mohamed",
"Alaa": "Mohamed",
"Albashityalshaer": "Kefah",
"Makki": "Mohamed",
# spell-checker: enable
}

if __name__ == "__main__":
display_sorted_names(group_names)
65 changes: 65 additions & 0 deletions solutions/prime_num_generator.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
"""
A module for generating prime numbers up to a given limit.
Module contents:
- generate_primes(limit): Generates a list of prime numbers up to a given limit.
- get_valid_input(prompt): Prompts the user for valid input and validates it as a positive number.
Prime number generation rules:
- A prime number is a natural number greater than 1 that is not divisible by any number other than 1 and itself.
"""


def generate_primes(limit):
"""
Generate a series of prime numbers up to a given limit.
Args:
limit (float): The upper limit up to which prime numbers are generated.
Returns:
list: A list of prime numbers up to the specified limit.
Raises:
AssertionError:
- If 'limit' is not a float or integer.
- If 'limit' is less than 2.
Example:
>>> generate_primes(10)
[2, 3, 5, 7]
"""
# Input validation
assert isinstance(limit, (int, float)), "Limit must be a float or an integer"
assert limit >= 2, "Limit must be greater than or equal to 2"

primes = []
for num in range(2, int(limit) + 1):
if all(num % i != 0 for i in range(2, int(num**0.5) + 1)):
primes.append(num)
return primes


def get_valid_input(prompt):
"""
Prompt the user for input and validate it as a positive number (integer or float).
Args:
prompt (str): The message displayed to the user.
Returns:
float: A valid positive number input.
Raises:
AssertionError: If the prompt is not a string.
Example:
>>> get_valid_input("Enter a number: ")
# User enters 10
10.0
"""
assert isinstance(prompt, str), "Prompt must be a string"

while True:
try:
value = float(input(prompt)) # Accept input as float
if value > 0: # Ensure the value is positive
return value
print("The number must be greater than 0.")
except ValueError:
print("Invalid input. Please enter a valid number.")


if __name__ == "__main__":
user_limit = get_valid_input("Enter the limit for prime numbers: ")
print(f"Prime numbers up to {int(user_limit)}: {generate_primes(user_limit)}")
6 changes: 6 additions & 0 deletions solutions/pyproject.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
[tool.ruff]
exclude = [
"solutions/is_leap_year.py" # Exclude nonexistent file
]
line-length = 88 # Optional: set a line-length limit
select = ["E", "F", "W"] # Optional: select specific error codes to check
70 changes: 70 additions & 0 deletions solutions/str_sorting.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
"""
A module for sorting and displaying names from a dictionary based on first names.
The names of the team's members (Group-25) are the data utilized to run this program.
Module contents:
- get_first_name(item): Extracts the first name from a dictionary item.
- display_sorted_names(names_dict): Displays names sorted by first names.
Sorting rules:
- Names are sorted alphabetically by first names, then by last names if first names are identical.
"""

from typing import Dict, Tuple

def get_first_name(item: Tuple[str, str]) -> str:
"""
Extract the first name from a dictionary item.
Args:
item (Tuple[str, str]): A tuple containing (last_name, first_name).
Returns:
str: The first name.
Raises:
TypeError: If 'item' is not a tuple.
ValueError: If 'item' does not contain exactly two elements.
"""
if not isinstance(item, tuple):
raise TypeError("Input item must be a tuple")
if len(item) != 2:
raise ValueError("Input tuple must contain exactly two elements (last_name, first_name)")
return item[1]

def display_sorted_names(names_dict: Dict[str, str]) -> None:
"""
Display names in alphabetical order of first names.
Args:
names_dict (Dict[str, str]): Dictionary with last names as keys and first names as values.
Returns:
None. Prints names in format:
1. FirstName LastName
2. FirstName LastName
"""
if not isinstance(names_dict, dict):
raise TypeError("names_dict must be a dictionary")
for key, value in names_dict.items():
if not isinstance(key, str) or not isinstance(value, str):
raise TypeError("Both keys and values must be strings")

if not names_dict:
print("No names to display.")
return

sorted_names = sorted(names_dict.items(), key=lambda item: (item[1].lower(), item[0].lower()))

for i, (last_name, first_name) in enumerate(sorted_names, 1):
print(f"{i}. {first_name} {last_name}")

# Define group names, then main block
group_names = {
"Abd Elraheem": "Amin",
"Mohammed": "Razan",
"Seedahmed": "Abdalrahman",
"Solomon": "Alexander",
"Ibrahim": "Azza",
"El-Waleed": "Tamir",
"Saeed": "Mohamed",
"Alaa": "Mohamed",
"Albashityalshaer": "Kefah",
"Makki": "Mohamed"
}

if __name__ == "__main__":
display_sorted_names(group_names)
Loading
Loading