Tom Brady
Tom Brady

Reputation: 1

Creating Truth Table with Python IndexError:list out of range

Trying to make a Truth table through Python using itertools but keep getting same error

Heres my code so far

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

Error comes on main() and on w0 = gen_constants (int(sys.argv [1]))

Upvotes: 0

Views: 569

Answers (2)

Misha Akovantsev
Misha Akovantsev

Reputation: 1825

You need to provide integer argument.

Compare these:

$ 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'

Or update your code to deal with any input or with the absence of one.


UPDATE:

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)

Which gives you:

$ 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

Upvotes: 0

philofinfinitejest
philofinfinitejest

Reputation: 4047

IndexError: list index out of range means that the index supplied is too large for the list that you are indexing, meaning that when the line

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

is executed sys.argv contains at most 1 item, not the 2 that would make sys.argv[1] return a result, which means that you are not passing in an argument when running the script.

Upvotes: 1

Related Questions