Exiting a for loop - python

I know I'm missing something really simple here....but I cannot put my finger on it.
My code is trying to find divisors for the items in "numbers". When count reaches 10 I know I have found the first item in numbers which has 10 divisors...but I cannot see to exit the loop. It just keeps printing the items in numbers that have 10 or more divisors.
I thought it was the indent, but no. I then moved the counter inside the first for loop to see if that was it, and still nothing.
numbers = []
numbers = [i for i in range(1, 100)]
for i in range(1, 100):
test = sum(numbers[0:i])
count = 0
for j in range(1, test+1):
if test % j == 0:
count +=1
if count == 10:
print test
break
Suggestions?

break breaks only the inner-most for loop. You need to check for count == 10 after that as well:
for i in range(1, 100):
test = sum(numbers[0:i])
count = 0
for j in range(1, test+1):
if test % j == 0:
count +=1
if count == 10:
print test
break # Breaks for j but not for i
if count == 10:
break # Breaks for i

You have to exit both for loops. There are two options:
1) Put the code in a function and use return instead of break
def process_something():
for a in items:
for b in other_items:
if some_condition:
return
2) Use a helper variable to detect that the outer loop should break too:
for a in items:
done = False
for b in other_items:
if some_condition:
done = True
break
if done:
break
In your case, you can use if count == 10: instead of if done: but I don't like duplicating "application logic" (DRY principle), so count == 10 should be in code only once. But this is a matter of taste.
3) Wrap the outer loop in a try:/catch ...: and raise exception instead of break, but please don't do this.

Related

What is the most efficient way to see whether one item of a list is the sum of two other items in the list?

The script is supposed to take in three whole numbers from the user(who will input the numbers) and
determine whether one of them is divisible by ten.
determine whether two of the numbers can add up to the remaining number.
I believe the first one is done, but the second one puzzled me for a bit. first I did "trial and error" which worked but took up too many lines for my taste, then I tried this:
num_list = [num_1, num_2, num_3]
for i in num_list:
a = num_list.index(i)
if i % 10 == 0:
is_div_by_10 = True
if i == num_list[a-1] + num_list[a-2]:
addsUpToNumber = True
sure my phrasing isn't great, but I cant find a way to use lesser lines of code to get the same result.
Without changing too much, I think you were pretty close. I'd split it up into two separate loops though:
is_divisible = False
is_summable = False
num_list = [1, 2, 3]
for num in num_list:
if num % 10 == 0:
is_divisible = True
break # we don't need to check the other numbers.
for i, num in enumerate(num_list):
if num == num_list[i-1] + num_list[i-2]:
is_summable = True
break # we don't need to check the other numbers.
Alternatively:
is_divisible = any(num % 10 == 0 for num in num_list)
is_summable = any(num == num_list[i-1] + num_list[i-2] for i, num in enumerate(num_list))

How to skip a part of the code if a certain condition is met [duplicate]

This question already has answers here:
how to stop a for loop
(9 answers)
Closed 2 years ago.
As I am getting more and more comfortable with writing scripts in Python I wrote a script that finds prime numbers by trying to divide each number in a range in each number (kinda like Brute Force haha).
It works but I wanted to make the process faster and more efficient.
My code:
count = 0
for i in range(2,1000):
j = 2
while j < 1000:
if i%j==0:
count = count + 1
j = j + 1
if count == 1:
print(i)
count = 0
Explanation:
I check and store in count how many time does a number can be divided.
If by the end of the check count equals 1 that means that the number is prime (gets divided only by itself).
What I want now is to stop the process of checking how many times the number can get divided when the "count" variable exceed 1 (2 or more). How do I do that?
I wanted to do something with try and except but didn't know what...
Add an extra condition in here, and break out of the loop if the count is greater than one. Put this inside the while loop:
if i % j == 0:
count += 1
if count > 1:
break
As mentioned in the comments, it's cleaner to just use count as part of the loop condition. Here's an improved version:
for i in range(2, 1000):
j = 2
count = 0
while j <= i and count < 2:
if i % j == 0:
count += 1
j += 1
if count == 1:
print(i)
Of course, there are faster ways to find if a number is prime - in particular, in the inner loop you should not iterate until 1000, not even until i is reached, just until the sqrt(i), but I'll leave that as an improvement for you to make ;)
You can try using break. What break does is that it skips the remaining part of the loop and jumps to the statement following the loop.
count = 0
for i in range(2,1000):
j = 2
while j < 1000:
if i%j==0:
count = count + 1
break
j = j + 1 ### line 8
if count == 1:
print(i)
count = 0
In this code, when python encounters break, it skips the remaining part of the loop (that is, the remaining loop is not executed) and jumps straight to the next statement, which is line 8
Its all wrong, first you have to understand the algorithm to check for prime, basically a number is prime if it can't be fully divided by any number between 2 to (number//2)-1
Now in your question, you couldn't use break anywhere, bcz you first searching for all divisible and then checking prime, better I'm adding a sample code to your problem which is more feasible to find primes
Code
number = int(input("Enter A Number"))
for i in range(2,number//2+1): #See range arguments
if(number%i==0):
print("Not A Prime")
break #Break loop when condition reached

How to start a loop from where the user stop the loop?

How do I make a loop start from where it was left off? For example
def nextSquare():
i=0
while i<10:
k = (input("enter number"))
i=i+1
if k=='Done':
break;
else:
continue
If I stopped the loop at 5 the next time I want it to run from i = 6 instead of i = 0.
Thanks.
In order to store the iteration index, you can pass it as a parameter and return it back to the calling function.
For example:
def lol(i):
while(i < 10):
print(i) #unique value of i
k = int(input())
if k == 5:
print("Iteration skipped")
break
else:
print("Next iteration")
i += 1
return i
i = 0
i = lol(i)
i = lol(i)
i = lol(i)
i = lol(i)
In this example, I am calling lol four times. It stores the iteration index as i when it is called. It passes the same index so that it resumes the iteration from that index. If k != 5, then it increments the index, and returns it. Else, the operation is skipped.
ALSO
Looking at your example, I would say that there is a logical mistake.
k = (input("enter number"))
In this statement, you are asking for a number. However, you are comparing it to 'Done'. A logical mistake, I would say.

map(int, raw_input().split()) gets infinite input

Here's the code:
a = input()
b = map(int, raw_input().split())
maxcnt=1
for k in range(0,a):
cnt=1
j=k+1
while b[k]%b[j] == 0 or b[j]%b[k] == 0 :
cnt += 1
if maxcnt < cnt:
maxcnt = cnt
print maxcnt
While giving the list values, after giving the values separated with spaces, I press enter and it still keeps getting the input. What's the issue?
The statement b = map(int, raw_input().split()) is perfectly okay. The problem is that you are encountering an infinite loop in the later while part of your code. There should be some issue with the logic.
So, you are taking modulo of consecutive numbers in the list b ? So, an input like this:
b = [1,2,3,4]
will cause an infinite loop, since 1%2 == 0 or 2%1 ==0 => True. It is clearly an input dependent scenario.
Your code shows a while statement which does not change it's conditions while looping:
while (b[s] % b[j]) == 0 or
(b[j] % b[s]) == 0:
cnt += 1
As you can see here, cnt is not in the condition (b[s] % b[j]) == 0 or (b[j] % b[s]) == 0, therefore, it will just keep on incrementing cnt and will not stop.
What you see is an empty console (which you then thought meant it was asking for more input) which was actually just the while loop running continuously.

How to break while loop in an inner for loop in python?

while doesn't break when i>10 in for loop:
i = 0
x = 100
while i<=10:
for a in xrange(1, x+1):
print "ok"
i+=1
and it prints "ok" 100 times. How to break the while loop when i reaches 10 in for loop?
Until the inner loop "returns", the condition in the outer loop will never be re-examined. If you need this check to happen every time after i changes, do this instead:
while i<=10:
for a in xrange(1, x+1):
print "ok"
i+=1
if i > 10:
break
That break will only exit the inner loop, but since the outer loop condition will evaluate to False, it will exit that too.
i = 0
x = 100
def do_my_loops():
while i<=10:
for a in xrange(1, x+1):
print "ok"
i+=1
if time_to_break:
return
do_my_loops()
where time_to_break is the condition you're checking.
Or in general:
def loop_container():
outer_loop:
inner_loop:
if done:
return
loop_container()
The problem is that the outer loop's condition won't be checked until the inner loop finishes - and at this point i is already 100. From my perspective, the correct way to write this and get the desired output would be to put a guard inside the inner loop and break it when i reaches 10.
for a in xrange(1, x+1):
if i < 10:
print "ok"
i+=1
else:
break
If there is some other reason why you want to break an outer loop while you're inside the inner loop, maybe you should let us in on the details to better understand it.
What about this?
x = True
while x:
for i in range(20):
if i>5:
x = False
break
else:
print(i)
booked = False
for i in range(100, 200):
if booked:
break
while True:
for x in range(1, 3):
if booked:
break
result = 0
if result == 1:
booked = True
break
continue

Categories

Resources