简体   繁体   English

我的 python 列表程序由于某种原因无法运行

[英]My python list program doesn't work for some reason

a = []
s = 0
k = 0
for i in range(20):
    x = int(input())
    if x<0:
        s+=x
        k+=1
    a.append(x)
z = s/k
for i in range(20):
    l = (a[i])-z
    del a[i]
    a.append(l)
print(a)
input()

The task is: The values of a one-dimensional list of 20 elements are read from a standard data input stream.任务是:从标准数据输入 stream 中读取 20 个元素的一维列表的值。 Convert the original list by subtracting from the value of each element of the list the arithmetic average of the negative elements of the list.通过从列表中每个元素的值中减去列表中负元素的算术平均值来转换原始列表。 The source data is integers ranging from -10^6 to 10^6.源数据是从 -10^6 到 10^6 的整数。

This isn't the answer, but you've been dinged because your code isn't easily testable.这不是答案,但你已经被叮了,因为你的代码不容易测试。 Your description of the problem is vague and since your code is buggy we don't have a good idea what to expect of it.您对问题的描述含糊不清,并且由于您的代码有问题,我们不知道会发生什么。 Its best to give sample input and sample output.最好提供样本输入和样本 output。 And you should do it so that we can just copy/paste and run it.你应该这样做,这样我们就可以复制/粘贴并运行它。

Since this is something you should generally be doing with code anyway, here is an example of how to make your code testable.因为这是你通常应该对代码做的事情,这里有一个如何让你的代码可测试的例子。 First, don't do anything at module level.首先,不要在模块级别做任何事情。 Put the algorithm in a function将算法放入 function

foo.py foo.py

import sys

def bar(input_sequence):
    a = []
    s = 0
    k = 0
    vals = iter(input_sequence)
    for i in range(20):
        x = next(vals)
        if x<0:
            s+=x
            k+=1
        a.append(x)
    z = s/k
    for i in range(20):
        l = (a[i])-z
        del a[i]
        a.append(l)

if __name__ == "__main__":
    a = foo(sys.stdin)
    print(a)

Now you can call foo() with canned input that you already know the result you want.现在您可以使用已知道所需结果的固定输入调用foo() Might as well put this in the python unittest framework so you can easily add and run tests as functionality of your program grows.不妨把它放在 python 单元测试框架中,这样您就可以随着程序功能的增长轻松添加和运行测试。

testfoo.py测试foo.py

import unittest
import foo

class TestFoo(unittest.TestCase):

    def test_bar_1():
        test_data = ['todo: fill in here']
        expected_result = ['todo: fill in here']
        result = foo.bar(test_data)
        self.assertEqual(expected_result, result)

if __name__ == "__main__":
    unitttest.main()

now you can go the command prompt and type现在你可以 go 命令提示符并输入

python testfoo.py

We can run this code and it tells us exactly what you expect the function to do.我们可以运行这段代码,它准确地告诉我们您期望 function 做什么。 In a "test first" design, you'd write the testfoo.py before foo.py so that you'd have an easy way to validate the code as you write it.在“测试优先”的设计中,您将在testfoo.py之前编写foo.py ,这样您就可以在编写代码时轻松验证代码。

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

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