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

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 に答える