Iteration: Exercise Answers

Iteration: Exercise Answers#

  1. Write a function greater_than_x that takes two parameters: a list and a number. The function should return a new list consisting of any entries in the list greater than the number. Assume all entries in the list are numbers.

1def greater_than_x(l, x):
2    result = []
3    for y in l:
4        if y > x:
5            result.append(y)
6    return result
7
8greater_than_x([1, 2, 3, 5, 6, 7, 8, 9, 10], 5)
[6, 7, 8, 9, 10]
  1. Given this list of closing stock prices, create functions to compute the mean, median, and standard deviation. Assume we have a sample, but you can also write your function to make this an optional flag.

stock_prices = [ 123.75, 124.38, 121.78, 123.24, 122.41, 121.78, 127.88, 127.81, 128.70, 131.88]
 1stock_prices = [123.75, 124.38, 121.78, 123.24, 122.41, 121.78, 127.88, 127.81, 128.70, 131.88]
 2
 3def compute_mean(values):
 4    return sum(values) / len(values)
 5
 6def compute_median(values):
 7    sorted_list = sorted(values)
 8    num_elements = len(values)
 9    if num_elements % 2 == 0:
10        return (sorted_list[num_elements // 2] + sorted_list[num_elements // 2 - 1]) / 2
11    else:
12        return sorted_list[num_elements // 2]
13
14def compute_standard_deviation(values, sample=True):
15    mean = compute_mean(values)
16    total = 0
17    for price in values:
18        total += (price - mean) ** 2
19    if sample:
20        return (total / (len(values) - 1)) ** 0.5
21    else:
22        return (total / len(values)) ** 0.5
23
24print(f"Mean:               {compute_mean(stock_prices):.4f}")
25print(f"Median:             {compute_median(stock_prices):.4f}")
26print(f"Std Dev (sample):   {compute_standard_deviation(stock_prices):.4f}")
27print(f"Std Dev (pop):      {compute_standard_deviation(stock_prices, sample=False):.4f}")
Mean:               125.3610
Median:             124.0650
Std Dev (sample):   3.4705
Std Dev (pop):      3.2924
  1. Generate a range that produces the following numbers: 10, 12, 14, 16, 18, and 20.

1list(range(10, 21, 2))
[10, 12, 14, 16, 18, 20]
  1. Create a guessing game. Generate a random number between 1 and 100. Have the user guess. Print a message if the guess is too high, too low, or correct. Repeat until the user guesses the number. Print the number of guesses.

 1import random
 2
 3number = random.randint(1, 100)
 4num_guesses = 0
 5print("I've generated a random number between 1 and 100. Try to guess it!")
 6while True:
 7    num_guesses += 1
 8    guess = int(input("Enter your guess: "))
 9    if guess == number:
10        break
11    elif guess < number:
12        print("That number was too low.")
13    else:
14        print("That number was too high.")
15print(f"Congratulations! You guessed it in {num_guesses} guesses.")
I've generated a random number between 1 and 100. Try to guess it!
---------------------------------------------------------------------------
StdinNotImplementedError                  Traceback (most recent call last)
Cell In[4], line 8
      4 num_guesses = 0
      5 print("I've generated a random number between 1 and 100. Try to guess it!")
      6 while True:
      7     num_guesses += 1
----> 8     guess = int(input("Enter your guess: "))
      9     if guess == number:
     10         break
     11     elif guess < number:

File ~/Documents/GitHub/jupyternotebooks/venv/lib/python3.14/site-packages/ipykernel/kernelbase.py:1402, in Kernel.raw_input(self, prompt)
   1400 if not self._allow_stdin:
   1401     msg = "raw_input was called, but this frontend does not support input requests."
-> 1402     raise StdinNotImplementedError(msg)
   1403 return self._input_request(
   1404     str(prompt),
   1405     self._get_shell_context_var(self._shell_parent_ident),
   1406     self.get_parent("shell"),
   1407     password=False,
   1408 )

StdinNotImplementedError: raw_input was called, but this frontend does not support input requests.
  1. Produce a compound interest chart for ten years using 1 to 15% for the interest rate. The x-axis should be the interest rate, with the y-axis being the years. Right justify the numbers. Assume $100.00 is the initial principle.

 1def compute_compound_interest(principle, rate, years):
 2    n = 12
 3    return principle * (1 + rate / n) ** (n * years)
 4
 5principle = 100
 6num_years = 10
 7start_interest_rate = 1
 8end_interest_rate = 15
 9
10print("Interest Rate".center(end_interest_rate * 7 + 7, ' '))
11print("Years  ", end='')
12for interest in range(start_interest_rate, end_interest_rate + 1):
13    print(f"{interest:7d}", end='')
14print()
15
16for year in range(1, num_years + 1):
17    print(f"   {year:2d}  ", end='')
18    for interest in range(start_interest_rate, end_interest_rate + 1):
19        amount = compute_compound_interest(principle, interest / 100, year)
20        print(f"{amount:7.2f}", end='')
21    print()
                                                 Interest Rate                                                  
Years        1      2      3      4      5      6      7      8      9     10     11     12     13     14     15
    1   101.00 102.02 103.04 104.07 105.12 106.17 107.23 108.30 109.38 110.47 111.57 112.68 113.80 114.93 116.08
    2   102.02 104.08 106.18 108.31 110.49 112.72 114.98 117.29 119.64 122.04 124.48 126.97 129.51 132.10 134.74
    3   103.04 106.18 109.41 112.73 116.15 119.67 123.29 127.02 130.86 134.82 138.89 143.08 147.39 151.83 156.39
    4   104.08 108.32 112.73 117.32 122.09 127.05 132.21 137.57 143.14 148.94 154.96 161.22 167.73 174.50 181.54
    5   105.12 110.51 116.16 122.10 128.34 134.89 141.76 148.98 156.57 164.53 172.89 181.67 190.89 200.56 210.72
    6   106.18 112.74 119.69 127.07 134.90 143.20 152.01 161.35 171.26 181.76 192.90 204.71 217.23 230.51 244.59
    7   107.25 115.01 123.34 132.25 141.80 152.04 163.00 174.74 187.32 200.79 215.22 230.67 247.22 264.94 283.91
    8   108.33 117.34 127.09 137.64 149.06 161.41 174.78 189.25 204.89 221.82 240.13 259.93 281.34 304.50 329.55
    9   109.41 119.70 130.95 143.25 156.68 171.37 187.42 204.95 224.11 245.04 267.91 292.89 320.18 349.98 382.53
   10   110.51 122.12 134.94 149.08 164.70 181.94 200.97 221.96 245.14 270.70 298.91 330.04 364.37 402.25 444.02
  1. Read two strings from the user. The first string is a text block. The second string is a character, series of characters, or a word to find within each word of the text block. Split the first string by whitespace and then keep only those words that contain the second string. Join the remaining words together into a string, separated by a comma.

 1sentence = input("Enter a sentence: ")
 2search_string = input("Enter the search string to find: ")
 3
 4words = sentence.split()
 5result = []
 6for word in words:
 7    if search_string in word:
 8        result.append(word)
 9final_result = ",".join(result)
10print(final_result)
---------------------------------------------------------------------------
StdinNotImplementedError                  Traceback (most recent call last)
Cell In[6], line 1
----> 1 sentence = input("Enter a sentence: ")
      2 search_string = input("Enter the search string to find: ")
      3 
      4 words = sentence.split()

File ~/Documents/GitHub/jupyternotebooks/venv/lib/python3.14/site-packages/ipykernel/kernelbase.py:1402, in Kernel.raw_input(self, prompt)
   1400 if not self._allow_stdin:
   1401     msg = "raw_input was called, but this frontend does not support input requests."
-> 1402     raise StdinNotImplementedError(msg)
   1403 return self._input_request(
   1404     str(prompt),
   1405     self._get_shell_context_var(self._shell_parent_ident),
   1406     self.get_parent("shell"),
   1407     password=False,
   1408 )

StdinNotImplementedError: raw_input was called, but this frontend does not support input requests.
  1. Given the following lists, generate random sentences by combining random words from each list in this order: article noun verb preposition article noun. Capitalize the first word of the sentence and place a period at the end. Repeat five times.

 1import random
 2
 3article = ["the", "a", "one", "some", "any"]
 4noun = ["boy", "girl", "dog", "town", "car"]
 5verb = ["drove", "jumped", "ran", "walked", "skipped"]
 6preposition = ["to", "from", "over", "under", "on"]
 7
 8for i in range(5):
 9    sentence = (random.choice(article).capitalize() + " " + random.choice(noun) + " " +
10                random.choice(verb) + " " + random.choice(preposition) + " " +
11                random.choice(article) + " " + random.choice(noun) + ".")
12    print(sentence)
Some car jumped on some dog.
Some boy drove to the dog.
A town drove from some girl.
The girl ran on a town.
The boy drove on any boy.
  1. Write a function that converts an integer to a string with a specific base. def convert_int_to_base(i, base=10):

 1def convert_int_to_base(i, base=10):
 2    characters = "0123456789abcdefghijklmnopqrstuvwxyz"
 3    result = ""
 4    while i >= base:
 5        i, r = divmod(i, base)
 6        result = characters[r] + result
 7    return characters[i] + result
 8
 9print(convert_int_to_base(190, 16))  # 'be'
10print(convert_int_to_base(16, 16))   # '10'
11print(convert_int_to_base(255, 16))  # 'ff'
12print(convert_int_to_base(100, 10))  # '100'
13print(convert_int_to_base(8, 2))     # '1000'
be
10
ff
100
1000