如何在python中编写生成Fibonacci

时间:2015-01-27 22:23:28

标签: python generator fibonacci yield function

def fib(a, b, f):

fib必须产生(使用产量)广义Fibonacci 序列,a和b是第一和第二元素。 f是获得第三个元素而不是+ b作为正常Fibonacci序列的函数。使用take函数(如下所示)进行测试。

我的代码在

之下
def fib(a, b, f):
    x = a
    y = b
    yield x
    x, y = y, f(x,y)
    fib(x,y,f)

我不知道我的代码有什么问题,当我尝试测试它时,它会显示出来 "TypeError: 'generator' object is not subscriptable"

测试用例是:

 take(5, fib(0, 1, lambda x, y: x - y))

它应该放在:

[0, 1, -1, 2, -3]

并且我写的功能是:

def take(n, iterable):
       x = []
    if n <= 0:
        return x
    else:
        for i in range (0,n):
            x.append(iterable[i])
        return x

3 个答案:

答案 0 :(得分:2)

该消息表示生成器不支持索引,因此iterable[i]失败。相反,使用next()函数从迭代器中获取下一个项目。

def take(n, iterable):
    x = []
    if n > 0
        itr = iter(iterable)     # Convert the iterable to an iterator
        for _ in range(n):       # Repeat n times
            x.append(next(itr))  # Append the next item from the iterator
    return x

此外,您的fib()功能无效。你不应该在功能结束时递归;而是编写一个循环,yield每次迭代都是一个值。

def fib(a, b, f):
    x = a
    y = b
    while True:
        yield x
        x, y = y, f(x,y)

答案 1 :(得分:0)

您无法将来自fib()等生成器函数的结果编入索引。以下内容通过将zip()range()参数一起使用来避免这种情况。当其中一个参数到达然后结束时,zip()会自动停止。

def fib(a, b, f):
    x, y = a, b
    while True:
        yield x
        x, y = y, f(x, y)

def take(n, iterable):
    return [] if n <= 0 else [v for _, v in zip(range(n), iterable)]

print( take(5, fib(0, 1, lambda x, y: x-y)) )

输出:

[0, 1, -1, 2, -3]

答案 2 :(得分:0)

您将遇到的最简单的斐波那契方法:

import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.navigation.fragment.NavHostFragment
import androidx.navigation.ui.AppBarConfiguration
import androidx.navigation.ui.setupActionBarWithNavController
import androidx.navigation.ui.setupWithNavController
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        val appBarConfiguration = AppBarConfiguration(setOf(R.id.home, R.id.saved))

        val navHostFragment = supportFragmentManager.findFragmentById(R.id.nav_host_container) as NavHostFragment
        val navController = navHostFragment.navController

        setupActionBarWithNavController(navController, appBarConfiguration)
        bottom_nav.setupWithNavController(navController)
    }
}