0

尝试使用 itertools 通过 Python 制作真值表但不断收到相同的错误

到目前为止,这是我的代码

import sys
import itertools

def gen_constants(numvar):
    l = []
    for i in itertools.product([False, True], repeat=numvar):
        l.append (i)
    return l

def big_and (list):

    if False in list:
        return False
    else:
        return True

def big_or (list):
    if True in list:
        return True
    else:
        return False


def main():
    w0 = gen_constants (int(sys.argv [1]))
    for i in w0:
        print big_and (i)
    for i in w0:
        print big_or (i)



if __name__ == '__main__':
    main()

错误出现在 main() 和 w0 = gen_constants (int(sys.argv [1]))

4

2 回答 2

1

IndexError: list index out of range表示提供的索引对于您要索引的列表来说太大了,这意味着当该行

w0 = gen_constants (int(sys.argv [1]))

执行sys.argv的最多包含 1 个项目,而不是 2 会sys.argv[1]返回结果的项目,这意味着您在运行脚本时没有传入参数。

于 2012-02-10T02:56:40.163 回答
0

您需要提供整数参数。

比较这些:

$ python /tmp/111.py 
Traceback (most recent call last):
  File "/tmp/111.py", line 33, in <module>
    main()
  File "/tmp/111.py", line 24, in main
    w0 = gen_constants (int(sys.argv [1]))
IndexError: list index out of range

$ python /tmp/111.py 1
False
True
False
True

$ python /tmp/111.py 2
False
False
False
True
False
True
True
True

$ python /tmp/111.py w
Traceback (most recent call last):
  File "/tmp/111.py", line 33, in <module>
    main()
  File "/tmp/111.py", line 24, in main
    w0 = gen_constants (int(sys.argv [1]))
ValueError: invalid literal for int() with base 10: 'w'

或者更新您的代码以处理任何输入或没有输入。


更新:

def main():
    try:
        argument = sys.argv[1]
    except IndexError:
        print 'This script needs one argument to run.'
        sys.exit(1)

    try:
        argument = int(argument)
    except ValueError:
        print 'Provided argument must be an integer.'
        sys.exit(1)

    w0 = gen_constants (argument)
    for i in w0:
        print big_and (i)
    for i in w0:
        print big_or (i)

这给了你:

$ python /tmp/111.py
This script needs one argument to run.

$ python /tmp/111.py 2.0
Provided argument must be an integer.

$ python /tmp/111.py w
Provided argument must be an integer.

$ python /tmp/111.py 1
False
True
False
True
于 2012-02-10T02:28:35.773 回答