微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

迭代器类不递增值 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_() 没有增加

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。