Why doesn't "break" stop this for loop? - python-3.x

for i in range(999*999):
if ispalindrome(999*999-i)==True and isprime(999*999-i) == False:
factors = listfactors(999*999-i)
for j in range(len(factors)):
if len(str(factors[j])) == 3 and len(str(int((999*999-i)/factors[j])))==3:
print(999*999-i)
quit()
This is my code. I want to check whether these conditions are true and then stop once I've found the first one, but it prints all of the numbers that fit the conditions in the console. My thinking was that it should stop when it's got the first number
EDIT: I tried using quit() instead of break, but this still doesn't work, which I don't understand. I did try it with two break statements, but that didn't work. I wonder whether I got the indentation wrong.

In order to quit a double loop, use a function instead and return from the function. A break only works for the innermost loop.
Exampe:
def whatever():
for i in range(999 * 999):
if ispalindrome(999 * 999 - i) and not isprime(999 * 999 - i):
factors = listfactors(999 * 999 - i)
for j in factors:
if len(str(j)) == 3 and len(str(int((999 * 999 - i) / j))) == 3:
return 999*999-i
print(whatever())

the function break will only go out of 1 level. An easier way to do what you want is to make it a function as stated by Hubert. If you really do not want to use a function, you could create another variable continue and set it to True and check if it is not True at every level and if so break, then set it to False once it finds the answer, this way when it is found it will exit each loop as continue is no longer True.
Hope it helps.
P.S. You should mark a tick by Hubert's answer since it is solving your problem.

Related

A Python code of a program that reads an integer, and prints the integer it is a multiple of either 2 or 5 but not both

A Python code of a program that reads an integer, and prints the integer is a multiple of either 2 or 5 but not both.
First off, SO is not a forum to ask people to solve your homework without first putting effort yourself. you could have written a simple naive solution with if-else statements and posted that in your question, asking for a better way to do this.
That being said, I'm still adding my approach because I think you should know that a beautiful and simple way would be to just use an XOR check:
n = int(input("Input a number: "))
answer = True if (n % 2 == 0) != (n % 5 == 0) else False
print(answer)
I'm assuming the user will always input a value that can be cast as an integer. You can take care of the error handling process. Once the number has been read, I do a simple XOR check to return True if the number is only divisible by either 2 or 5 but not both, and False in all other cases. This works because bool(a)!=bool(b) gives True only when bool(a) and bool(b) evaluate to different things.
Demonstration:
def check(n):
return (n%2 == 0) != (n%5 ==0)
print(check(2)) # Out: True
print(check(5)) # Out: True
print(check(10)) # Out: False
print(check(3)) # Out: False

How to replace a variable with nothing if certain conditions are met using a if statement (Python 3)

I'm trying to make a completing the square calculator. I replicated some of the lengthy code to show where im getting my issue:
a=1
if (a == 1):
print ()
print ("bcdf" + str(a))
Output: bcdf1
In this case, I want it to output bcdf
I genuinely looked all over the place trying to find an answer to this.
I'm not sure if I understand correctly the problem, but probably this is the solution you're searching for:
a = 1
if (a == 1):
print("bcdf")
else:
print("bcdf" + str(a))
You can find more information regarding if..else statements in the documentation.
Since a is a number you could set it to None to reset its value. Also, if you are using Python>3.6 you have f-strings to print what you want nicely in one line:
a = 1
if a == 1:
a = None
print(f"bcdf{a if a is not None else ''}")
This says to evaluate to an empty string if a is None.
If you do not have f-strings you can do it the old way with format, it does exactly the same thing:
a = 1
if a == 1:
a = None
print("bcdf{}".format(a if a is not None else ""))

How to break 1 cycle in a for-loop without stopping the whole loop?

I am programming a program that will make a list of all numbers from 1 to 200 that:
are not divisible by 7 or 11
do not contain the digit 7 or 11 in their number.
I want to use the pass function so when the condition is not met, it will continue with the next number. I don't really know how to do it. The pass function is probably the wrong one. I know the break function does also not work because it will end the whole loop.
Please explain me how to make this program work on this way. There are probably plenty other ways to calculate this, but the point is that i want to understand how to use the for loops better :).
n = 200 #all digits till and including 200
numbers = [] #empty list for accumulation values
for i in range(1,(n+1)):
if i%7 == 0 or i%11 == 0: #if one of these 3 conditions are met
pass #it should continue to the next number (i)
if str(7) in str(i):
pass
if str(11) in str(i):
pass
numbers.append(i)
print(numbers)
print(sum(numbers)) # for my assignment i need to sum the list
use continue in place of pass.
pass does nothing
continue skips to the next loop
so i had to use continue in my example.

Is there any trick or method to count recursion calls on paper(with larger numbers)?

Hi everyone it is my first question here! I would like to ask about some tricks how can we count recursive calls in a paper, without using computer? The language in example is Python 3.xx. In this example if I get larger number like 11 how can I count number of stars in this example "easily"?
def func(numb):
print('*', end='')
if numb <= 1:
return False
for i in range(numb):
if func(i) and numb%i == 0:
return False
return True
func(11)
I found too uneffective, to write everything as the program running, especially if it is on a test, too time consuming.
Thank you for helping!
There are several methods of counting recursive calls; this one basically is iteration, I guess, you do
T(n) + T(n - 1) + T(n - 2) ... // in which T(n) is the complexity of the recursive call
Substitution will lead to the same result and master theorem is useless here, so that's the best you can do, and since every one of your calls is linear this ends up being (worst case scenario, of course):
n + (n - 1) + (n - 2) ... + 2 // since you end at 1
But you can actually reduce your recursive calls if you do this:
if numb%i == 0 and func(i): // you won't reach func(i) if num % i != 0
Please check these function.
def recursion(numb):
if(numb<1):
return False
print('*'),
numb-=1
recursion(numb)
recursion(11)
print('')
def recursion1(numb):
if(numb<1):
return False
for i in range(numb):
print('*'),
print('')
numb-=1
recursion1(numb)
recursion1(11)

changing the value of iterator of for loop at certain condition in python

Hello friend while learning python it came into my mind that is there any way by which we can directly jump to a particular value of iterator without iterating fro example
a=range(1.10) or (1,2,3,4,5,6,7,8,9)
for i in a
print ("value of i:",i)
if (certain condition)
#this condition will make iterator to directly jump on certain value of
#loop here say if currently i=2 and after this it will directly jump the
#the iteration value of i=8 bypassing the iterations from 3 to 7 and
#saving the cycles of CPU)
There is a solution, however it involves complicating your code somewhat.
It does not require an if function however it does require both while and try loops.
If you wish to change the numbers skipped then you simply change the for _ in range() statement.
This is the code:
a = [1,2,3,4,5,6,7,8,9,10]
at = iter(a)
while True:
try:
a_next = next(at)
print(a_next)
if a_next == 3:
for _ in range(4, 8):
a_next = next(at)
a_next = str(a_next)
print(a_next)
except StopIteration:
break
The iterator interface is based on the next method. Multiple next calls are necessary to advance in the iteration for more that one element. There is no shortcut.
If you iterate over sequences only, you may abandon the interator and write an old-fashioned C-like code that allows you to move the index:
a = [1,2,3,4,5,6,7,8,9,10]
a_len = len(a)
i = 0
while i < a_len:
print(a[i])
if i == 2:
i = 8
continue
i += 1

Resources