Larrrrrrrrrry - 1 year ago 75

Python Question

I was trying to solve Project Euler Problem #4 and while I have solved it I am not satisfied with my code because it generates repeats.

Below is the code:

`pal = []`

for i in range(100 ** 2, 1000 ** 2):

if str(i) == str(i)[::-1]:

pal.append(i)

for n in pal:

for x in range(100, 1000):

if 99 < n / x < 1000 and n % x == 0:

print(x, n//x, n)

# largest palindrome product of two 3-digit numbers

When I run this code, I get repeats ie. multiples of the same palindrome product. For example, it will return 840048 twice, which is a product of 888 and 946. Is there a way to not generate repeats with this code?

EDIT 1: part of my build output

`946 888 840048`

869 982 853358

982 869 853358

894 957 855558

957 894 855558

924 932 861168

Answer Source

You could you `set`

or to store values just once:

```
pal = set()
for i in range(100 ** 2, 1000 ** 2):
if str(i) == str(i)[::-1]:
pal.add(i)
for n in pal:
for x in range(100, 1000):
if 99 < n / x < 1000 and n % x == 0:
print(x, n//x, n)
```