fibaux(n)[0]在python中意味着什么?

时间:2016-02-14 08:14:05

标签: java python function

所以我正在寻找一个更有效的斐波那契计算器的代码,但我不明白返回fibaux(n)[0]意味着什么。我试图将它转换为java,我几乎拥有它,但我不明白这一部分。谢谢!

 def fib(n):
 ## Handle special case when n == 0
 if n == 0:
    return 0
## General case, return the first of the
## two values returned by fibaux
else:
    return fibaux(n)[0]

## Auxiliary function
## Return the nth and (n-1)th Fibonacci numbers
## n must be an integer >= 1
def fibaux(n):
  ## Base case of for recursion
  if n == 1:
     return 1, 0
  else:
    ## Recursive case
    f2, f1 = fibaux(n - 1)
    return f2 + f1, f2

好的谢谢你们!我现在明白了,但我想我在将这个转换为java时没有走上正轨,因为我没有得到正确的输出,这就是我写的:

  public class Fibonacci {

   public static int[] fib(int number){
      if (number == 0){
       return new int[] {0};
     }
     else{
       int fibauxArray[] = fibaux(number);
       int f3 = fibauxArray[0];
       return new int[] {f3};
     }
    }

public static int[] fibaux(int number){
  if (number == 1){
     return new int[] {1, 0};
  }
  else{
     int[] Q = fibaux(number-1);
     int f2 = Q[0]+Q[0];
     int f1 = Q[0];
     return new int[] {f2, f1};
 }

}

有什么建议吗?再次感谢。

1 个答案:

答案 0 :(得分:1)

fibaux会返回两个数字的tuple(不可更改的列表):

>>> fibaux(3)
(2, 1)

[0]获取索引0处的项目(第一个数字):

>>> fibaux(3)[0]
2

我相信如果您将此移植到Java,您可能要使用fibaux(n).get(0)(如果fibaux返回List)或fibaux(n)[0](如果{{ 1}}返回fibaux

相关问题