-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathwhile_loops.py
More file actions
185 lines (153 loc) · 6.49 KB
/
Copy pathwhile_loops.py
File metadata and controls
185 lines (153 loc) · 6.49 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
"""
While Loop Exercises - Complete the functions below
Run this file with: python topic.py
Or work interactively with: python3 -i topic.py
"""
# Exercise 1: Basic While Loops
def count_down(n):
"""Print countdown from n to 1, then print 'Blast off!'"""
# Your code here
pass
def sum_while_positive(numbers):
"""Sum numbers from the list while they are positive. Stop at first non-positive."""
# Your code here
pass
def find_first_even(numbers):
"""Return the first even number in the list, or None if no even number exists."""
# Your code here
pass
# Exercise 2: Input Validation Loops
def get_positive_number():
"""Keep asking user for input until they enter a positive number."""
# Your code here - use input() function
# Note: This won't work in automated testing, so just return a placeholder
return 5 # placeholder for testing
def get_valid_grade():
"""Keep asking for a grade between 0 and 100."""
# Your code here - return placeholder for testing
return 85 # placeholder for testing
def get_yes_or_no():
"""Keep asking until user enters 'yes' or 'no'."""
# Your code here - return placeholder for testing
return "yes" # placeholder for testing
# Exercise 3: Number Processing
def factorial_while(n):
"""Calculate factorial using while loop."""
# Your code here
pass
def fibonacci_sequence(limit):
"""Generate Fibonacci sequence up to limit."""
# Your code here
pass
def digital_root(number):
"""Keep summing digits until single digit remains."""
# Example: 9875 -> 9+8+7+5 = 29 -> 2+9 = 11 -> 1+1 = 2
# Your code here
pass
# Exercise 4: String Processing
def remove_vowels_while(text):
"""Remove all vowels from text using while loop."""
# Your code here
pass
def reverse_string_while(text):
"""Reverse string using while loop."""
# Your code here
pass
def find_longest_word(text):
"""Find the longest word in a sentence."""
# Your code here
pass
# Exercise 5: List Processing
def remove_duplicates_while(items):
"""Remove duplicates from list while preserving order."""
# Your code here
pass
def merge_sorted_arrays(arr1, arr2):
"""Merge two sorted arrays into one sorted array."""
# Your code here
pass
def find_peak_element(numbers):
"""Find an element that is greater than its neighbors."""
# Your code here
pass
# Exercise 6: Game Logic
def guessing_game_logic(secret, max_attempts):
"""Simulate number guessing game logic."""
# Return number of attempts needed (simulate with simple logic)
# Your code here
pass
def rock_paper_scissors_tournament(rounds):
"""Simulate tournament and return winner."""
# Your code here - return placeholder
return "Player 1" # placeholder
def dice_roll_until_sum(target_sum):
"""Keep rolling two dice until their sum equals target."""
# Your code here - return number of rolls needed
# Use random.randint(1, 6) for dice rolls
import random
# Your code here
pass
# Exercise 7: Mathematical Algorithms
def gcd_while(a, b):
"""Calculate Greatest Common Divisor using Euclidean algorithm."""
# Your code here
pass
def power_while(base, exponent):
"""Calculate base^exponent using while loop."""
# Your code here
pass
def is_prime_while(number):
"""Check if number is prime using while loop."""
# Your code here
pass
# Exercise 8: Advanced Processing
def collatz_sequence_length(n):
"""Calculate length of Collatz sequence starting from n."""
# Collatz: if even, divide by 2; if odd, multiply by 3 and add 1
# Continue until reaching 1
# Your code here
pass
def binary_search_while(sorted_list, target):
"""Implement binary search using while loop."""
# Your code here
pass
def find_equilibrium_index(numbers):
"""Find index where sum of left elements equals sum of right elements."""
# Your code here
pass
def run_tests():
"""Test all the functions to verify they work correctly."""
print("Testing Basic While Loops:")
print("count_down(5):")
count_down(5) # Should print 5, 4, 3, 2, 1, Blast off!
print(f"sum_while_positive([2, 3, 4, -1, 5]): {sum_while_positive([2, 3, 4, -1, 5])}") # Should print 9
print(f"find_first_even([1, 3, 4, 7]): {find_first_even([1, 3, 4, 7])}") # Should print 4
print(f"find_first_even([1, 3, 5]): {find_first_even([1, 3, 5])}") # Should print None
print("\nTesting Number Processing:")
print(f"factorial_while(5): {factorial_while(5)}") # Should print 120
print(f"fibonacci_sequence(20): {fibonacci_sequence(20)}") # Should print [0, 1, 1, 2, 3, 5, 8, 13]
print(f"digital_root(9875): {digital_root(9875)}") # Should print 2
print("\nTesting String Processing:")
print(f"remove_vowels_while('hello world'): {remove_vowels_while('hello world')}") # Should print 'hll wrld'
print(f"reverse_string_while('hello'): {reverse_string_while('hello')}") # Should print 'olleh'
print(f"find_longest_word('The quick brown fox'): {find_longest_word('The quick brown fox')}") # Should print 'quick' or 'brown'
print("\nTesting List Processing:")
print(f"remove_duplicates_while([1, 2, 2, 3, 1]): {remove_duplicates_while([1, 2, 2, 3, 1])}") # Should print [1, 2, 3]
print(f"merge_sorted_arrays([1, 3, 5], [2, 4, 6]): {merge_sorted_arrays([1, 3, 5], [2, 4, 6])}") # Should print [1, 2, 3, 4, 5, 6]
print(f"find_peak_element([1, 3, 2, 4, 1]): {find_peak_element([1, 3, 2, 4, 1])}") # Should print index of peak
print("\nTesting Mathematical Algorithms:")
print(f"gcd_while(48, 18): {gcd_while(48, 18)}") # Should print 6
print(f"power_while(2, 8): {power_while(2, 8)}") # Should print 256
print(f"is_prime_while(17): {is_prime_while(17)}") # Should print True
print(f"is_prime_while(15): {is_prime_while(15)}") # Should print False
print("\nTesting Advanced Processing:")
print(f"collatz_sequence_length(5): {collatz_sequence_length(5)}") # Should print length of sequence
print(f"binary_search_while([1, 3, 5, 7, 9], 5): {binary_search_while([1, 3, 5, 7, 9], 5)}") # Should print 2
print(f"find_equilibrium_index([1, 3, 5, 2, 2]): {find_equilibrium_index([1, 3, 5, 2, 2])}") # Should find equilibrium
if __name__ == "__main__":
print("Python While Loop Exercises")
print("=" * 40)
print("Complete the functions above, then run this file to test them.")
print("Uncomment the line below when you're ready to test:")
print()
# run_tests() # Uncomment this line to run tests