|
| 1 | +# Double all values in a list using built-in range function. |
| 2 | + |
| 3 | +values = [1, 2, 3] |
| 4 | +for i in range(len(values)): |
| 5 | + values[i] = 2 * values[i] |
| 6 | + |
| 7 | +print(values) |
| 8 | + |
| 9 | + |
| 10 | +# Double all values using enumerate built-in function. |
| 11 | + |
| 12 | +values = [1, 2, 3] |
| 13 | +for pair in enumerate(values): |
| 14 | + i = pair[0] |
| 15 | + v = pair[1] |
| 16 | + values[i] = 2 * v |
| 17 | + |
| 18 | +print(values) |
| 19 | + |
| 20 | + |
| 21 | +# Easier to read solution |
| 22 | + |
| 23 | +values = [1, 2, 3] |
| 24 | +for (i, v) in enumerate(values): # i stands for index in the list values, v stands for value in the list values |
| 25 | + values[i] = 2 * v |
| 26 | + |
| 27 | +print(values) |
| 28 | + |
| 29 | +# Example of ragged list |
| 30 | + |
| 31 | +times = [["8:30", "9:03", "10:20", "11:23", "13:00"], |
| 32 | + ["8:01", "9:35", "10:00", "11:01", "11:02"], |
| 33 | + ["9:15", "10:01", "11:11", "11:29", "13:00"], |
| 34 | + ["10:20", "11:00", "11:02", "11:07", "12:07"], |
| 35 | + ["9:01", "12:23", "13:23", "14:00", "14:01"]] |
| 36 | +for day in times: |
| 37 | + for time in day: |
| 38 | + print(time) |
| 39 | + |
| 40 | + |
| 41 | +# Calculate the growth of a bacteria colony using a simple exponential growth model |
| 42 | +# P(t + 1) = P(t) + rP(t) |
| 43 | +# P(t) population size at time, r is the growth rate |
| 44 | + |
| 45 | +time = 0 |
| 46 | +population = 1000 |
| 47 | +growth_rate = 0.21 # 21% growth per minute |
| 48 | +while population < 2000: |
| 49 | + population = round(population + growth_rate * population, 2) |
| 50 | + print(population) |
| 51 | + time = time + 1 |
| 52 | +print(f"It took {time} minutes for the bacteria to double") |
| 53 | +print(f" and the final population was {population} bacteria") |
| 54 | + |
1 | 55 |
|
0 commit comments