why does my code multiply 2 times instead of one - python

My code should verify if a number is even, if it is, it prints the number multiplied by 2, if it isn't, it should print the number multiplied by 3, but just doesn't work.
m = int(input())
for i in range(m):
n = int(input())
n*=2 if n%2==0 else n*3
print(n)
When i try this input:
3
1
2
3
It returns:
3
4
**27** <- ?

n *= 2 if n % 2 == 0 else n * 3
means
n *= (2 if n % 2 == 0 else n * 3)
which means
if n % 2 == 0:
n = n * 2
else:
n = n * n * 3
You meant to write
n *= 2 if n % 2 == 0 else 3

n*=2 if n%2==0 else n*3
Operator precedence.
This statement is interpreted as
n *= (2 if n%2==0 else n*3)
And for input 3, n%2==0 is not true, so the statement becomes
n *= 9
Which is 27.

Related

How can I reverse the value of the output?

Let's put int 5 as a sample input; in my code its expressed as this:
n = int(input())
for i in range(0, n):
n = n - 1
print(n**2)
I get an output as:
16
9
4
1
0
Instead I want to reverse the result to:
0
1
4
9
16
How do you go about solving this problem?
The following will reverse the output:
n = int(input())
for i in range(0,n):
print(i**2)
It will loop from 0 to your inputted n value, printing it's square at each iteration. This also negates the need for the n = n - 1 line.
Output:
0 ** 2
1 ** 2
.
.
.
n ** 2

Why does program count one extra value (cycle "while")?

Why the program count one more value? For example, I give him N = 50. It gives out:
1
4
9
16
25
36
49
64
Code:
N = int(input())
n = 1
k = 1
while n < N:
n = k ** 2
print(n)
k = k + 1
As explained, you're checking n then changing n, you want to change n then check before continuing.
You can use the walrus operator to assign n and check it's value all in the while statement. (requires Python 3.8+)
N = int(input())
n = 1
k = 1
while (n := k**2) < N:
print(n)
k += 1
This essentially assigns n to k**2 then checks if that result is <N before continuing.
1
4
9
16
25
36
49
Your program outputs 1 4 9 16 25 36 49 64 if your input is 50 because the `while`` loop is checking the value before you increase it. Once in the loop, you increase it, calculate the square and then print.
If you want it to terminate, try setting calculating n as the last step in the loop:
N = int(input())
n = 1
k = 1
while n < N:
print(n)
k = k + 1
n = k ** 2
You're checking whether you reached the limit before you calculate the square and print it. So you're checking the previous value of n, not the one that's about to be printed.
Move the check inside the loop.
while True:
n = k ** 2
if n >= N:
break
print(n)
k += 1
The n < N is evaluated after you've changed (and printed) n.
n = 1
k = 1
N=50
while 1:
n = k ** 2
if n > N:
break
print(n)
k = k + 1
To fix this, break before you print, moving the evaluation inside the loop rather than after the last update of n
1
4
9
16
25
36
49
With the condition of your code, for example, when n = 49, The condition is fulfilled because 49 < 50 therefore it will continue to process the value and print the new one. But once n = 64 which is > 50, it stops. This is a possible solution:
N = int(input())
n = 1
k = 1
while True:
if n >= N:
break
n = k ** 2
print(n)
k = k + 1
This will continuously execute the code but once the condition is met that n >= N, it will stop executing.

Get n times 1 in a number from n through mathmetical operations

How can we get n times 1 by using n. you can use only arithmetic operations not string functions. like
if n equals 1 output equals 1
if n equals 2 output equals 11
if n equals 3 output equals 111
if n equals 4 output equals 1111
any loop is not allowed
Try this:
def func(n):
if n==1:
return 1
return 10**n - 8*func(n-1)*10 - 9
test:
In [49]: func(10)
Out[49]: 1111111111
In [50]: func(3)
Out[50]: 111
In [51]: func(4)
Out[51]: 1111
You can do it this way. It is a recursive function:
def get_ones(n):
if (n == 0):
return 0
elif (n == 1):
return 1
return 10**(n-1) + get_ones(n-1)
print(get_ones(5))
The idea is that 111 = 1*(10^0) + 1*(10^1) + 1*(10^2)

How do I solve this: "Step forward and backward problem"?

The Problem Statement:
Sanjay is addicted to alcohol. Every night he drinks 4 bottles of vodka. He is going to his home. At first, he takes a step forward (which is 5m) but beacuse he is drunk, after his each step in forward direction, his body gets imbalanced and he takes a step backward (which is 3m).
Each step takes 1 min to complete. The distance from the bar to home is n metres. Calculate the time taken by him to reach his home.
Input Format:
single line containing one integer n.
Constraints:
0 <= n < 10^18
Output Format
single integer describing the time taken by him to reach home.
from math import *
n = int(input())
x = 0
m = 0
n = n % 1000000007
n = n % 1000000007
while x < n:
x += 5
m += 1
if x >= n:
break
x -= 3
m += 1
print(m)
But the time limit is exceeding in the last test case i.e. for n = 10^18 like numbers
Sample Input 0
11
Sample Output 0
7
The time taken is simply n/2 * 2
He advances 2 meters each "cycle" 5 forward 3 back
So we see how many "cycles" go into n (n / 2m) this will result
In the number of "cycles" taken to reach his house
Then we simply multiply by the amount of time taken per cycle (2 minutes)
to get the total time taken (t = n/2 * 2).
Try reducing the problem. Let time_taken(dist) be the function that tells us how long it takes to get home. Then the following hold:
time_taken(1) == 1
time_taken(2) == 1
time_taken(3) == 1
time_taken(4) == 1
time_taken(5) == 1
time_taken(6) == 1 * 2 + time_taken(4) (since 5-3 = 2)
== 1 * 2 + 1
time_taken(7) == 1 * 2 + time_taken(5)
== 1 * 2 + 1
time_taken(11) == 1 * 2 + time_taken(9)
== 2 * 2 + time_taken(7)
== 3 * 2 + time_taken(5)
== 3 * 2 + 1
time_taken(26) == 1 * 2 + time_taken(24)
== 2 * 2 + time_taken(22)
== ...
== 11 * 2 + time_taken(4)
== 11 * 2 + 1
if n > 5:
time_taken(n) == 1 * 2 + time_taken(n - 2)
== 2 * 2 + time_taken(n - 4)
== ...
== (formula here) * 2 + time_taken(4 or 5)

Compare and count same digits between two numbers

I'm looking to write a function that receives two four-digit numbers (m, n) that counts how many digits are the same between m and n, including duplicates and zeroes on the left. The thing is, my professor only taught us how to use loops, and don't want us to use lists and intersections, and I'm no able to do it.
For example, if m = 331 and n = 3, it should return 2 as the amount of equal digits, bit if n = 33, it should return 3 same digits.
>>> compare_digits(331, 3)
2
>>> compare_digits(332, 33)
3
Edit: This is the code I created before, and it counts same digits more than it should, but the central idea is the usage of % and // to read each digit, but it's not working...
def compare_digits(m, n):
read_ndigits = 0
same_digits = 0
while read_ndigits < 4: #number of digits
current_n = n % 10
read_mdigits = 0
while read_mdigits < 4:
current_m = m % 10
if current_n == current_m:
same_digits += 1
m //= 10
read_mdigits += 1
n //= 10
read_ndigits += 1
return same_digits
The output is very messy and I can't even recognize any pattern.
You can use collections.Counter() with set intersection:
from collections import Counter
def compare_digits(m, n):
m_counts = Counter(str(m).zfill(4))
n_counts = Counter(str(n).zfill(4))
return sum(min(m_counts[k], n_counts[k]) for k in m_counts.keys() & n_counts.keys())
print(compare_digits(331, 3)) # 2
print(compare_digits(332, 33)) # 3
print(compare_digits(3, 331)) # 2
Well, I decided to limit the number of digits to 4 and not be generic about it, so I wrote this and it worked perfectly:
def compare_digits(m, n):
a = m % 10
m //= 10
b = m % 10
m //= 10
c = m % 10
m //= 10
d = m % 10
read_ndigits = 0
same_digits = 0
while read_ndigits < 4:
current = n % 10
if current == a:
same_digits += 1
a = None
elif current == b:
same_digits += 1
b = None
elif current == c:
same_digits += 1
c = None
elif current == d:
same_digits += 1
d = None
n //= 10
read_ndigits += 1
return same_digits
Thank you all for your help :)

Categories