Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
The Collatz Sequence
#10
Truman, in your final code, you are now printing the results twice, first in your collatz function and then in your while loop. So now if I input f.e. number 3 output is:
Output:
3 10 10 5 5 16 16 8 8 4 4 2 2 1
You should remove print from your collatz function, and probably add one more condition for printing number 1.
def collatz(number):
    if number % 2 == 0:
        return number//2
    else:    
        result = 3*number + 1
        return result       
try:
    n = int(input("Give me a number: "))
    while n != 1:
        print(n)
        n = collatz(abs(n))
    if n == 1:
        print(n)
except ValueError:
    print('Type a number please!')
Also one more thing to consider -> I dont think user should be able to input negative number, from what I read on wikipedia -
Quote:The Collatz conjecture is a conjecture in mathematics that concerns a sequence defined as follows: start with any positive integer n.

Actually in this case, if statement from my comment above
    if n == 1:
should be replaced with else(same result, but nicer).
Reply


Messages In This Thread
The Collatz Sequence - by Truman - Apr-17-2018, 10:54 PM
RE: The Collatz Sequence - by micseydel - Apr-17-2018, 11:10 PM
RE: The Collatz Sequence - by Truman - Apr-18-2018, 10:11 PM
RE: The Collatz Sequence - by mlieqo - Apr-18-2018, 09:29 AM
RE: The Collatz Sequence - by vaison - Apr-18-2018, 01:41 PM
RE: The Collatz Sequence - by vaison - Apr-19-2018, 11:03 AM
RE: The Collatz Sequence - by Truman - Apr-19-2018, 09:38 PM
RE: The Collatz Sequence - by vaison - Apr-19-2018, 10:23 PM
RE: The Collatz Sequence - by Truman - Apr-19-2018, 10:48 PM
RE: The Collatz Sequence - by mlieqo - Apr-20-2018, 08:08 AM
RE: The Collatz Sequence - by s_sahil - Dec-27-2018, 07:19 AM
RE: The Collatz Sequence - by Truman - Dec-27-2018, 11:28 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Collatz-problem CaptainNeemo 2 2,266 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,861 Nov-23-2020, 05:15 PM
Last Post: cananb
  [split] The Collatz Sequence valencia 4 3,754 Jan-06-2019, 08:10 PM
Last Post: valencia

Forum Jump:

User Panel Messages

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