gpt4 book ai didi

python 使用斐波那契数列

转载 作者:行者123 更新时间:2023-11-30 23:53:28 26 4
gpt4 key购买 nike

我试图仅在单词出现的次数与斐波那契数列中出现的次数相同时才打印出来。如果一个单词显示 1、2、3、5、8 等,那么它就会打印出来。我已经让程序根据出现的次数打印单词。我无法弄清楚如何在程序中使用该序列。任何提示或示例将不胜感激。

def fib():
a,b = 0, 1
while 1:
yield a
a, b= b, a+b

from collections import Counter
import string


while True:
filename=raw_input('Enter a file name: ')
if filename == 'exit':
break
try:
file = open(filename, 'r')
text=file.read()
file.close()
except:
print('file does not exist')
else:

for word in string.punctuation:
text=text.replace(word, "")
word_list = text.lower().split(None)
word_freq = {}

for word in word_list:
if len(word) > 1:
word_freq[word] = word_freq.get(word, 0) + 1

print(sorted(word_freq.items(), key=lambda item: item[1]))
// I am pretty sure something with the seqeunce should go into the above line
// but have been unable to figure it out.

print('Bye')

最佳答案

class FibSet:
'''Fibonacci sequence with the in operator defined'''

def __init__(self):
self.a, self.b = 0, 1
self.fib = set()

def __contains__(self, n):
if n > self.b:
self.compute_upto(n)
return n in self.fib

def compute_upto(self, n):
while self.b < n:
self.fib.add(self.a)
self.a, self.b = self.b, self.a + self.b

关于python 使用斐波那契数列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5668969/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com