Collatz sequence including the user value in the output - python

How do I include the user input value in the very first place in the output?
here is my code below:
seq = []
n = int(input("\nEnter a number (greater than 1): "))
while (n > 1):
if n % 2 == 0:
n = n // 2
else:
n = 3 * n + 1
seq.append(n)
print()
print(*seq)
So when I entered 6, it was printed like this:
3 10 5 16 8 4 2 1
My entered value (which MUST be included) is missing.
Please help!

In your current code, you add n to seq at the end of every iteration. To add the initial value of n, simply do seq.append(n) before entering the while loop:
seq = []
n = int(input("\nEnter a number (greater than 1): "))
seq.append(n) # this is the addition you need
while (n > 1):
if n % 2 == 0:
n = n // 2
else:
n = 3 * n + 1
seq.append(n)
print()
print(*seq)

There are several ways you can do this. I believe the most logical way is to move your seq.append(n) statement to the first line of your while loop to capture your input. The issue will then be that 1 will be dropped off the end of the list. To fix that, you change your while loop condition to capture the one and add a condition to break out of the while loop:
seq = []
n = int(input("\nEnter a number (greater than 1): "))
while (n > 0):
seq.append(n)
if n == 1:
break
if n % 2 == 0:
n = n // 2
else:
n = 3 * n + 1
print()
print(*seq)
#output:
Enter a number (greater than 1): 6
6 3 10 5 16 8 4 2 1

Related

Python while loop query

I need a little help understanding this piece of code, the result generated by the code is:
4 3 2 0
Why is 1 not being printed? Thanks in advance. here is the code:
n = 3
while n > 0:
print(n + 1, end = " ")
n -= 1
else:
print(n, end = "")
n=3 -> prints n+1 i.e. 4
n-1 = 2
n=2 -> prints 3
n-1 = 1
n=1 -> prints 2
n-1 = 0
n=0 -> goes to else statement as while condition is not satisfied. prints 0
It's because you print n+1 every time in the loop, then outside the loop you print n. If you print n+1 the output will be 4 3 2 1:
n = 3
while n > 0:
print(n + 1, end = " ")
n -= 1
else:
print(n + 1, end = "")

Get a number as many as the user inputed

I have a task to make an output program like this
if input : 5
then output : 2,6,10,14,18
Output must as many of total number as the input
My previous code like this
n = 5
num = 2
i = 1
while i <= n:
if num % 2 == 0:
if num % 4 != 0:
print(num)
i = i+1
num = num+1
But my output was just 2 numbers, i should get 5 numbers.
2,6
Can anyone help me?
Put the i+1 under the second if condition
if num % 4 != 0:
print(num)
i = i + 1
As you can see your output is following the Arithmetic progression
#### first number
a = 2
#### diffrence between the seq numbers
d = 4
#### number of terms in sequence
n = 5
### running loop n times
### a + (n-1) * d ( geeting the nth didgit in AP `enter code here`)
for i in range(1, n+1):
print(2 + (i-1)*d , end=',')

Loops with variables that count- trying to find out where this ends

I'm supposed to type the programs output. Input is 6, 3
target = int(input())
n = int(input())
while n <= target:
print(n * 2)
n += 1
My output - 6
My reasoning- 3 < 6 so the code will run through. 3 * 2 = 6 so 6 gets printed out. Then we do 6 += 1 which would be 7. 7 is not <= 6 so code shouldn't run through again.
The expected output:
6
8
10
12
n += 1 is shorthand for n = n + 1. The loop ends when n is greater than target.
Can someone please tell me where I am going wrong?
print(n * 2) does not affect the value of n. Since we did not put n * 2 in the value of n, the value of n changes only by n += 1.
target = int(input())
n = int(input())
while n <= target:
n = n * 2
print(n)
n += 1
This is the main difference between print and return statement.
Using return changes the flow of the program. Using print does not
def func(target,n):
while n <= target:
return (n * 2)
n += 1
target = int(input())
n = int(input())
print(func(target,n))
See here

Print the collatz sequence of a positive int, n, one value per line stoping at 1 using python

I've done:
def collatz(n):
seq = n
if n == 1:
n = n
while n > 1:
if n % 2 == 0:
n = n // 2
else:
n = 3 * n + 1
print(seq)
The corrct output for calling this function, while n = 10:
collatz(10)
10
5
16
8
4
2
1
But the only number printed is n itself.
The issue is that you are only printing seq which was set to n at start of the function, after the while loop has executed. Hence you only get the value printed once.
You should print the value inside the while loop as well as at start (for the first 10 print). Example -
def collatz(n):
print(n)
while n > 1:
if n % 2 == 0:
n = n // 2
else:
n = 3 * n + 1
print(n)
Demo -
>>> def collatz(n):
... print(n)
... while n > 1:
... if n % 2 == 0:
... n = n // 2
... else:
... n = 3 * n + 1
... print(n)
...
>>> collatz(10)
10
5
16
8
4
2
1
You need to print once for every step within your loop. Your print statement is outside your while loop hence it only fires once.
Additionally, you want to print the value that is changing n not seq which never chances in this function.
On that note, you don't even need seq as you never use it!
The two lines if n == 1: n = n don't do anything. Even if n==1, setting n to itself doesn't change the value.

Collatz sequence

How can I take an integer as input, of which the output will be the Collatz sequence following that number. This sequence is computed by the following rules:
if n is even, the next number is n/2
if n is odd, the next number is 3n + 1.
e.g. when starting with 11
11 34 17 52 26 13 40 20 10 5 16 8 4 2 1
This is my code now:
n = int(raw_input('insert a random number'))
while n > 1:
if n%2 == 0:
n_add = [n/2]
collatz = [] + n_add
else:
n_add2 = [3*n + 1]
collatz = [] + n_add2
print collatz
if I execute this and insert a number, nothing happens.
You are never changing the number n, so it will be the same each time round. You are also only printing if the number is odd. Also, square brackets [] indicate an array - I'm not sure what your goal is with this. I would probably rewrite it like this:
n = int(raw_input('insert a random number'))
while n > 1:
if n%2 == 0:
n = n/2
else:
n = 3*n + 1
print n
You might want to take some time to compare and contrast what I'm doing with your instructions - it is almost literally a word-for-word translation (except for the print
It is a little unclear from your code if you want to just print them out as they come out, or if you want to collect them all, and print them out at the end.
You should be modifying n each time, this will do what you want:
n = int(raw_input('insert a random number'))
while n > 1:
n = n / 2 if not n & 1 else 3 * n + 1 # if last bit is not set to 1(number is odd)
print n
## -- End pasted text --
insert a random number11
34
17
52
26
13
40
20
10
5
16
8
4
2
1
Using your own code to just print out each n:
n = int(raw_input('insert a random number'))
while n > 1:
if n % 2 == 0:
n = n / 2
else:
n = 3 * n + 1
print n
Or keep all in a list and print at the end:
all_seq = []
while n > 1:
if n % 2 == 0:
n = n / 2
else:
n = 3 * n + 1
all_seq.append(n)
print(all_seq)
def collatz(number):
while number != 1:
if number % 2 == 0:
number = number // 2
print(number)
elif number % 2 == 1:
number = number * 3 + 1
print(number)
try:
num = int(input('Please pick any whole number to see the Collatz Sequence in action.\n'))
collatz(num)
except ValueError:
print('Please use whole numbers only.')
I've also been working on it for a while now, and here's what I came up with:
def collatz (number):
while number != 1:
if number == 0:
break
elif number == 2:
break
elif number % 2 == 0:
number = number // 2
print (number)
elif number % 2 == 1:
number = 3 * number + 1
print (number)
if number == 0:
print ("This isn't a positive integer. It doesn't count")
elif number == 2:
print ("1")
print ("Done!")
elif number == 1:
print ("1")
print ("Done!")
try:
number = int(input("Please enter your number here and watch me do my magic: "))
except (ValueError, TypeError):
print ("Please enter positive integers only")
try:
collatz(number)
except (NameError):
print ("Can't perform operation without a valid input.")
Here is my Program:
def collatz(number):
if number % 2 == 0:
print(number//2)
return number // 2
elif number % 2 == 1:
print(3*number+1)
return 3*number+1
else:
print("Invalid number")
number = input("Please enter number: ")
while number != 1:
number = collatz(int(number))`
And the output of this program:
Please enter number: 12
6
3
10
5
16
8
4
2
1

Categories

Resources