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.
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 months ago.
Improve this question
function should return the sum of all the divisors of a number, without including it. A divisor is a number that divides into another without a remainder. so for this I have written below function in python.
def sum_divisors(n):
k = 1
sum = 0
while k < n :
if n % int(k) == 0:
print(k)
sum = sum + int(k)
k += 1
k = k + 1
# Return the sum of all divisors of n, not including n
return sum
print(sum_divisors(0)) # 0
print(sum_divisors(3)) # Should sum of 1 # total 1
print(sum_divisors(36))
print("----------") # Should sum of 1+2+3+4+6+9+12+18 # total 55
print(sum_divisors(102))
print("----------") # Should be sum of 2+3+6+17+34+51 # total 114
But I am getting o/p as --> 0 , 1 49, 112 respectively for above function.
after analysis I found that - value of "k" is not getting incremented inside if block as 2 and 4.
K value is comming as below for above four functioned when getting called-->
0
----------
1
1 --> it should be 2
----------
1 --> after 1 next should come as 2 , as 36 is divisible by 2
3 --> after 3 next should come as 4 , as 36 is divisible by 4, but it is missing
6
9
12
18
49
----------
1 --> after 1 next should come as 2 , as 102 is divisible by 2
3
6
17
34
51
112
so can anyone please tell what is going wrong above. If possible you can suggest any alternate method to optimize above program.
You're incrementing k twice, once conditionally inside the if, once unconditionally outside it, so you can never find adjacent factors. Remove the one inside the if.
Better, just replace it with a for+range loop and stop managing k manually:
def sum_divisors(n):
sum = 0
for k in range(1, n):
if n % k == 0: # No need to int-ify k, it's always an int anyway
print(k)
sum += k # Can use += to avoid repetition, and k is an int already
# Return the sum of all divisors of n, not including n
return sum
If the print is purely for debugging and can be removed, this simplifies to a one-liner, with the optimized sum function + a generator expression:
def sum_divisors(n):
return sum(k for k in range(1, n) if n % k == 0)
you only have to comment the first addition of k :
it is as if you're incrementing it twice so you're jumping on numbers to test on.
def sum_divisors(n):
k = 1
sum = 0
while k < n :
if n % int(k) == 0:
# print(k)
sum = sum + int(k)
# k += 1
k = k + 1
# Return the sum of all divisors of n, not including n
return sum
print(sum_divisors(0)) # 0
print(sum_divisors(3)) # Should sum of 1 # total 1
print(sum_divisors(36))
print("----------") # Should sum of 1+2+3+4+6+9+12+18 # total 55
print(sum_divisors(102))
print("----------") # Should be sum of 2+3+6+17+34+51 # total 114
You have both k += 1 and k = k + 1 inside your loop, so that means that you add 2 for every iteration.
This code:
def sum_divisors(n):
k = 1
sum = 0
while k < n :
if n % int(k) == 0:
print(k)
sum = sum + int(k)
k = k + 1
# Return the sum of all divisors of n, not including n
return sum
print(sum_divisors(0)) # 0
print("----------")
print(sum_divisors(3)) # Should sum of 1 # total 1
print("----------")
print(sum_divisors(36))
print("----------") # Should sum of 1+2+3+4+6+9+12+18 # total 55
print(sum_divisors(102))
print("----------") # Should be sum of 2+3+6+17+34+51 # total 114
Gives this output:
0
----------
1
1
----------
1
2
3
4
6
9
12
18
55
----------
1
2
3
6
17
34
51
114
----------
You have to use "else" for k = k + 1
def sum_divisors(n):
k = 1
sum = 0
print(n)
while k < n :
if n % k == 0:
print(k)
sum = sum + k
k += 1
else:
k = k + 1
return sum
The task is: introduced 2 numbers N(0-10000) - number of components, Q - number of requests. Then inputs N numbers of tests results. And then input Q numbers. Need to summarize an amount of all numbers in N which are less then Q
Sample Input:
10 3
2 6 8 4 5 1 9 0 3 7
3
8
0
Sample Output:
6
36
0
Made this task. If i m doing it local, with other random numbers it works. When i m trying to upload it on the stepik task I`ve got timelimit exceeded.
N, Q = input().split()
N = int(N)
Q = int(Q)
problems = input().split()
numMis = [0]*Q
MB = [0]*Q
if N > 0 or Q > 0:
for i in range(Q):
numMis[i] = int(input())
for i in range(Q):
for j in range(N):
if numMis[i] >= int(problems[j]):
MB[i] += int(problems[j])
for i in range(Q):
print(MB[i])
else:
print('0')
I am new to Python and Stackoverflow in general, so sorry if my formatting sucks and i'm not good at enlish.But i have a problem with this code.
print('Displays prime numbers from 1 to N.')
n = int(input('Please enter a value of n: '))
for n in range(1, n + 1):
if n >= 1:
for i in range(2, n):
if (n % i) == 0:
break
else:
print('They are',n,end=' ')
The result of the code when ran comes out looking like this:
Displays prime numbers from 1 to N.
Please enter a value of n:40
They are 1 They are 2 They are 3 They are 5 They are 7 They are 11 They are 13 They are 17 They are 19 They are 23 They are 29 They are 31 They are 37
but i want it like this:
Displays prime numbers from 1 to N.
Please enter a value of n:40
They are 1 2 3 5 7 11 13 17 19 23 29 31 37
If you're completely determined not to use the print function more than once inside the loop, you could set a flag to determine whether to print the first two words. Like so:
print('Displays prime numbers from 1 to N.')
n = int(input('Please enter a value of n: '))
first = 'They are '
for n in range(1, n + 1):
if n >= 1:
for i in range(2, n):
if (n % i) == 0:
break
else:
print(first + str(n), end=' ')
if len(first) > 0:
first = ''
The following solution may help you
print('Displays prime numbers from 1 to N.')
n = int(input('Please enter a value of n: '))
num = [] # Create empty list
for n in range(1, n + 1):
if n >= 1:
for i in range(2, n):
if (n % i) == 0:
break
else:
num.append(n)
# Write the print statement outside of the loop and use .join() function and for loop
#to print each element of the list look like the output you have posted
#
print('They are'," ".join(str(x) for x in num))
Output:
Displays prime numbers from 1 to N.
Please enter a value of n: 40
They are 1 2 3 5 7 11 13 17 19 23 29 31 37
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 :)
So what I am trying to do is to find count of alternating numbers such that it alternates with -ve and positive sign
for eg: 1 -2 3 -4 would get me 4 3 2 1 as from 1 to -4 including the two numbers there are 4 numbers.
Simillarly for 1 1 -3 2 would get me 1 3 2 1
Now I have the code but I cannot optimise it and it returns me a time limit exceeded error even though it works for moderate input stream.
j=0
count=0
length=(raw_input())
st=map(int,raw_input().split())
while j+1 < len(st):
k=j+1
count=0
temp=j
while k<len(st) and ((st[k]<0 and st[j]>0) or (st[k]>0 and st[j]<0)):
count+=1
k+=1
j+=1
print count+1,
j=temp+1
print 1
Try using for loops instead of while loops as that avoids you some variable assignments:
st = map(int, raw_input().split())
length = len(st)-1
for i in range(length):
count = 1
for j in range(i, length):
if (st[j]<0 and st[j+1]>0) or (st[j+1]<0 and st[j]>0):
count += 1
else:
break
print(count)
print(1)
This will give:
<< 1 -2 3 4
>> 4
>> 3
>> 2
>> 1
<< 1 1 -3 2
>> 1
>> 3
>> 2
>> 1
It may also be a bit faster if you extract the numbers from the list once instead of twice:
st = map(int, raw_input().split())
length = len(st)-1
for i in range(length):
count = 1
for j in range(i, length):
first, second = st[j:j+2]
if (first<0 and second>0) or (first>0 and second<0):
count += 1
else:
break
print(count)
print(1)
The last thing I would try is checking that they sigs are different with a single comparisson but I do not really expect this to be faster:
st = map(int, raw_input().split())
length = len(st)-1
for i in range(length):
count = 1
for j in range(i, length):
product = st[j] * st[j+1]
if product != abs(product):
count += 1
else:
break
print(count)
print(1)