Python Forum
[split] The Collatz Sequence
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[split] The Collatz Sequence
#1
Hello,

This is my first time posting. Hope my question is clear and thank you in advance for everyone's advise.

I'm newbie to python and never expose to any programming whatsoever.

Took a while to figure out this collatz exercise - based on Automate the Boring Stuff (ABS).

Questions:
1.The code below gives me the result I want - based on what the output should be per ABS and after doing many hours of research on how others solve this (and tweak it to my style).
When the code prompt me to 'enter a number', I type 3 and i get the expected output.
However, I don't understand why the WHILE statements has to be !=1?
Since I type 3 anyway (assume user only type 3), I tried to change the statement to >2 or =3, but it gives me different result. I'm very confused. Huh Cry

2. Is it possible to use FOR loop instead of WHILE loop?
Try to do it myself, (just replace WHILE with FOR), and I got error. I also can't seem to find anyone else who use FOR loop in this exercise.

3. What's the difference between print and return? I thought I was just duplicating the code until I accidentally switch the order of print/return (i.e.return THEN print, instead of print THEN return), and the code doesn't work. Tried to do my own google research but i don't see anything very clear. Maybe it will help if you can please advise based on my code below (so i can relate to it)?

Again, thank you kindly.

print('enter a number')
def collatz(number):
    if int(number) %2==0:
        print(int(number)//2)
        return(int(number)//2)    
    else:
        print(3*int(number)+1)
        return(3*int(number)+1)
        
        
number=input()
[b]while int(number)!=1:[/b]
    number=collatz(number)
Reply


Messages In This Thread
[split] The Collatz Sequence - by valencia - Jan-06-2019, 06:01 AM
RE: [split] The Collatz Sequence - by Gribouillis - Jan-06-2019, 10:23 AM
RE: [split] The Collatz Sequence - by valencia - Jan-06-2019, 01:39 PM
RE: [split] The Collatz Sequence - by Gribouillis - Jan-06-2019, 01:47 PM
RE: [split] The Collatz Sequence - by valencia - Jan-06-2019, 08:10 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Collatz-problem CaptainNeemo 2 2,194 Dec-07-2020, 04:09 PM
Last Post: deanhystad
  How can I found how many numbers are there in a Collatz Sequence that I found? cananb 5 3,767 Nov-23-2020, 05:15 PM
Last Post: cananb
  The Collatz Sequence Truman 11 14,104 Dec-27-2018, 11:28 PM
Last Post: Truman

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020