0

new to python and wanted to try out coding the x3+1 function (if a number is odd, it gets multiplied by three and then we add 1, and if it is even, the number is divided by 2. this continues up to 1, since after that it just loops on itself). I managed to code it but i really wanted to mimplement it in a graph?

import matplotlib.pyplot as plt

def x3Graph(b):
    inc = 1
    plt.plot((inc*4), b, 'ko', ms=1)
    switch = 1
    while(switch == 1):
        if((b % 2) == 0):
            b = b/2
            inc = inc + 1
            plt.plot((inc*4), b, 'ko', ms=1)
        elif(b != 1):
            b = 3*b+1
            inc = inc + 1
            plt.plot((inc*4), b, 'ko', ms=1)
        else:
            inc = inc + 1
            switch = 2
    ax = plt.subplot(111)
    ax.plot((inc*4), b, 'ko', ms=1)
    ax.spines['right'].set_visible(False)
    ax.spines['top'].set_visible(False)
    ax.tick_params(labelbottom=False)
    plt.show()

what it looks like for 17

I set a difference of 4 every number, so really the only axis being used is the left one, the bottom one is only there to separate each point from eachother. the problem with that is that i cant use the x=[a,b] method to draw lines, so i have no idea how to do it. please keep in mind that i am an extreme beginner in python. Is there any way i can implement what i have in mind? (lines in between each point)

Cqrbon
  • 1
  • 1
  • 1
    You need to create two lists, one for the `inc` values, and another for the `b` values. And append the values during each step. Instead of plotting at each step, you only plot the lists once at the end (`plt.plot(inc_list, b_list, '-ko')`). By the way, there is no good reason to use `inc * 4` instead of just `inc`. – JohanC Sep 03 '21 at 11:55

1 Answers1

0

If you want

if a number is odd, it gets multiplied by three and then we add 1, and if it is even, the number is divided by 2

Then you can use list comprehension to create the y axis:

import matplotlib.pyplot as plt

x = range(2,100)
y = [i/2 if i%2 == 0 else i*3+1 for i in x]
plt.plot(x,y)

output:

enter image description here

mujjiga
  • 14,755
  • 2
  • 28
  • 43