Very Beginner Problem in Python While Loop - python

Why this While loop is not breaking or stopping
I have added some output screenshot
term = 0
i = 13
while True:
print i > 1
print "i = ",i
if i == 1:
term += 1
break
if i%2 == 0:
i = i / 2
term += 1
if i%2 != 0:
i = i * 3 + 1
term += 1
Output
I also tried This way too
term = 1
i = 13
while i > 1:
print i > 1
if i%2 == 0:
i = i / 2
term += 1
if i%2 != 0:
i = i * 3 + 1
term += 1

Use elif to make the cases mutually exclusive. You don't want multiple if statements to execute in the same loop iteration.
if i%2 == 0:
i = i / 2
term += 1
elif i%2 != 0:
i = i * 3 + 1
term += 1
Or just make it else since the second condition is redundant.
if i%2 == 0:
i = i / 2
term += 1
else:
i = i * 3 + 1
term += 1
The reason it oscillates between 2 and 4 as written is because 2 causes both if statements to run. 2 is even so the first one runs and halves i, making it 1. Now it's odd and the second one triggers, turning 1 into 4.
if i%2 == 0:
i = i / 2 # 2 --> 1
term += 1
if i%2 != 0:
i = i * 3 + 1 # 1 --> 4
term += 1
The next iteration 4 becomes 2.
if i%2 == 0:
i = i / 2 # 4 --> 2
term += 1
These two iterations repeat over and over in an endless cycle.

Let's say your i is 2. It is divisible by 2, so if i % 2 == 0 fires, and i becomes 1. And the code continues to execute, so now we are at if i % 2 != 0 line, and this condition is also true, because you just modified i and it's now 1. So i becomes 4.
Your modified second attempt, which prevents the second condition from being checked if the first one succeeds, is below:
term = 1
i = 13
while i > 1:
print(i > 1)
if i % 2 == 0:
i = i / 2
term += 1
elif i % 2 != 0:
i = i * 3 + 1
term += 1
Also notice that you actually don't need to check the second condition, as it is definitely true if the first one is not, so elif ... line can be replaced just with else:
You can also use continue keyword to stop the rest of the loop from executing if the first condition is true:
term = 1
i = 13
while i > 1:
print(i > 1)
if i % 2 == 0:
i = i / 2
term += 1
continue
if i % 2 != 0:
i = i * 3 + 1
term += 1
Your first attempt has exactly the same problem; fixing it I leave as an exercise for the reader :)
P.S. do not learn Python 2

The problem is:
if i%2 == 0:
i = i / 2
term += 1
if i%2 != 0:
i = i * 3 + 1
term += 1
The problem is that, if i % 2 == 0 is true, it will remain true until i = 1. Once i = 1, i % 2 != 0 executes and makes i = 4.

Related

debug they have same value but still get index out of range

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

Writing a "Chessboard" function in Python that prints out requested length of binary

I have an assignment for my Python course that I'm struggling with.
We are supposed to make a function that prints out binary as follows:
If the input is:
chessboard(3)
It should print out:
101
010
101
And so forth..
Its a "simple" program but I'm really new to coding.
I can produce a while loop that writes out the correct length and amount of lines but I'm struggling to produce variation between the lines.
This is what I have come up with so far:
def chessboard(n):
height = n
length = n
while height > 0:
while length > 0:
print("1", end="")
length -= 1
if length > 0:
print("0", end="")
length -= 1
height -= 1
if length == 0:
break
else:
print()
length = n
With the input:
chessboard(3)
It prints out:
101
101
101
Could someone help me figure out how I could start every other line with zero instead of one?
As I understand it, it is simple :
print("stackoverflow")
def chessboard(n):
finalSentence1 = ""
finalSentence2 = ""
for i in range(n): #we add 0 and 1 as much as we have n
if i%2 == 0: #
finalSentence1 += "1"
finalSentence2 += "0"
else:
finalSentence1 += "0"
finalSentence2 += "1"
for i in range(n): #we print as much as we have n
if i%2 == 0:
print(finalSentence1)
else:
print(finalSentence2)
chessboard(3)
returns :
stackoverflow
101
010
101
I am working on the same kind of assignment, but as we have only covered conditional statements and while loops so far, following the same logic, here is my solution:
def chessboard(size):
output_1 = ''
output_2 = ''
i = 1
j = 1
while j <= size:
while i <= size:
if i % 2 == 0:
output_1 += '1'
output_2 += '0'
i += 1
else:
output_1 += '0'
output_2 += '1'
i += 1
if j % 2 == 0:
print(output_1)
j += 1
else:
print(output_2)
j += 1
chessboard(5)
returns:
10101
01010
10101
01010
10101
def chessboard(x):
i = 0
while i < x:
if i % 2 == 0:
row = "10"*x
else:
row = "01"*x
print(row[0:x])
i += 1

Factorization: What went wrong with d? [duplicate]

This question already has answers here:
What is a debugger and how can it help me diagnose problems?
(2 answers)
Closed 2 years ago.
Consider:
Enter image description here
Input: 20
17
999997
Output: 2^2 * 5
17
757 * 1321
My code:
a = int(input())
# Find the factors first
for i in range(2, a+1):
s = 0
b = a
d = 0
# See if it is a prime number
if a%i == 0:
for x in range(1, i+1):
if a%x == 0:
d = d + x
if (d-1)/i == 1:
d = 0
print(i)
else:
s = 0
b = a
d = 0
continue
d = 0
# I will see how many prime numbers
while(b>0):
if (b/i)%1 == 0:
s = s + 1
b = b/i
else:
b = 0
if b == 1:
b = 0
print(s)
I will find the factors first, and then see if it is a prime number. If so, I will see how many prime numbers it is
if i input 12, it outputs 2 2
Enter link description here
I believe you need the output of the following.
import math
a = int(input())
while (a % 2 == 0):
print(2)
a = int(a/2)
while (a % 3 == 0):
print(3)
a = int(a/3)
for i in range(5, math.ceil(math.sqrt(a)), 6):
while (a % i == 0):
print(i)
a = int(a / i)
while (a % (i + 2) == 0):
print(i + 2)
a = int(a / (i + 2))
if (a > 3):
print(a)
This will give you the prime factors for a given number. As I can understand, it is what you are looking for.
a = int(input("Enter a number:"))
for i in range(2, a + 1):
if a % i != 0:
continue
# SETTING THE DEFAULT VALUES AT THE BEGINNING OF EVERY ITERATION OF THE LOOP
s = 0
b = a
d = 0
for x in range(1, i + 1):
if b % x == 0:
d = d + x
if (d - 1) / i == 1:
d = 0
print(i)
else:
# s = 0 # NO LONGER NEEDED, AS WE RESET THEM AT THE BEGINNING OF THE LOOP
# b = a
# d = 0
continue
while b > 0:
if (b / i) % 1 == 0:
s = s + 1
b = b / i
else:
b = 0
if b == 1:
b = 0
print(s)
a /= i**s # THIS LINE IS IMPORTANT
You were close. You forgot to set the default values at the beginning of every iteration of the loop, so they sometimes didn't have the right values ; and you should set a to a different value by dividing it by the factor you found (i**s, so i to the power of s).
As has been mentioned, your code also follows an odd coding style. I suggest you stop putting newlines between each statement, and start separating operators with spaces (example: range(3+5) is bad, range(3 + 5) is more readable)
You are using too many loops here and that's why you are getting too much confused. Here is the code which serve the same purpose (if I understand your problem correctly)
a = int(input("Enter a number: "))
i = 2
factors = []
while i <= a:
if (a%i) == 0:
factors.append(i)
a = a/i
else:
i = i + 1
print(factors)
here I am returning a list, if you want you can change the type accordingly.
Here are the inputs/outputs:
Enter a number: 17
[17]
Enter a number: 100
[2, 2, 5, 5]
Enter a number: 12
[2, 2, 3]

How to loop over modulus?

newbie here. I've been trying to find the least common multiple of the numbers 1 thru 10. My code so far
def smallest_multiple():
a = 0
while True:
a += 1
if a%1 == 0 and a%2 == 0 and a%3 == 0 and a%4 == 0 and a%5 == 0 and a%6 == 0 and a%7 == 0 and a%8 == 0 and a%9 == 0 and a%10 == 0:
return a
print(smallest_multiple())
My result is 2520, which seems to be correct. It is the smallest number that is divisible by the numbers 1 thru 10 without remainder. But is there a way to make the 5 line shorter (not that much modulus) by iterating over them? I've tried something like this
def smallest_multiple():
a = 0
while True:
a += 1
for i in range(1, 11):
if a % i == 0:
return a
print(smallest_multiple())
But that returns just 1, not 2520. Is there a way to make
if a%1 == 0 and a%2 == 0 and a%3 == 0 and a%4 == 0 and a%5 == 0 and a%6 == 0 and a%7 == 0 and a%8 == 0 and a%9 == 0 and a%10 == 0:
shorter?
You could change it to
if all([a%i == 0 for i in range(1,11)]):
All takes a list and returns True if everything in the list is True
This uses a simple list comprehension to go through numbers 1 through 10, and check if they are all True with a%i == 0
You could use all:
def smallest_multiple():
factors = [i for i in range(1, 11)]
a = 0
while True:
a += 1
if all([a % factor == 0 for factor in factors]):
return a
print(smallest_multiple())
Output
2520
UPDATE
As suggested by #PatrickHaugh you can avoid the creation of lists:
def smallest_multiple():
factors = range(1, 11)
a = 0
while True:
a += 1
if all(a % factor == 0 for factor in factors):
return a
print(smallest_multiple())
Output
2520
Speaking of one-liners ^^
Not an Infinity loop, though
import sys
next(i for i in xrange(1, sys.maxsize) if len([j for j in range(1,10) if i % j == 0]) == 9)
#=> 2520
And this is not the most efficient solution.

Am I using the modulo operator incorrectly?

If my understanding is correct, 5 % 5 should equal 0. However when i run this code:
endless = 0
while endless == 0:
n = int(input("Provide a number here: "))
count = 0
sum = 0
while count < n:
if 1+count % 3 == 0 | 1+count % 5 == 0:
sum += 1 + count
count += 1
if count >= n:
print(sum)
It always returns 0, which implies that 1+count % 3 or 1+count % 5 never equals 0. What did i miss?
EDIT:
I seem too have missed fundamental maths somehow.
Dont use bitwise OR, and use paranthesis (operator precedence)!
Try:
(1+count) % 3 == 0 or (1+count) % 5 == 0:
^ ^ ^^ ^ ^
The operator priority of % is the same as / and higher than +, that means:
1+count % 3 == 1 + (count % 3)
which can never be 0 since modulo returns a value between 0 and 2.

Categories