1

I am trying to display the 3x+1 problem (if the number is odd multiply it by 3 and add 1, if it is even divide by 2) live on a line graph. How can I take the outputs that are still generating and plot them on a graph in real time?

This is the code I wrote:

from random import randint
random_int = (randint(1, 100))
i = 1

while i == 1:
    if random_int % 2 == 0:
        random_int = random_int/2
        print(random_int)
    else:
        random_int = random_int*3+1
        print(random_int)
John Kugelman
  • 349,597
  • 67
  • 533
  • 578

1 Answers1

0

Create a recursive function and plot using matplotlib

import matplotlib.pyplot as plt

def myFun(num: int, counter=1):
    if num == 1:  # if equal to 1 end the loop and return
        plt.scatter(counter, num)  # plot the last point - i.e., 1
        return num, counter
    plt.scatter(counter, num) # plot counter on x and number on y
    # Call your function again (recursion)
    return myFun(num//2 if num%2 == 0 else 3*num+1, counter+1)

myFun(123)

enter image description here

Without calling your function in the return

def myFun(num: int, counter=1):
    while True:
        if num == 1:  # if equal to 1 end the loop and return
            plt.scatter(counter, num) # plot the last point - i.e., 1
            return num, counter
        plt.scatter(counter, num) # plot counter on x and number on y
        num, counter = num//2 if num%2 == 0 else 3*num+1, counter+1

myFun(123)
It_is_Chris
  • 13,504
  • 2
  • 23
  • 41
  • It would be better to use a loop. Recursion risks stack overflow since Python lacks [tail call optimization](https://stackoverflow.com/questions/13591970/does-python-optimize-tail-recursion). – John Kugelman Jun 03 '22 at 14:41