How do I rewrite the first code to use a while loop instead of the given for loop? The output of the two programs should be the same.
num = 500
for j in range(30, 100):
if j > 70:
num = num – 5
else:
num = num + 2
print(num)
print("program output is", num)
I have tried this but it does not work correctly:
num = 500
while j > 30 and j < 100:
if j > 70:
num = num – 5
else:
num = num + 2
print(num)
A for loop automatically updates the loop variable (j) in every iteration.
In a while loop however, you have to assign a new value to the variable yourself, otherwise the loop will never end.
A for loop like
for j in range(a, b):
# do something ...
is equivalent to this while loop:
j = a
while j < b:
# do something ...
j += 1
(Note that j += 1 means the same as j = j + 1.)
In your case, you need to write:
num = 500
j = 30
while j < 100:
if j > 70:
num = num – 5
else:
num = num + 2
print(num)
j += 1
print("program output is", num)
Related
When I debug my code, the value of the variables shows that they are equal to my limit condition but my while loop still works
I'm trying to stop my while loop by this limitation:
while (i + j) != len(fruits):
Even though (i+j) is equal to len(fruits), the loop still works, it doesn't break.
It should be broken when it meets my limitation.
My code is below:
from typing import List
class Solution:
def totalFruit(self, fruits: List[int]) -> int:
pointed = [0 for i in range(max(fruits) + 1)]
maX, count = 0, 0
count_type = 0
i, j = 0, 0
while (i + j) != len(fruits):
while count_type < 3:
if pointed[fruits[i + j]] == 0:
count_type += 1
if count_type < 3:
count += 1
pointed[fruits[i + j]] += 1
j += 1
elif count_type < 3 and pointed[fruits[i + j]] != 0:
pointed[fruits[i + j]] += 1
count += 1
j += 1
if count > maX: maX = count
if pointed[fruits[i]] == 1: count_type -= 2
pointed[fruits[i]] -= 1
count -= 1
i += 1
j-= 1
return maX
fruits = input()
fruits = [int(i) for i in fruits.split()]
obj = Solution()
print(obj.totalFruit(fruits))
when I debug:
enter image description here
It is constantly showing the error that ZeroDivisionError.
start= 11
end = 75
print("Prime numbers between ",start," and ",end," are : ")
for i in range (start, end+1):
if i > 1:
c = 2*i
for j in range(c):
if i//j == 0:
break
else:
print(i)
range(c) specifies that the loop should start at 0.
range(1,c) specifies that the loop should start at 1.
You get the error because in python, when you use for loop, it iterates from 0 to c, and since you're making a division (i // j), you're dividing by 0 in the first loop iteration.
Here is how it should be done:
start= 11
end = 75
print("Prime numbers between ",start," and ",end," are : ")
for i in range (start, end+1):
if i > 1:
c = 2*i
for j in range(1, c): #we're iterating now from 1 to c
if i//j == 0:
break
else:
print(i)
range(c) is 0 all the way to c
solution: range(1,c)
How can I display the first 25 integer prime numbers in the given interval? I can't find a way to limit it to 25 integer prime numbers.
minimum = 1000000000
maximum = 9999999999
print ("The first 25 10-digit prime numbers are:")
for num in range (minimum, maximum + 1):
if num > 1:
for i in range (2, num):
if (num % i) == 0:
break
else:
print(num)
you have to use a counter to store how many prime numbers you've found.
minimum = 1000000000
maximum = 9999999999
print ("The first 25 10-digit prime numbers are:")
counter = 0
for num in range (minimum, maximum + 1):
if counter == 25: break
if num > 3:
for i in range (2, int(num/2)): # for optimization
if (num % i) == 0:
break
else:
counter += 1
print(counter,num)
else:
counter += 1
print(counter,num)
here is the more optimized code with the hints in the comments:
import math
minimum = 1000000000
maximum = 9999999999
print ("The first 25 10-digit prime numbers are:")
counter = 0
for num in range (minimum, maximum + 1):
if counter == 25: break
if num > 3:
if (num % 2) != 0:
for i in range (3, math.ceil(math.sqrt(num)), 2):
if (num % i) == 0:
break
else:
counter += 1
print(counter,num)
else:
counter += 1
print(counter,num)
If nothing else, you could use a variable to keep track of how many you've printed and break from the outer loop when that hits 25.
Here's an example, added to your code.
minimum = 1000000000
maximum = 9999999999
printed = 0
print ("The first 25 10-digit prime numbers are:")
for num in range (minimum, maximum + 1):
if num > 1:
for i in range (2, num):
if (num % i) == 0:
break
else:
print(num)
printed+= 1
if printed >= 25:
break
You can try this.
from sympy import isprime
i=1
count = 0
while count < 25:
if isprime(i):
print(i)
count += 1
i += 1
There is no error in this code but its not printing the result. Here, what could be the problem.
# Using WHILE LOOP
num = int(input('Enter any positive integer: '))
sum1 = 0
i = 1
if num <= 0:
print('Invalid Number.')
else:
while(i < num):
if num % i == 0:
sum1 = sum1 + i
i = i + 1
if sum1 == num:
print(num, "is a perfect number")
else:
print(num, "is not a perfect number")
The problem lies here:
if num % i == 0. The == operator checks if the remainder of num/i is 0. If yes, then it updates i. But, if num % i is not 0, then it never adds anything to i. So, with each iteration, you are doing the same thing: num % i == 0.
You need to bring i = i + 1 outside if statement because i should increase regardless of whether the number is divisible or not.
Also, it is better to use i+=1. See difference between add and iadd
while(i < num):
if num % i == 0:
sum1 = sum1 + i
i = i + 1
You set if num % i == 0: i += 1, so if num % i != 0, i will not be updated. you just add else after if num % i == 0.
num = int(input('Enter any positive integer: '))
sum1 = 0
i = 1
if num <= 0:
print('Invalid Number.')
else:
while(i < num):
if num % i == 0:
sum1 = sum1 + i
i += + 1
else:
i+=1
if sum1 == num:
print(num, "is a perfect number")
else:
print(num, "is not a perfect number")
You set up an infinite while loop.
If i < num is true and num % i == 0 is false, the while loop will run infinitely. You can verify this by using a print statement inside the while loop. Like this:
while(i < num):
if num % i == 0:
sum1 = sum1 + i
i = i + 1
print('Passed the if statement')
If Passed the if statement gets printed multiple times then num % i == 0 is false and the if statement got ignored, and the while loop keeps running and ignoring the if statement again and again.
Once you figured out the problem, you could find out many solutions. I could suggest moving the incrementation of i out of the if statement so that whenever num % i == 0 results to false, i would be incremented and checked again. So the while loop could look like this:
while(i < num):
if num % i == 0:
sum1 = sum1 + i
i = i + 1
I am trying to get the lowest number that is divisible by all the numbers from 1 to 20.
The problem is in i%j == 0. It's giving me this error:
ZeroDivisionError: integer division or modulo by zero
even though I tried the same thing with a variable and a constant and it passes:
i % 2 == 0
My code:
i = 20
while True:
k = 0
for j in range(21):
if i % j == 0:
k += 1
if k == 21:
break
i+= 1
print(i)
Your current approach won't work for the time constraint - it'll just take too long to complete.
Try this code first and figure out what's the trick to save computing time.
primes = [2,3,5,7,11,13,17,19]
prod = 1
for p in primes:
n = 2
prod *= p
while (p**n < 21):
prod *= p
n += 1
print(prod) # 232_792_560
If you insist on using the for-loops to solve it. Here it's another alternative way:
i = 1
for k in (range(1, 21)):
if i % k > 0:
for j in range(1, 21):
if (i*j) % k == 0:
#print(i, j, k) # for debug only
i *= j
break
print(f' loop-way: {i} ') # 232792560