Skip to content

Commit 852726c

Browse files
committed
[Fix] Refactor Math Python Projects to Follow Guidelines
1 parent 707daa0 commit 852726c

4 files changed

Lines changed: 232 additions & 294 deletions

File tree

Lines changed: 45 additions & 61 deletions
Original file line numberDiff line numberDiff line change
@@ -1,68 +1,52 @@
1-
def binary_search(arr, target):
2-
"""
3-
Performs a binary search on a sorted list.
4-
Returns the index of the target if found, otherwise returns -1.
5-
"""
6-
low = 0
7-
high = len(arr) - 1
1+
print("=" * 40)
2+
print("🔍 BINARY SEARCH INTERACTIVE TOOL 🔍")
3+
print("=" * 40)
4+
print("\n📝 Easily find the position of a number in a sorted list.")
85

9-
while low <= high:
10-
# Calculate the middle index safely
11-
mid = (low + high) // 2
12-
guess = arr[mid]
6+
while True:
7+
print("\n" + "=" * 40)
8+
try:
9+
user_input = input("🎯 Enter sorted numbers separated by spaces (e.g., 2 5 8 12): ").strip()
10+
if not user_input:
11+
print("❌ Error: Input cannot be empty.")
12+
continue
13+
14+
arr = [int(x) for x in user_input.split()]
1315

14-
# Check if the target is found at the middle position
15-
if guess == target:
16-
return mid
16+
# Check if the list is actually sorted
17+
if arr != sorted(arr):
18+
print("❌ Error: List must be sorted for Binary Search! Please enter sorted numbers.")
19+
continue
1720

18-
# If the target is smaller, ignore the right half
19-
elif guess > target:
20-
high = mid - 1
21+
target = int(input("🎯 Enter the number you want to find: ").strip())
22+
23+
# Binary Search procedural logic
24+
low = 0
25+
high = len(arr) - 1
26+
found_index = -1
27+
28+
while low <= high:
29+
mid = (low + high) // 2
30+
guess = arr[mid]
2131

22-
# If the target is larger, ignore the left half
32+
if guess == target:
33+
found_index = mid
34+
break
35+
elif guess > target:
36+
high = mid - 1
37+
else:
38+
low = mid + 1
39+
40+
if found_index != -1:
41+
print(f"\n🎉 Success! Element found at position: {found_index + 1}")
42+
print(f"📍 Index in array: {found_index}")
2343
else:
24-
low = mid + 1
44+
print("\n😔 Element not found in the list.")
2545

26-
# Target element is not present in the list
27-
return -1
28-
29-
30-
def test_binary_search():
31-
""" Background test cases to ensure logic accuracy before user input.."""
32-
test_list = [2, 5, 8, 12, 16, 23, 38, 56, 72, 91]
33-
34-
# Test case 1: Element is in the middle
35-
assert binary_search(test_list, 23) == 5, "Test Case 1 Failed"
36-
37-
# Test case 2: Element is at the start
38-
assert binary_search(test_list, 2) == 0, "Test Case 2 Failed"
39-
40-
# Test case 3: Element does not exist
41-
assert binary_search(test_list, 100) == -1, "Test Case 3 Failed"
42-
43-
44-
if __name__ == "__main__":
45-
# For logic check
46-
test_binary_search()
47-
48-
# --- USER INTERACTION SECTION ---
49-
print(" === Binary Search Interactive Tool === ")
50-
try:
51-
user_input = input("Enter Sorted numbers seperated by spaces (e.g.,2 5 8 12) : ")
52-
arr=[int(x) for x in user_input.split()]
53-
54-
#check if the list is actually sorted
55-
if arr != sorted(arr):
56-
print("Error: List must be Sorted for Binary Search!")
57-
else:
58-
target = int(input("Enter The Number You Want to Find -:" ))
59-
result = binary_search(arr, target)
60-
61-
if result != -1:
62-
print(f"Success! Element found at position : {result +1 }")
63-
print(f"Index in array : {result}")
64-
else:
65-
print("Element not found in the List.")
66-
6746
except ValueError:
68-
print("Error: Please Enter valid integers only.")
47+
print("❌ Error: Please enter valid integers only.")
48+
49+
again = input("\n🔄 Do you want to search again? (y/n): ").strip().lower()
50+
if again != 'y':
51+
print("\n👋 Thanks for using Binary Search! Goodbye!\n")
52+
break
Lines changed: 62 additions & 111 deletions
Original file line numberDiff line numberDiff line change
@@ -1,121 +1,72 @@
1-
print("=" * 50)
2-
print("THE COLLATZ CONJECTURE SEQUENCE")
3-
print("=" * 50)
4-
print("\nAlso known as the 3n+1 problem")
5-
print("Rules:")
6-
print("- If the number is even: divide by 2")
7-
print("- If the number is odd: multiply by 3 and add 1")
8-
print("- Continue until you reach 1")
9-
print("=" * 50)
1+
print("🎮 The Collatz Conjecture Sequence 🎮")
2+
print("Also known as the 3n+1 problem\n")
3+
print("📚 Rules:")
4+
print(" - If the number is even: divide by 2")
5+
print(" - If the number is odd: multiply by 3 and add 1")
6+
print(" - Continue until you reach 1\n")
107

118
MAX_STEPS = 100000
12-
MAX_VALUE = 10**18
139
MAX_INPUT = 10**12
14-
steps_cache = {1: 0}
15-
16-
def collatz_next(n):
17-
return n // 2 if n % 2 == 0 else 3 * n + 1
18-
19-
def get_remaining_sequence(n):
20-
seq = []
21-
while n != 1:
22-
n = collatz_next(n)
23-
seq.append(n)
24-
return seq
25-
def collatz_sequence(start):
26-
if start in steps_cache:
27-
n = start
28-
yield n
29-
while n != 1:
30-
n = collatz_next(n)
31-
yield n
32-
return
33-
34-
n = start
35-
path = [n]
36-
steps = 0
37-
38-
yield n
39-
40-
while n != 1 and steps < MAX_STEPS:
41-
n = collatz_next(n)
42-
steps += 1
43-
44-
if n > MAX_VALUE:
45-
print("\n\n⚠ Computation stopped: safety limit reached")
46-
break
47-
48-
yield n
49-
path.append(n)
50-
51-
if n in steps_cache:
52-
for remaining in get_remaining_sequence(n):
53-
yield remaining
54-
steps += steps_cache[n]
55-
break
56-
57-
total = steps_cache.get(n, 0)
58-
for value in reversed(path):
59-
total += 1
60-
steps_cache[value] = total
6110

6211
while True:
6312
try:
64-
number = int(input("\nEnter a positive integer to start: "))
65-
if number > 0:
66-
if number > MAX_INPUT:
67-
print(f"Input too large! Maximum allowed: {MAX_INPUT:,}")
68-
continue
69-
break
70-
else:
71-
print("Please enter a positive integer!")
13+
number = int(input("🎯 Enter a positive integer to start: "))
14+
if number <= 0:
15+
print("❌ Please enter a positive integer!")
16+
continue
17+
if number > MAX_INPUT:
18+
print(f"⚠️ Input too large! Maximum allowed: {MAX_INPUT:,}")
19+
continue
7220
except ValueError:
73-
print("Please enter a valid number!")
74-
75-
original_number = number
76-
77-
print(f"\nStarting with: {number}")
78-
print("\nSequence:")
79-
80-
sequence = []
81-
steps = 0
82-
max_value = number
83-
84-
gen = collatz_sequence(number)
21+
print("❌ Please enter a valid number!")
22+
continue
8523

86-
first = next(gen)
87-
print(first, end="")
88-
sequence.append(first)
89-
90-
for num in gen:
91-
sequence.append(num)
92-
steps += 1
93-
max_value = max(max_value, num)
94-
print(f" → {num}", end="")
95-
if steps % 10 == 0:
96-
print()
97-
98-
print("\n\n" + "=" * 50)
99-
print("SEQUENCE COMPLETE!")
100-
print("=" * 50)
101-
print(f"Starting number: {original_number}")
102-
print(f"Total steps: {steps}")
103-
print(f"Sequence length: {len(sequence)}")
104-
print(f"Highest number reached: {max_value}")
24+
original_number = number
25+
sequence = [number]
26+
steps = 0
27+
max_value = number
10528

106-
if len(sequence) <= 100:
107-
view_details = input("\nWould you like to see step-by-step details? (yes/no): ").lower()
108-
if view_details in ['yes', 'y']:
109-
print("\nDetailed Steps:")
110-
print("-" * 50)
111-
for i in range(len(sequence) - 1):
112-
current = sequence[i]
113-
next_num = sequence[i + 1]
114-
if current % 2 == 0:
115-
print(f"Step {i + 1}: {current} is even → {current} ÷ 2 = {next_num}")
116-
else:
117-
print(f"Step {i + 1}: {current} is odd → ({current} × 3) + 1 = {next_num}")
118-
print("-" * 50)
29+
print(f"\n🚀 Starting with: {number}")
30+
print("📊 Sequence:")
31+
print(number, end="")
11932

120-
print("\n✓ The sequence reached 1 as expected!")
121-
print("=" * 50)
33+
while number != 1 and steps < MAX_STEPS:
34+
if number % 2 == 0:
35+
number = number // 2
36+
else:
37+
number = 3 * number + 1
38+
39+
steps += 1
40+
sequence.append(number)
41+
42+
if number > max_value:
43+
max_value = number
44+
45+
print(f" ➡️ {number}", end="")
46+
if steps % 10 == 0:
47+
print()
48+
49+
print("\n\n✅ SEQUENCE COMPLETE!")
50+
print(f"📍 Starting number: {original_number}")
51+
print(f"👣 Total steps: {steps}")
52+
print(f"📏 Sequence length: {len(sequence)}")
53+
print(f"🏆 Highest number reached: {max_value}")
54+
55+
if len(sequence) <= 100:
56+
view_details = input("\n🔍 Would you like to see step-by-step details? (y/n): ").strip().lower()
57+
if view_details in ['y', 'yes']:
58+
print("\n📝 Detailed Steps:")
59+
for i in range(len(sequence) - 1):
60+
current = sequence[i]
61+
next_num = sequence[i + 1]
62+
if current % 2 == 0:
63+
print(f" Step {i + 1}: {current} is even ➡️ {current} ÷ 2 = {next_num}")
64+
else:
65+
print(f" Step {i + 1}: {current} is odd ➡️ ({current} × 3) + 1 = {next_num}")
66+
67+
print("\n🎉 The sequence reached 1 as expected!")
68+
69+
again = input("\n🔄 Do you want to test another number? (y/n): ").strip().lower()
70+
if again != 'y':
71+
print("\n👋 Thanks for exploring the Collatz Conjecture! Goodbye!\n")
72+
break

0 commit comments

Comments
 (0)