python - 迭代器类不递增值 Python
问题描述
我正在使用 Iterator 类来生成几何级数。当我编译代码时,它运行了正确的次数,但我的迭代器的值并没有从第一个值改变。例如,如果我输入 5 作为项数,2 作为第一项,3 作为共同比率,程序将输出 2 五次。我搞砸了什么?
class geo_p:
def __init__(self, n):
self.a = int(input('Enter the first term:'))
self.d = int(input('Enter the common ratio:'))
self.i = self.a
self.n = n
def _iter_(self):
return self
def _next_(self):
i = 1
if i < self.n:
#sets curr = to the current term in progression
current = self.i
self.i = (self.i * (self.d**(i-1)))
i +=1
return current
else:
raise StopIteration()
y = geo_p
n = int(input('Enter the number of terms: '))
y.__init__(y, n)
print(y)
for i in range (n):
print(y._next_(y))
解决方案
i
始终为 1(在 的顶部__next__
)
1-0 总是零
任何提高到零的东西都是 1 (@ self.d**(i-1)
)
所以你最终得到self.i = self.i * 1
但是正如对这个答案和原始问题的评论所指出的那样......你还有其他问题......但这就是为什么self.i
当你打电话时没有增加_next_()
推荐阅读
- c++ - 查找频率最高的元素(如果可能的话,最小的)及其在整数数组中的出现次数
- github - 使用 Github Actions 从非跟踪文件添加发布
- nim-lang - 如何在 Nim 中回显带有转义序列的字符串?
- cmake - 多个子目录项目的 CMake 文件
- c - 即使代码正确,输出的字符数组代码存储也是错误的
- node.js - 如果我的测试是用 Typescript 编写的,如何在浏览器模式下运行 Jasmine?
- database - 如何定义复杂对象的 Sequelize 模型?
- python - 修复格式错误的 tsv
- python - 我使用套接字在 python 中编写一个反向 shell 收费,我得到一个错误,说'int'对象没有属性'encode'
- javascript - 在 javascript 中使用正则表达式验证用户名