我剛剛看到了lua
,其中包括sieve.lua
live demo。它是使用協程的Erathostenes篩的實現。我立即想到的是:這看起來乾淨多在python:
#!/usr/bin/env python3
# sieve.py
# the sieve of Eratosthenes programmed with a generator functions
# typical usage: ./sieve.py 500 | column
import sys
# generate all the numbers from 2 to n
def gen(n):
for i in range(2,n):
yield i
# filter the numbers generated by `g', removing multiples of `p'
def filter(p, g):
for n in g:
if n%p !=0:
yield n
N=int(sys.argv[1]) if len(sys.argv)>1 else 500 # from command line
x=gen(N) # generate primes up to N
while True:
try:
n = next(x) # pick a number until done
except StopIteration:
break
print(n) # must be a prime number
x = filter(n, x) # now remove its multiples
這不會有很多工作要做這樣一個問題,但使用Python 3.4.3
我的機器上的堆棧溢出發生某處N>7500
。使用sieve.lua
和Lua 5.2.3
,堆棧溢出發生在N>530
。可以像任何其他對象一樣傳遞生成器對象(代表暫停的協程),並且可以在任何地方將next()內置的應用程序應用於其中,因此python中的協程是一流的。如果我錯了,請糾正我。
爲什麼蟒需要這麼多的構造個人猜測:它引入語言相當最近,需要適應工作蓄客已經現有的語法(向其他語句中添加'async')你也似乎鏈接了很多資源來解釋各種構造如何工作 - 你的問題沒有被文檔回答嗎? –
我不知道python協同工作是如何工作的,但是如果你需要Lua協程的幫助,我可以:) – warspyking
[Here's](http://sahandsaba.com/understanding-asyncio-node-js-python-3- 4.html)一個很好的帖子在python asyncio如果有點長時間的囉嗦...對於Lua,我一直認爲[Documentation](https://www.lua.org/pil/9.1.html)寫得很好 – Aaron