Skip to content

Commit 97ba7f5

Browse files
committed
feat: Add initial set of logic building problems
1 parent c79034c commit 97ba7f5

File tree

5 files changed

+211
-0
lines changed

5 files changed

+211
-0
lines changed
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
"""
2+
The Collatz Conjecture (3n + 1 Problem)
3+
4+
The conjecture states that for any positive integer n, repeatedly applying
5+
the following steps will always eventually reach 1:
6+
- If n is even, divide it by 2.
7+
- If n is odd, multiply it by 3 and add 1.
8+
"""
9+
10+
def collatz_sequence(n: int) -> list[int]:
11+
"""
12+
Generates the Collatz sequence for a given starting number.
13+
>>> collatz_sequence(6)
14+
[6, 3, 10, 5, 16, 8, 4, 2, 1]
15+
>>> collatz_sequence(1)
16+
[1]
17+
"""
18+
if n <= 0:
19+
return []
20+
21+
sequence = [n]
22+
while n != 1:
23+
if n % 2 == 0:
24+
n = n // 2
25+
else:
26+
n = 3 * n + 1
27+
sequence.append(n)
28+
return sequence
29+
30+
if __name__ == "__main__":
31+
import doctest
32+
doctest.testmod()
33+
try:
34+
num = int(input("Enter a positive integer to start the Collatz sequence: "))
35+
if num > 0:
36+
print(f"Sequence: {collatz_sequence(num)}")
37+
else:
38+
print("Please enter a positive integer.")
39+
except ValueError:
40+
print("Invalid input. Please enter an integer.")

logic_building_problems/hangman.py

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
"""
2+
A classic word-guessing game: Hangman.
3+
The computer picks a secret word, and the player tries to guess it letter by letter.
4+
"""
5+
import random
6+
7+
def play_hangman():
8+
"""
9+
Starts an interactive session of Hangman.
10+
This function is interactive and does not have a testable return value.
11+
"""
12+
words = ["python", "github", "algorithm", "developer", "computer"]
13+
secret_word = random.choice(words)
14+
guessed_letters = set()
15+
incorrect_guesses = 0
16+
max_attempts = 6
17+
18+
print("Welcome to Hangman!")
19+
20+
while incorrect_guesses < max_attempts:
21+
# Display the current state of the word
22+
display_word = ""
23+
for letter in secret_word:
24+
if letter in guessed_letters:
25+
display_word += letter
26+
else:
27+
display_word += "_"
28+
print(f"\nWord: {display_word}")
29+
print(f"Incorrect guesses left: {max_attempts - incorrect_guesses}")
30+
31+
if display_word == secret_word:
32+
print(f"Congratulations! You guessed the word: {secret_word}")
33+
return
34+
35+
guess = input("Guess a letter: ").lower()
36+
37+
if len(guess) != 1 or not guess.isalpha():
38+
print("Please enter a single letter.")
39+
continue
40+
41+
if guess in guessed_letters:
42+
print("You already guessed that letter.")
43+
elif guess in secret_word:
44+
print("Good guess!")
45+
guessed_letters.add(guess)
46+
else:
47+
print("Sorry, that letter is not in the word.")
48+
incorrect_guesses += 1
49+
guessed_letters.add(guess)
50+
51+
print(f"\nGame over! The word was: {secret_word}")
52+
53+
if __name__ == "__main__":
54+
play_hangman()
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
"""
2+
Kaprekar's Constant (6174)
3+
4+
Kaprekar's routine is an algorithm that, with a few exceptions, will eventually
5+
converge to the number 6174.
6+
7+
The routine is as follows:
8+
1. Take any four-digit number, using at least two different digits.
9+
2. Arrange the digits in descending and then in ascending order to get two
10+
four-digit numbers.
11+
3. Subtract the smaller number from the bigger number.
12+
4. Go back to step 2 and repeat.
13+
"""
14+
15+
KAPREKARS_CONSTANT = 6174
16+
17+
def kaprekar_routine(n: int) -> list[int]:
18+
"""
19+
Performs the Kaprekar routine and returns the sequence of numbers.
20+
>>> kaprekar_routine(3524)
21+
[3524, 3087, 8352, 6174]
22+
>>> kaprekar_routine(6174)
23+
[6174]
24+
"""
25+
if not 1000 <= n <= 9999:
26+
raise ValueError("Input must be a four-digit number.")
27+
if len(set(str(n).zfill(4))) < 2:
28+
raise ValueError("Input must have at least two different digits.")
29+
30+
sequence = [n]
31+
while n != KAPREKARS_CONSTANT:
32+
s_num = str(n).zfill(4)
33+
desc_str = "".join(sorted(s_num, reverse=True))
34+
asc_str = "".join(sorted(s_num))
35+
n = int(desc_str) - int(asc_str)
36+
sequence.append(n)
37+
return sequence
38+
39+
if __name__ == "__main__":
40+
import doctest
41+
doctest.testmod()
42+
try:
43+
num = int(input("Enter a 4-digit number (with at least two different digits): "))
44+
result_sequence = kaprekar_routine(num)
45+
print(f"Sequence: {' -> '.join(map(str, result_sequence))}")
46+
except ValueError as e:
47+
print(f"Error: {e}")
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
"""
2+
A simple number guessing game.
3+
The program generates a random number and the user has to guess it.
4+
"""
5+
import random
6+
7+
def guessing_game(low: int, high: int):
8+
"""
9+
Starts an interactive number guessing game.
10+
This function is interactive and does not have a return value for doctests.
11+
"""
12+
secret_number = random.randint(low, high)
13+
attempts = 0
14+
print(f"I'm thinking of a number between {low} and {high}. Can you guess it?")
15+
16+
while True:
17+
try:
18+
guess = int(input("Enter your guess: "))
19+
attempts += 1
20+
if guess < secret_number:
21+
print("Too low! Try again.")
22+
elif guess > secret_number:
23+
print("Too high! Try again.")
24+
else:
25+
print(f"Congratulations! You guessed it in {attempts} attempts.")
26+
break
27+
except ValueError:
28+
print("Invalid input. Please enter an integer.")
29+
30+
if __name__ == "__main__":
31+
guessing_game(1, 100)
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
"""
2+
A simple, interactive Rock, Paper, Scissors game.
3+
The user plays against the computer, which makes a random choice.
4+
"""
5+
import random
6+
7+
def play_rock_paper_scissors():
8+
"""
9+
Starts an interactive session of Rock, Paper, Scissors.
10+
This function is interactive and does not have a testable return value.
11+
"""
12+
options = ["rock", "paper", "scissors"]
13+
14+
while True:
15+
user_choice = input("Choose rock, paper, or scissors (or 'quit' to exit): ").lower()
16+
17+
if user_choice == "quit":
18+
print("Thanks for playing!")
19+
break
20+
21+
if user_choice not in options:
22+
print("Invalid choice. Please try again.")
23+
continue
24+
25+
computer_choice = random.choice(options)
26+
print(f"Computer chose: {computer_choice}")
27+
28+
if user_choice == computer_choice:
29+
print("It's a tie!")
30+
elif (user_choice == "rock" and computer_choice == "scissors") or \
31+
(user_choice == "scissors" and computer_choice == "paper") or \
32+
(user_choice == "paper" and computer_choice == "rock"):
33+
print("You win!")
34+
else:
35+
print("You lose!")
36+
print("-" * 20)
37+
38+
if __name__ == "__main__":
39+
play_rock_paper_scissors()

0 commit comments

Comments
 (0)