Last week we faced the issues of Palindromes.
This week we are going to solve it.
First, lets have a look at the obvious solution:
We need to find a Palindrome. Forward is the same as backwards:
str(x*y) == str(x*y)[::-1]
This line takes the product(xy) makes a string out of it, str(xy), inverts that string, [::-1], and compares it to the original string.
"[a:b:c]" is so much fun to work with and every time I get very confused and will google it:))
Next one is to find the values for x and y:
for x in range(9000,10000): for y in range(x,10000):
We just try numbers above 9000, all the other are not worth to test.
Now mix everything together:
maxpal = 0 for x in range(9000,10000): for y in range(x,10000): p = x * y if str(p) == str(p)[::-1] and p > maxpal: maxpal = p print(maxpal)
We run it and get the answer:
There you go!
But now for the fun one:
max([x*y for x in range(9000,10000) for y in range(x,10000) if str(x*y) == str(x*y)[::-1]])
What is this?
The maximum out of the list:
[x*y for x in range(9000,10000) for y in range(x,10000) if str(x*y) == str(x*y)[::-1]]
The list are items made of the product x*y
and the rest are the same for loops and if statements as described above to filter it.
Result is the same.
This week, there is no homework for you, just post a comment or question and get some BEER
Posted with STEMGeeks