-3

Why can't I see the result of the function when I use range()? I want to create a range of numbers where each the number will be evaluate in "colla" function. But range doesn't work with "colla"

def colla(num):
    fin = []
    while num != 1:
        if num % 2 == 0:
            num = num // 2
            fin.append(0)
        elif num % 2 == 1:
            num = 3 * num + 1
            fin.append(1)
    counter = []
    for Z in fin:
        if Z == 0:
            counter.append(Z)
    return ("{:.0%}".format((len(counter)/len(fin))))

for i in range(5):   
    print(colla(i)) # here I have a problem!
Nimantha
  • 6,405
  • 6
  • 28
  • 69
Gen Pol
  • 9
  • 4
  • Can you post the error message? – Mark Lavin Aug 18 '21 at 20:06
  • There's no error message. The program loops for a long time. – quamrana Aug 18 '21 at 20:07
  • Use a debugger and step through your code. It quickly becomes obvious that you're stuck in an infinite loop (because `range()` starts at `0` and `num % 2 == 0` and `num // 2` is also `0`) [How to debug small programs.](//ericlippert.com/2014/03/05/how-to-debug-small-programs/) | [What is a debugger and how can it help me diagnose problems?](//stackoverflow.com/q/25385173/843953) – Pranav Hosangadi Aug 18 '21 at 20:07
  • no error message, when i run program all is empty – Gen Pol Aug 18 '21 at 20:08
  • colla works without range – Gen Pol Aug 18 '21 at 20:09

1 Answers1

1

Your colla() function requires input numbers of 2 and above.

Try this:

for i in range(2,6):   
    print(colla(i))

Please be aware that calling colla(0) will result in an infinite loop, or rather "out of memory" when fin fills up with 0s. Also calling colla(1) results in a ZeroDivisionError because fin will be an empty list.

quamrana
  • 37,849
  • 12
  • 53
  • 71
  • Yeah! It works. Thank you! I realized, my range starting with zero number and creating infity loop – Gen Pol Aug 18 '21 at 20:13