简体   繁体   中英

Efficient, elegant way to create mathematical series in Python

In Javascript, here is a simple mathematical series.

var myList = []

for (var x = 2; x < 10000; x = x * 2) {
    mylist.push(x);
}

I cannot create a similar series in Python without:

  • Using a while loop

  • Looping over the entire range of numbers to 10,000 in a comprehension

Is this one of the rare cases where Python is a less elegant language?
Am I unaware of some functionality in Python here?

This can be done with itertools (as suggested by 4castle) operating on generator expressions.

from itertools import takewhile, count
myList = takewhile(lambda x: x < 10000, map(lambda x: 2 ** x, count()))

In python 2, you will need to use itertools.imap instead of map .

I don't get the question here. What do you class as elegance? For a couple of (perfectly legible) extra you can have a while loop set up.

def my_func():
    x = 2
    my_list = []

    while x < 10000:
        my_list.append(x)
        x = x * 2

I used timeit on an ancient laptop for basic code:

10000000 loops, best of 3: 34.9 ns per loop

This debate is irrelevant in terms of execution time or readability. There is no merit in discussing this further than to get into a debate about {} and ; that are all over JS in general, which is counter-productive. I'm sure some people are looking for one-liners but that will be obfuscated and inefficient.

"Efficient" and "elegant" can be a bit ambiguous. I'll assume "efficient" means both concise to type and quick to evaluate. And elegant I suppose means the result of its evaluation can be quickly and easily understood from the source.

Your question, in general, is difficult to answer because, for the most part, mathematical series as written by mathematicians can include arbitrarily complex operations that may or may not resolve to something "elegant" in one language or another (eg linear algebra is much more elegant in MATLAB/Octave than in Python).

Your question, specifically, is very easy to express elegantly (in either language) by noting the actual underlying mathematical expression you're really trying to evaluate:

在此处输入图片说明

Which, in python, is this:

from math import floor, log2
[2**x for x in range(1, floor(log2(10000))+1)]

In fact, I'm not sure you can represent the construction of this set as elegantly with JavaScript, but don't quote me on that because I am by no means an expert in that language.

So the answer is... It really depends on what you're trying to express. In this case, I prefer the python list comprehension to evaluation in a loop (in either language), but that's just me.

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