使用Python创建真值表IndexError:列出超出范围

时间:2012-02-10 02:16:10

标签: python list itertools truthtable

尝试使用itertools通过Python创建一个Truth表,但不断出现相同的错误

到目前为止我的代码

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]))

2 个答案:

答案 0 :(得分:1)

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

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

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

答案 1 :(得分: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