簡體   English   中英

需要幫助划分Python列表中元素的比例

[英]Need help dividing the ratio of elements in a Python list

我正在處理一個問題,要求我a)根據用戶輸入,按照用戶輸入的順序輸出斐波那契數,就像下面所做的那樣,b)除以並打印兩個最近項的比率。


fixed_start = [0, 1]          

def fib(fixed_start, n):      
    if n == 0:
        return fixed_start    
    else:
        fixed_start.append(fixed_start[-1] + fixed_start[-2])  
        return fib(fixed_start, n -1)      

numb = int(input('How many terms: '))

fibonacci_list = fib(fixed_start, numb)

print(fibonacci_list[:-1]) 

我希望我的輸出看起來像下面的樣子:

"How many terms:" 3

1 1
the ratio is 1.0
1 2
the ratio is 2.0
2 3
the ratio is 1.5

您是否正在尋找列表中最后2個項目的比例? 如果是,則應該可以。

print(fibonacci_list[-2:])
print(float(fibonacci_list[-1]/fibonacci_list[-2]))

或者,如果您要查找每2個數字之間的比率(剛開始時0和1除外),則下面的代碼應該可以解決問題

for x,y in zip(fibonacci_list[1:],fibonacci_list[2:]):
    print(x,y)
    print('the ratio is ' + str(round((y/x),3)))

輸出類似於以下15個項的斐波那契列表

1 1
the ratio is 1.0
1 2
the ratio is 2.0
2 3
the ratio is 1.5
3 5
the ratio is 1.667
5 8
the ratio is 1.6
8 13
the ratio is 1.625
13 21
the ratio is 1.615
21 34
the ratio is 1.619
34 55
the ratio is 1.618
55 89
the ratio is 1.618
89 144
the ratio is 1.618
144 233
the ratio is 1.618
233 377
the ratio is 1.618
377 610
the ratio is 1.618
610 987
the ratio is 1.618

當您已經解決了以列表形式生成斐波那契數列的第一部分時,您可以從中訪問最后兩個元素(最新)並獲取它們的比率。 Python使我們可以使用負索引從后向訪問列表的元素

def fibonacci_ratio(fibonacci_list):
    last_element = fibonacci_list[-1]
    second_last_element = fibonacci_list[-2]
    ratio = last_element//second_last_element
    return ratio

python中的double //將確保浮點除法。 希望這可以幫助!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM