I was working through a programming challenge I found on Reddit and it seemed easy enough:
Find all numbers less than \$10^n\$ where the number and its reverse (the reverse of \$123\$ is \$321\$) are both divisible by \$7\$ and then sum them all together.
def challenge_229(power): numbers = [] for x in range(0, 10**power, 7): if x % 7 == 0 and int(str(x)[::-1]) % 7 == 0: numbers.append(x) print(sum(numbers)) challenge_229(3) # <-- Change this value.
Which works great for the example input of \$3\$, which results in the output \$10,787\$. However, it does not scale very well at all. To reach the goal requiring 10^11 will not be practical.
I figured the worst part of my program was the
int(str(x)[::-1]) % 7 == 0
bit I used to reverse the number, but I’m unsure how I would go about making it more efficient. Does anyone have any ideas how I can optimize my program or think of a way I could solve it with relatively condense code that doesn’t use brute force?
Answer
There is a better way to implement the design you seem to be using. Rather than generating numbers and storing them in a list, just generate the numbers:
def generate_numbers(power):
for x in range(0, 10**power, 7):
if x % 7 == 0 and int(str(x)[::-1]) % 7 == 0:
yield x
Then do what you want with the generated sequence; e.g.
print( sum(generate_numbers(3)) )
This is more a point of design than optimization, but I imagine it would be faster too.
Attribution
Source : Link , Question Author : Vale , Answer Author : Community