简体   繁体   English

为什么我的函数抛出“ StopIteration”异常?

[英]Why is my function throwing a 'StopIteration' exception?

I've got a function that calculates Pythagorean triples using a generator. 我有一个函数,可以使用生成器来计算勾股三元组。 However when i call next(myfunc()) it throws this error: 但是,当我调用next(myfunc())它将引发此错误:

Traceback (most recent call last):
  File "path omitted", line 124, in <module>
    next(x)
StopIteration

Where x = myfunc() 其中x = myfunc()

Here is my function: 这是我的功能:

import math

def myfunc():
    i = 1
    for z in range(0, i):
        for y in range(0, z):
            for x in range(0, y):
                if (math.pow(x, 2) + math.pow(y, 2)) == math.pow(z, 2):
                    yield (x*y*z)
                    i += 1

The problem is that your function does not yield anything because your range are probably messed up: 问题在于您的函数无法产生任何结果,因为您的范围可能被弄乱了:

  1. z goes from 0 to i - 1 ( 0 ) - So you have only one loop z = 0 z0i - 10 )-所以你只有一个循环z = 0
  2. y goes from 0 to z - 1 ( -1 ) - See the problem? y0z - 1-1 )-看到问题了吗?

So basically you're calling next on an "empty" generator, so you get a StopIteration exception. 因此,基本上,您是在“空”生成器上调用next ,因此您会收到StopIteration异常。

Also note that range(0, i) is evaluated only once, just after i = 1 , so incrementing i in your inner loop does not affect the bound of your outer loop, so it is a useless statement. 还要注意,仅在i = 1之后i = 1 range(0, i)进行一次评估,因此在内部循环中递增i不会影响外部循环的边界,因此这是一个无用的声明。

BTW, most of the time you do not have to call next manually, you should rather use a for loop: 顺便说一句,大多数情况下,您不必手动调用next ,您应该使用for循环:

for a in myfunc(): # The for loop handle the StopIteration exception for you
    print(a)

Edit: And you should not use math.pow to compute the square value of an integer because it is not accurate (floating point precision) and it is much more slower than doing x * x , so simply check x * x + y * y == z * z (or use python power notation ** : x ** 2 + y ** 2 == z ** 2 ). 编辑:并且您不应该使用math.pow计算整数的平方值,因为它不准确(浮点精度)并且比执行x * x慢得多,因此只需检查x * x + y * y == z * z (或使用python幂符号**x ** 2 + y ** 2 == z ** 2 )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM