Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 当相同的值出现在列表中时,如何停止循环?_Python_Python 3.x_List_Math_While Loop - Fatal编程技术网

Python 当相同的值出现在列表中时,如何停止循环?

Python 当相同的值出现在列表中时,如何停止循环?,python,python-3.x,list,math,while-loop,Python,Python 3.x,List,Math,While Loop,以上是我的任务。当相同的项目出现在列表中时,我必须停止循环,然后我必须对它们求和 def squareA(a,b): res = [] z = 0 while z!= 3: res.insert(0,(a + z)**2) res.insert(0,(b - z)**2) z += 1 print(res) res = list(dict.fromkeys(res)) print(res) res = sum(res) ret

以上是我的任务。当相同的项目出现在列表中时,我必须停止循环,然后我必须对它们求和

def squareA(a,b):
  res = []
  z = 0

  while z!= 3:

     res.insert(0,(a + z)**2)
     res.insert(0,(b - z)**2)
     z += 1

  print(res)
  res = list(dict.fromkeys(res))
  print(res)
  res = sum(res)

  return res

a = 5
b = 6
print(squareA(a,b))

我想你可能想得太多了。与从两端附加正方形(同时从a向上和从b向下)不同,您可以执行以下操作:

def square(a, b):
    rv = a**2
    for i in range(a, b):
        rv+= (i+1)**2
    return rv
或者使用示例代码中的列表:

def square(a, b):
    rv = [a**2]
    for i in range(a, b):
        rv.append((i+1)**2)
    return sum(rv)

例如,当我输入a=5,b=6时,我的程序将它们平方和,但当我有a=1和b=4时,和看起来像1+16+9+4=30欢迎使用StackOverflow。看见在您发布MRE代码并准确说明问题之前,我们无法有效地帮助您。我们应该能够将您发布的代码粘贴到文本文件中,并重现您指定的问题。你还没有描述你的问题。据我猜测,你想让我们教你如何分析和解决一般问题;这将超出堆栈溢出的范围。pogiloyded:将问题的描述放在您的问题中。上面练习的图像