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
Related
Find the sum of all multiples of n below m
Keep in Mind n and m are natural numbers (positive integers) m is
excluded from the multiples
sumMul(2, 9) ==> 2 + 4 + 6 + 8 = 20
sumMul(3, 13) ==> 3 + 6 + 9 + 12 = 30
sumMul(4, -7) ==> "INVALID"
I did sum of list using range(n, m, n) using n as step.
I also tried modulus to avoid range 3 args error.
I can pass many tests but cannot pass all of them.
I have tried lots of logic but to no avail. What I am doing wrong?
CODEWARS: https://www.codewars.com/kata/57241e0f440cd279b5000829/train/python
MY CODE:
def sum_mul(n, m):
my_list = [number for number in range(n, m) if number % n == 0]
sum_list = sum(my_list)
if sum_list >= 1:
return sum_list
elif n == 0 and m == 0:
return 'INVALID'
elif n == m:
return n - m
elif n > m:
return 'INVALID'
Your code fails if n == 0 as then the number % n checks in the list comprehension fail, so you should check that before trying to compute the sum. Also, you could use a range with step and just do sum(range(n, m, n)). However, both ways might be too slow for some test cases with very large m.
You can do this in O(1) with the following observations:
there are (m-1) // n multiples of n below m
the sum of natural numbers from 1 to n is n*(n+1)//2
Combine those two to get the result.
Example for sumMul(3, 13) ==> 3 + 6 + 9 + 12 = 30:
(13-1) // 3 == 4 so we know there are 4 multiples of 3 below 13
those are 3 + 6 + 9 + 12 == 3 * (1 + 2 + 3 + 4)
with (2) we know 1 + 2 + 3 + 4 == 4*5//2 == 10
so the result is 10 * 3 == 30
Putting that into code and handling the special cases is left as an exercise to the interested reader.
You have one main problem, that is you should prevent the situation when n==0 and you divide it in your list comprehension. It will raise zero division error. so you should check before the validation that n is not equal to zero.
Second thing is that you need to check whether n or m are negatives, as the exercise declared both n and m should be positives.
def sum_mul(n, m):
if n==0:
return 'INVALID'
my_list = [number for number in range(n, m) if number % n == 0]
sum_list = sum(my_list)
if sum_list >= 1:
return sum_list
elif n < 0 and m <= 0:
return 'INVALID'
elif n == m:
return n - m
elif n > m:
return 'INVALID'
You can just compute that result mathematically using integer divisions:
def sum_mul(n, m):
if n<1 or n>m: return "INVALID"
return m//n*(m//n+1)//2*n
First you get the number of multiple of n in m (which is merely dividing m by n ignoring the remainder) : m//n
Multiples of n will be nx1, nx2, nx3, ... up to the number of multiples. Factorizing the sum of those by n we get: n(1+2+3+ ... m//n).
The sum of numbers from 1 up to a given number x is obtained by x(x+1)/2. In this case x is the number of multiples m//n
Putting it all together we get n * x * (x+1) /2 where x is m//n, so:
n * (m//n) * (m // n + 1) // 2
You should comprove all cases before call sum function.
Like this:
def sum_mul(n, m):
if n == 0 or m == 0:
return 'INVALID'
if n == m:
return n - m
if n<0 or m<0:
return 'INVALID'
my_list = [number for number in range(n, m) if number % n == 0]
return sum(my_list)
In fact, you dont't need to create if elif structure because you are using returns, so next instruction after return not executed.
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
How do I make a code that follows this? 1⋅2+2⋅3+3⋅4+…+(n−1)⋅n
For example, if n=5, the answer is 1⋅2+2⋅3+3⋅4+4⋅5=40.
n cannot be less than or equal to two or more or equal to 1000
This is my code for now but it doesn't work.
n = int(input())
if n>= 2 and n<=1000:
sum = 0;
numbers = range(1, n+1)
for amount in numbers:
if (amount % 2 == 1):
sum *= amount
else:
sum += amount
print(sum)
For every number between 1 and n-1 (inclusive), you need to multiply it by the following number, and then sum them all. The easiest way to represent this is with a comprehension expression over a range call:
result = sum(i * (i + 1) for i in range(1, n))
You need to reproduce exactly the scheme you give
for each number, mulitply it with itself-1, and sum that
def compute(n):
if 2 <= n <= 1000:
total = 0
for amount in range(1, n + 1):
total += amount * (amount - 1)
print(total)
But that's the same as multiplying each with itself+1, if you change the bound to get one step less
for amount in range(1,n):
total += amount * (amount + 1)
Then you can use builtin methos sum and a generator syntax
def compute(n):
if 2 <= n <= 1000:
total = sum(nb * (nb + 1) for nb in range(1,n))
print(total)
If you try to approach it mathematically, you can have the answer in a single expression.
Dry run your code. You will see that for n = 5, you are doing as follows:
Num of Iterations = 6 (1 -> 5+1)
Iteration 1
sum = 0 + 1 = 1
Iteration 2
sum = 1 * 2 = 2
Iteration 3
sum = 2 + 3 = 5
Iteration 4
sum = 5 * 4 = 20
Iteration 5
sum = 20 + 5 = 25
Iteration 6
sum = 25 * 6 = 150
In this, you are completely disregarding the BODMAS/PEMDAS rule of multiplication over addition in the process of regenerating and calculating the series
What you need to do is
Iteration 1:
sum = 0 + 2 * 1 = 2
Iteration 2:
sum = 2 + 3 * 2 = 8
Iteration 3:
Sum = 8 + 4*3 = 20
Iteration 4:
Sum = 20 + 5*4 = 40
Here, We have broken the step as follows:
For each iteration, take the product of (n) and (n-1) and add it to the previous value
Also note that in the process, we are first multiplying and then adding. ( respecting BODMAS/PEMDAS rule )
So, you need to go from n = 2 to n = 5 and on each iteration you need to do (n-1)*(n)
As mentioned earlier, the loop is as follows:
## Checks for n if any
sum = 0
for i in range(2, n):
sum = sum + (i-1)*i
print(sum)
I have to calculate the sum of all the multiples of 3 and 5 (including themselves) in a range of a given N number (N excluded). I created a python code and it works with N = 10 but doesn't work for N = 100. I don't understand why.
This is the code:
#!/bin/python3
import sys
def multiples_sum(n):
sum1 = 0
for i in range(n):
if i % 3 == 0:
sum1 = sum1 + i
if i % 5 == 0:
sum1 = sum1 + i
return sum1
t = int(input().strip())
for a0 in range(t):
n = int(input().strip())
print(multiples_sum(n))
you are counting the multiples of 15 (= 3 * 5) twice.
your code should be
for i in range(n):
if i % 3 == 0:
sum1 += i
elif i % 5 == 0:
sum1 += i
note the elif instead of if.
alternatively:
for i in range(n):
if i % 3 == 0 or i % 5 == 0:
sum1 += i
or directly (as DeepSpace suggests in the comments)
sum1 = sum(i for i in range(n) if 0 in {i % 3, i % 5})
note that there is no need for looping at all: knowing that the sum of the integers from 1 to (and including) n is
def sum_to(n):
return ((n+1)*n)//2
you can get your number from:
sum1 = 5 * sum_to((n-1)//5) + 3 * sum_to((n-1)//3) - 15 * sum_to((n-1)//15)
(that could be generalized and made somewhat prettier... but i'm sure you get the idea in this form).
EDIT:
In the meantime I saw #DeepSpace's solution in the comments, particularly the one with the if 0 in {i % 3, i % 5})-check - which I definitely admire; this is really smart!
I think I'd go this way, if you're interested in a different approach:
N = 100
sum(set(list(range(0, N, 3)) + list(range(0, N, 5))))
# 2318
Because 10 is less than 15, which is the least common multiple of 3 and 5.
You need to treat the particular case of 15.
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.