Python Forum

Full Version: I code a program to solve puzzle but i can't make it more dynamic.
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
# find the first number that is divided by 1 to 9 with 0 remainder
for i in range (10000):
	x = i % 3
	y = i % 4
	z = i % 7
	a = i % 5
	b = i % 6
	c = i % 8
	d = i % 9
	if x==y==z==a==b==c==d==0:
	 	print (i)
As it mention, i wanted to find numbers which are divided by 1 to 9 numbers with 0 remainders.
I tried to make it dynamic like instead of 1 to 9 what if i search numbers which are divided by 1 to 20 numbers.
I have already repeated lots of code line for 1 to 9 numbers and i don't want to do that for more numbers.
I tried to make a list of 1 to 20 numbers and with loop tried to iterate but failed.
Thanks in advance.
Maybe run two loops: one for the number to check, one for the division test.

max_check = 10000
dividends = [3, 4, 7, 5, 6, 8, 9]
for n in range(1,max_check):
    for dividend in dividends:
        if n % dividend:
            break
    else:
        print(f"{n} is evenly divided by {dividends}")
        break
else:
    print(f"No numbers found evenly divisible by {dividends} that are less than {max_check}")
There is no reason to test every value. If the result must be divisible for all numbers 1 through 9, the number will be divisible by 9. There is no reason to test 17 or 33 or 121.
def find_number(first, last):
    """Find first number that is divisible by all numbers in range first..last"""
    num = last
    while True:
        for divisor in range(first, last):
            if num % divisor != 0: # Failed test.  Try next num
                num += last
                break # break out of for loop
        else: # Gets called if for loop reaches end
            print(num)
            break;  # Break out of while loop

find_number(5, 13)
Great! Thank you so much.

The second nested 'for' loop with 'else' was the key that i missed.
And of course learned that i should use 0 as a boolean even i was working with arithmetic. It optimized code so well.
Thank you
you can use any()
for number in range (1, 10000):
    if not any(number % divisor for divisor in range(3, 10)):
        print(number)
        break # break out of loop early
else:
    print('no such number found')
note that probably you need to find more elegant (from math perspective) solution, not trying to brute-force it
Wow!
TIL any() function.
Thank you so much.