Convert Python Nested Loops to Lists

I started working on some of the problems of Project Euler and solved number 4 with a simple solution for brute force:

def mprods(a,b):
 c = range(a,b)
 f = []
 for d in c:
  for e in c:
   f.append(d*e)
 return f

max([z for z in mprods(100,1000) if str(z)==(''.join([str(z)[-i] for i in range(1,len(str(z))+1)]))])

After the solution, I tried to make it as compact as possible and came up with this terrible bottom line!

In order not to leave something halfway, I'm trying to condense a function mprodsin a list comprehension. So far I have come up with these attempts:

  • [d*e for d,e in (range(a,b), range(a,b))]
    Obviously completely on the wrong track. :-)
  • [d*e for x in [e for e in range(1,5)] for d in range(1,5)]
    It gives me [4, 8, 12, 16, 4, 8, 12, 16, 4, 8, 12, 16, 4, 8, 12, 16]where I expect [1, 2, 3, 4, 2, 4, 6, 8, 3, 6, 9, 12, 4, 8, 12, 16]or similar.

Any Pythonistas that can help? :)

+3
source share
3 answers
c = range(a, b)
print [d * e for d in c for e in c]
+7
source
from itertools import product

def palindrome(i):
  return str(i) == str(i)[::-1]

x = xrange(900,1000)

max(a*b for (a,b) in (product(x,x)) if palindrome(a*b))
  • xrange(900,1000) range(900,1000), , , , . , () .

  • product(xrange(900,1000),xrange(900,1000)) . . , product(A, B) , : ((x,y) for x in A for y in B). for-loop, , ( ).

    product('ab', range(3))('a',0) ('a',1) ('a',2) ('b',0) ('b',1) ('b',2) product((0,1), (0,1), (0,1))(0,0,0) (0,0,1) (0,1,0) (0,1,1) (1,0,0) ...

  • str(i)[::-1] - , .

  • , , .

  • , , , 91 99, range(90,100). 3- , range(900,1000).

+3

I think you will like this one line (formatted for readability):

max(z for z in (d*e
                for d in xrange(100, 1000)
                for e in xrange(100, 1000))
            if str(z) == str(z)[::-1])

Or a little changed:

c = range(100, 1000)
max(z for z in (d*e for d in c for e in c) if str(z) == str(z)[::-1])

I wonder how many partners would be in Lisp ...

+2
source

Source: https://habr.com/ru/post/1734310/


All Articles