Double Break out of Nested Loops [duplicate] - python

This question already has answers here:
How can I break out of multiple loops?
(39 answers)
Closed 9 years ago.
I've seen many different ways to break out of two nested loops at once, but what is the quickest and simplest for my code?
primes = [2]
for a in range(3, 500, 2):
for b in range(2, int(a ** 0.5 + 0.5)):
if a % b != 0:
primes.append(a)
if a % b == 0:
[x for x in primes if x != a]
# double break

Put the loops in a function and use the return keyword:
def func(primes):
for a in range(3, 500, 2):
for b in range(2, int(a ** 0.5 + 0.5)):
if a % b != 0:
primes.append(a)
if a % b == 0:
[x for x in primes if x != a]
return
primes = [2]
func(primes)
This tends to be a good thing when it makes the programmer write modularized code.

Refactor the double loop as a function and use return to break out.

If you don't want to use a function you can use a variable. Here it is flag
primes = [2]
flag = 0
for a in range(3, 500, 2):
for b in range(2, int(a ** 0.5 + 0.5)):
if a % b != 0:
primes.append(a)
if a % b == 0:
[x for x in primes if x != a]
flag = 1
break
if flag:
break

Related

Converting List Comprehension with if all conditions to Loops in Python

I'm trying to convert a list comprehension I have as part of a course I'm doing to a for loop but keep bumping into errors/mistakes. I'm using an if all in the list comprehension which I can't work out what ordering/how to incorporate this into a for loop.
My code is:
def count_primes(num):
prime = [x for x in range(2,num) if all (x % y != 0 for y in range (2,x))]
return len(prime)
I've currently tried (but not working)
def count_primes(num):
primes = [2]
for x in range(3,num):
for y in range(2,x):
if x % y == 0:
break
else:
primes.append(x)
break
return len(primes)
This should do the trick
primes = [2]
for x in range(3, num):
all_check = True
for y in range(2, x):
if x % y == 0:
all_check = False
break
if all_check:
primes.append(x)
You weren't actually looping all the way through in your example to check the value.

Python check through two lists

I am relatively new to python and I came across a problem given below:
Given two lists a and b and an integer n, Check if
a) All elements of a is a factor of n
b) n is a factor of all elements of b
My code doesn't seem to be correct. Can someone please point out the mistake here.
return n if n%x==0 for x in a and y%n==0 for y in b
Any help is appreciated
Obvious one (you were missing all(...)):
all(n % x == 0 for x in a) and all(y % n == 0 for y in b)
Fun one:
0 == n % reduce(lcm, a) == reduce(gcd, b) % n
Requires Python 3.9, though.
Test code:
from itertools import product
from math import gcd, lcm
from functools import reduce
R = range(1, 11)
true = false = 0
for n in R:
for a in product(R, repeat=3):
for b in product(R, repeat=3):
expect = all(n % x == 0 for x in a) and all(y % n == 0 for y in b)
result = 0 == n % reduce(lcm, a) == reduce(gcd, b) % n
assert result == expect
true += expect
false += not expect
print(true, false)
=> No failures, same 2,723 true results and 9,997,277 false results.

Python: Print all numbers in range divisible by x and y

I'm trying to print all numbers in range 1-100 that are divisible by x and y (ie. 2 nad 3). For now i have
for x in range(0, 101):
if x % (2 and 3) == 0: print("2, 3: ", x)
elif x % 2 == 0: print("2: ", x)
elif x % 3 == 0: print("3: ", x)
But it is not accurate, any suggestions?
(2 and 3) evaluates to 3, that's why you never see the condition elif x % 3 == 0 being executed, notice there's no print("3: ", x) in the output of your code, because it'd already fallen into the condition if x % (2 and 3) == 0.
You should be better using if ((x % 2) == 0 and (x % 3) == 0) : print("2, 3: ", x) on that line.
The reason it is not accurate is by writing x % (2 and 3) python is interpreting (2 and 3).(https://docs.python.org/2/reference/expressions.html)
in python (2 and 3) would return 3 because both values are "truthy" and the AND comparison operator in python will return the last value when both items are True.
As per Rajesh Kumar's suggestion you could do
if x % 6 == 0: # ...
or
if x % 2 == 0 and x % 3 == 0: # More verbose...
If you have a number that hast to be dividable by number x and number y you can look at it like:
If some rest is left after a division with divisor x or divisor y, the currently considered number toDivide is not the number you are looking for, because you want numbers where neither of the devisions results in a rest.
x = 2
y = 3
for toDivide in range(1, 101):
# can't divide by x and y
if toDivide%x and toDivide%y:
continue
print((str(x)+", "+str(y) if not toDivide%x and not toDivide%y else (str(x) if not toDivide%x else str(y)))+":"+str(toDivide))
edit: found and resolved the code-error
In if x % (2 and 3) == 0 the value of (2 and 3) is evaluated first, you should first check divisibility by 2 then by 3. i.e.
if (x % 2) and (x % 3)
the two expressions in brackets return booleans that you finally evaluate using and.
corrected:
for x in range(0, 101):
if (x % 2) and (x % 3):
print("2, 3: ", x)
elif x % 2 == 0:
print("2: ", x)
elif x % 3 == 0:
print("3: ", x)

How to divide with a loop? (Python)

I am trying to write a function to determine if a number is prime. I have come up with
the following solution, however inelegant, but cannot figure out how to write it.
I want to do the following: take the number x and divide it by every number that is less than itself. If any solution equals zero, print 'Not prime.' If no solution equals zero, print 'Prime.'
In other words, I want the function to do the following:
x % (x - 1) =
x % (x - 2) =
x % (x - 3) =
x % (x - 4) =
etc...
Here is as far as I have been able to get:
def prime_num(x):
p = x - 1
p = p - 1
L = (x % (p))
while p > 0:
return L
Wikipedia provides one possible primality check in Python
def is_prime(n):
if n <= 3:
return n >= 2
if n % 2 == 0 or n % 3 == 0:
return False
for i in range(5, int(n ** 0.5) + 1, 6):
if n % i == 0 or n % (i + 2) == 0:
return False
return True

highest palindrome with 3 digit numbers in python

In problem 4 from http://projecteuler.net/ it says:
A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 * 99.
Find the largest palindrome made from the product of two 3-digit numbers.
I have this code here
def isPalindrome(num):
return str(num) == str(num)[::-1]
def largest(bot, top):
for x in range(top, bot, -1):
for y in range(top,bot, -1):
if isPalindrome(x*y):
return x*y
print largest(100,999)
It should find the largest palindrome, it spits out 580085 which I believe to be correct, but project euler doesn't think so, do I have something wrong here?
When I revered the for loop I didn't think it through, I removed the thing that checks for the biggest, silly me. Heres the working code
def isPalindrome(num):
return str(num) == str(num)[::-1]
def largest(bot, top):
z = 0
for x in range(top, bot, -1):
for y in range(top,bot, -1):
if isPalindrome(x*y):
if x*y > z:
z = x*y
return z
print largest(100,999)
it spits out 906609
Iterating in reverse doesn't find the largest x*y, it finds the palindrome with the largest x. There's a larger answer than 580085; it has a smaller x but a larger y.
This would more efficiently be written as:
from itertools import product
def is_palindrome(num):
return str(num) == str(num)[::-1]
multiples = ( (a, b) for a, b in product(xrange(100,999), repeat=2) if is_palindrome(a*b) )
print max(multiples, key=lambda (a,b): a*b)
# (913, 993)
You'll find itertools and generators very useful if you're doing Euler in Python.
Not the most efficient answer but I do like that it's compact enough to fit on one line.
print max(i*j for i in xrange(1,1000) for j in xrange(1,1000) if str(i*j) == str(i*j)[::-1])
Tried making it more efficient, while keeping it legible:
def is_palindrome(num):
return str(num) == str(num)[::-1]
def fn(n):
max_palindrome = 1
for x in range(n,1,-1):
for y in range(n,x-1,-1):
if is_palindrome(x*y) and x*y > max_palindrome:
max_palindrome = x*y
elif x * y < max_palindrome:
break
return max_palindrome
print fn(999)
Here I added two 'break' to improve the speed of this program.
def is_palindrome(num):
return str(num) == str(num)[::-1]
def max_palindrome(n):
max_palindrome = 1
for i in range(10**n-1,10**(n-1)-1,-1):
for j in range(10**n-1,i-1,-1):
if is_palindrome(i*j) and i*j > max_palindrome:
max_palindrome = i * j
break
elif i*j < max_palindrome:
break
return max_palindrome
n=int(raw_input())
print max_palindrome(n)
Simple:
def is_pallindrome(n):
s = str(n)
for n in xrange(1, len(s)/2 + 1):
if s[n-1] != s[-n]:
return False
return True
largest = 0
for j in xrange(100, 1000):
for k in xrange(j, 1000):
if is_pallindrome(j*k):
if (j*k) > largest: largest = j*k
print largest
Each time it doesnot have to start from 999 as it is already found earlier.Below is a simple method using string function to find largest palindrome using three digit number
def palindrome(y):
z=str(y)
w=z[::-1]
if (w==z):
return 0
elif (w!=z):
return 1
h=[]
a=999
for i in range (999,0,-1):
for j in range (a,0,-1):
l=palindrome(i*j)
if (l==0):
h=h+[i*j]
a-=1
print h
max=h[0]
for i in range(0,len(h)):
if (h[i] > max):
max= h[i]
print "largest palindrome using multiple of three digit number=%d"%max
Here is my code to solve this problem.
lst = []
for i in range(100,1000):
for n in range(2,i) :
lst.append (i* n)
lst.append(i*i)
lst2=[]
for i in lst:
if str(i) == str(i)[::-1]:
lst2.append(i)
print max(lst2)
Here is my Python code:
max_pal = 0
for i in range(100,999):
for j in range(100,999):
mult = i * j
if str(mult) == str(mult)[::-1]: #Check if the number is palindrome
if mult > max_pal:
max_pal = mult
print (max_pal)
def div(n):
for i in range(999,99,-1):
if n%i == 0:
x = n/i
if x % 1 == 0:
x = n//i
if len(str(x)) == 3:
print(i)
return True
return False
def palindrome():
ans = []
for x in range(100*100,999*999+1):
s = str(x)
s = int (s[::-1])
if x - s == 0:
ans.append(x)
for x in range(len(ans)):
y = ans.pop()
if div(y):
return y
print(palindrome())
580085 = 995 X 583, where 906609 = 993 X 913.
Found it only by applying brute-forcing from top to bottom!
Here is the function I made in python to check if the product of 3 digit number is a palindrome
Function:
def is_palindrome(x):
i = 0
result = True
while i < int(len(str(x))/2):
j = i+1
if str(x)[i] == str(x)[-(j)]:
result = True
else:
result = False
break
i = i + 1
return result
Main:
max_pal = 0
for i in range (100,999):
for j in range (100,999):
x = i * j
if (is_palindrome(x)):
if x > max_pal:
max_pal = x
print(max_pal)
Here is my solution for that:
lst1 = [x for x in range(1000)]
palindrome = []
def reverse(x):
a = str(x)[::-1]
return int(a)
x = 0
while x < len(lst1):
for y in range(1000):
z = lst1[x] * y
if z == reverse(z):
palindrome.append(z)
x += 1
duppal = set(palindrome)
sortpal = sorted(duppal)
total = sortpal[-1]
print(sortpal)
print('Largest palindrome: ' + str(total))
ReThink: efficiency and performance
def palindrome(n):
maxNumberWithNDigits = int('9' * n) #find the max number with n digits
product = maxNumberWithNDigits * maxNumberWithNDigits
#Since we are looking the max, stop on the first match
while True:
if str(product) == str(product)[::-1]: break;
product-=1
return product
start=time.time()
palindrome(3)
end=time.time()-start
palindrome...: 997799, 0.000138998031616 secs

Categories

Resources