2016-02-14 45 views
-1

所以我在看一個更有效的斐波納契計算器的代碼,但我不明白什麼返回fibaux(n)[0]的含義。我試圖將其轉換爲Java,我幾乎擁有它,但我不明白這一部分。謝謝!在python中,fibaux(n)[0]是什麼意思?

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}; 
} 

} 

有什麼建議?再次感謝。

+0

它返回由'fibaux'函數返回的元組的第一個元素。 – Maroun

回答

1

fibaux返回兩個數字的tuple(一個不可改變的列表):

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

[0]採用了該項目索引0(第一號):

>>> fibaux(3)[0] 
2 

我相信,如果你正在移植這對於Java,您要麼使用fibaux(n).get(0)(如果fibaux返回List)或fibaux(n)[0](如果fibaux返回Array