Python while loop query - python

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 = "")

Related

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

Collatz sequence including the user value in the output

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

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.

How to find the sum of all the multiples of 3 or 5 below 1000 in Python?

Not sure if I should've posted this on math.stackexchange instead, but it includes more programming so I posted it here.
The question seems really simple, but I've sat here for at least one hour now not figuring it out. I've tried different solutions, and read math formulas for it etc but it won't gives me the right answer when coding it! I made two different solutions for it, which both gives me the wrong answer. The first solution gives me 265334 while the second one gives me 232169. The answer is 233168, so the second solution is closer.
I should mention this is a question from Project Euler, the first one to be precise.
Here's my code. Any ideas what's wrong?
nums = [3, 5]
max = 999
result = 0
for num in nums:
for i in range(1,max):
if num*i < max:
result += num*i
print result
result = 0
for i in range(0,max):
if i%3 == 0 or i%5 == 0:
result += i
print result
You are overcomplicating things. You just need a list of numbers that are multiples of 3 or 5 which you can get easily with a list comprehension:
>>> [i for i in range(1000) if i % 3 == 0 or i % 5 == 0]
Then use sum to get the total:
>>> sum([i for i in range(1000) if i % 3 == 0 or i % 5 == 0])
<<< 233168
Or even better use a generator expression instead:
>>> sum(i for i in range(1000) if i % 3 == 0 or i % 5 == 0)
Or even better better (courtesy Exelian):
>>> sum(set(list(range(0, 1000, 3)) + list(range(0, 1000, 5))))
range(k,max) does not include max, so you're really checking up to and including 998 (while 999 is a multiple of 3). Use range(1,1000) instead.
I like this the most:
def divisibles(below, *divisors):
return (n for n in xrange(below) if 0 in (n % d for d in divisors))
print sum(divisibles(1000, 3, 5))
The problem with your first solution is that it double-counts multiples of 15 (because they are multiples of both 3 and 5).
The problem with your second solution is that it doesn't count 999 (a multiple of 3). Just set max = 1000 to fix this.
result = 0
for i in range(0,1000):
if (i % 3 == 0 or i % 5 == 0):
print i
result = result + i
print result
Output:
0
3
5
6
9
.
.
.
993
995
996
999
233168
max = 1000 # notice this here
result = 0
for i in range(0,max):
if i%3 == 0 or i%5 == 0:
result += i
print result
This works, but use 1000 for max, so it includes 999 too.
I know this was 3 months ago but as an experiment because I am new to python I decided to try and combine some of the other people answers and I came up with a method you can pass the max number to and the divisors as a list and it returns the sum:
def sum_of_divisors(below, divisors):
return sum((n for n in xrange(below) if 0 in (n % d for d in divisors)))
max = 1000
nums = [3, 5]
print sum_of_divisors(max, nums)
There are floor(999/3) multiples of 3, floor(999/5) multiples of 5, and floor(999/15) multiples of 15 under 1000.
For 3, these are: 3 + 6 + 9 + 12 +... + 999 = 3 * (1 + 2 + 3 + 4 +...+333)
= 3 * (333 * 334 / 2) because the sum of the integers from 1 to k is k*(k+1)/2.
Use the same logic for the sum of multiples of 5 and 15. This gives a constant time solution. Generalize this for arbitrary inputs.
I know this is from 6 years ago but I just thought id share a solution that found from a math formula that I thought was interesting as it removes the need to loop through all the numbers.
https://math.stackexchange.com/a/9305
def sum_of_two_multiples(nums, maxN):
"takes tuple returns multiples under maxN (max number - 1)"
n1, n2 = nums = nums[:2]
maxN -= 1
def k(maxN, kx):
n = int(maxN / kx)
return int(kx * (0.5 * n * (n+1)))
return sum([k(maxN, n) for n in nums]) - k(maxN, n1*n2)
Outputs the follows
print(sum_of_two_multiples((3,5), 10))
# 23
print(sum_of_two_multiples((3,5), 1000))
# 233168
print(sum_of_two_multiples((3,5), 10**12))
# 233333333333166658682880
I think only the last few lines from your code are important.
The or statement is the key statement in this code.
Also rater than setting the max value to 999, you should set it to 1000 so that it will cover all values.
Here is my code.
ans=0
for i in range(1,1000):
if(i%3==0 or i%5==0):
ans += i
print(ans)
input('press enter key to continue');#this line is only so that the screen stays until you press a key
t = int(input())
for a in range(t):
n = int(input().strip())
sum=0
for i in range(0,n):
if i%3==0 or i%5==0:
sum=sum+i
print(sum)
You can also use functional programming tools (filter):
def f(x):
return x % 3 == 0 or x % 5 == 0
filter(f, range(1,1000))
print(x)
Or use two lists with subtraction of multiples of 15 (which appears in both lists):
sum1 = []
for i in range(0,1000,3):
sum1.append(i)
sum2 = []
for n in range(0,1000,5):
sum2.append(n)
del sum2[::3] #delete every 3-rd element in list
print(sum((sum1)+(sum2)))
I like this solution but I guess it needs some improvements...
here is my solution:
for n in range(100):
if n % 5==0:
if n % 3==0:
print n, "Multiple of both 3 and 5" #if the number is a multiple of 5, is it a multiple of 3? if yes it has has both.
elif n % 5==0:
print n, "Multiple of 5"
elif n % 3==0:
print n, "Multiple of 3"
else:
print n "No multiples"
this is my solution
sum = 0
for i in range (1,1000):
if (i%3)==0 or (i%5)==0:
sum = sum + i
print(sum)
count = 0
for i in range(0,1000):
if i % 3 == 0 or i % 5 ==0:
count = count + i
print(count)
I know it was 7 years ago but I wanna share my solution to this problem.
x= set()
for i in range(1,1001):
if (i % 3) == 0:
x.add(i)
for j in range(1,1001):
if (j % 5) == 0:
x.add(j)
print(sum(x))
I had to do it in range 1 , 100
This is how I did it.
For i in range(1,100):
If i ÷ 3 == 0 and i ÷ 5 == 0:
print(i)
So with 1000 you just change the 100 to 1000
I had to find the multiples of 3 and 5 within 100 so if you need 3 or 5 just change it to or and it will give you more answers too. I'm just starting to learn so correct me if I'm wrong
Here is the code:
count = 1000
m = [3, 5, 3*5]
result = 0
Sum = 0
for j in m:
result = 0
for i in range(count):
if i*j < 1000:
result = result + i*j
elif i == (count - 1):
if j < 15:
Sum = result + Sum
elif j == 15:
Sum = Sum - result
print(Sum)
total = 0
maxrange = input("Enter the maximum range") #Get the maximum range from the keyboard
print("")
max = int(maxrange)
for i in range (0,max):
if i%3 == 0 or i%5 ==0:
total = total +i
print (total)

Categories

Resources