I have tried to improve my code with the suggestions I recieved in my old question about Collatz conjecture
Here is the new code:
import matplotlib.pyplot as plt
import numpy as np
def collatz_algorithm(seed: int):
"""Apply the algorithm to a certain seed and stores the values after every iteration"""
n = seed
yield seed
while n > 1:
if n % 2 == 0:
n //= 2
else:
n = 3 * n + 1
yield n
def collatz_values(seed: int):
"""Creates a list that contains the values of the seed after every iterations when applying the algorithm"""
values = list(collatz_algorithm(seed))
return values
def max_value(seed: int):
"""Gets the maximum value reached by the seed during the iterative process"""
max_value = max(collatz_values(seed))
return max_value
def colors(seeds: int):
"""Creates an array of numbers for the colormap based on the number of seeds"""
colors = plt.cm.bwr(np.linspace(0, 1, seeds + 1))
return colors
def collatz_plot(start_seed, last_seed, step = 1, alpha = 0.5, ax = 0):
"""Creates a plot indicating the number of iterations and the values reached for a certain set of seeds"""
for i in range (start_seed, last_seed + 1, step):
axs[ax].plot(collatz_values(i), color = colors(last_seed - start_seed)[i - 2], alpha = alpha)
def collatz_scatter(start_seed, last_seed, step = 1, alpha = 0.5, ax = 1):
"""Creates a scatter plot indicating the max value reached by every seed in the set"""
for i in range (start_seed, last_seed + 1, step):
axs[ax].scatter(i, max_value(i), color = colors(last_seed - start_seed)[i - 2], alpha = alpha)
def collatz_graphs (start_seed, last_seed, step = 1, alpha = 0.5):
"""Plots the 2 graphs on 2 different axis"""
collatz_plot(start_seed, last_seed, step, alpha)
collatz_scatter(start_seed, last_seed, step, alpha)
fig, axs = plt.subplots(2, 1)
collatz_graphs(1, 500)
plt.suptitle("Collatz conjecture", font = "Times new roman", size = 22)
axs[0].set_xlabel("n of iterations before stuck in a loop", font = "Times new roman")
axs[0].set_ylabel("Values after every iteration", font = "Times new roman")
axs[1].set_xlabel("Seed", font = "Times new roman")
axs[1].set_ylabel("Max value reached by the seed", font = "Times new roman")
plt.show()
What do you think about it? Please point out every mistake. Also, I would like to know why this line works:
axs[ax].plot(collatz_values(i), color = colors(last_seed - start_seed)[i - 2], alpha = alpha)
Since there is only 1 argument for the plot function I think it creates a list of integers. What I cannot understand is why it doesn't put "collatz_values" on the x axis. Should I create another variable which keeps the count of iterations to make the plot function clearer?