简体   繁体   中英

Modify function to use list comprehision in Python

I have got a function:

def euler9():
    for b in range(1, 500):
        a = (500000 - 1000 * b) / (1000 - b)
        if a % 1 == 0:
            print(b * a * (1000 - a - b))

And I want to make it in one line like

x*x for x in range(1,1)

This is what I have done:

def euler9():
    print([b * a * (1000 - a - b) for b in range(1, 500) for a in (500000 - 1000 * b) / (1000 - b) if a % 1 == 0])

but I do not know what am I doing wrong. I have got an error: TypeError: 'float' object is not iterable

for is for iteration (looping). When you say for b in range(1, 500) you are not setting b = range(1, 500) , since that would make b a list. You are extracting each individual value and using them one at a time. You cannot extract values from a float.

Python has no syntax for simple assignment in list comprehensions, but you can work around that by putting the value inside a single-element list, thus making it iterable:

[b * a * (1000 - a - b) for b in range(1, 500) for a in [(500000 - 1000 * b) / (1000 - b)] if a % 1 == 0]

(You can put print(...) around the initial expression if you want but I assume you want to actually use the values)

But don't ever do this, it's hard to read and unnecessary.

Here for a in (500000 - 1000 * b) / (1000 - b) you are trying to iterate over a float number which is the result of a devision. As a quick fix try this:

def euler9():
    print([b * ((500000 - 1000 * b) / (1000 - b)) * (1000 - ((500000 - 1000 * b) / (1000 - b)) - b) 
           for b in range(1, 500) if ((500000 - 1000 * b) / (1000 - b)) % 1 == 0])

But, as you see it gets a bit messy that way, and it is recommended to use loops instead of list comprehension when things get complicated.

Turn it into a generator by changing print to yield :

def euler9():
    for b in range(1, 500):
        a = (500000 - 1000 * b) / (1000 - b)
        if a % 1 == 0:
            yield (b * a * (1000 - a - b))

Then you can access it as a list comprehension:

print [x for x in euler9()]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM