0

My professor asked me to simulate Boolean Gates and the output is a truth table

To simulate an n=3 Gates you need 3 for loop

for i in range(0,2):
     for j in range(0,2): 
           for k in range(0,2):
                 stuff

To simulate an n=2 Gates you need 2 for loop

for i in range(0,2):
     for j in range(0,2): 
                 stuff

i wanted to have an an n= user input, so there may be a chance where the user input more than 10 is there a way to automate the loop??

if there's any reference, especially if it uses an oop paradigm, it would be very helpfull Thank you

3
  • 1
    my idea was to do a recursive loop, is it possible?? Commented Apr 22, 2021 at 13:51
  • if I understand you, n changes the loop count by 2**n, if so you can just change the loop range by that equation. unless you use the loop count in stuff Commented Apr 22, 2021 at 13:52
  • 1
    It sounds like you're looking for itertools.product. Commented Apr 22, 2021 at 13:58

1 Answer 1

4

It looks like you want to generate all the possible 2**n combinations of values for i,j,k,.... If that is the case, you can use itertools.product to generate them all:

from itertools import product

for p in product(range(2), repeat=3):
    print(p)

Which will produce:

(0, 0, 0)
(0, 0, 1)
(0, 1, 0)
(0, 1, 1)
(1, 0, 0)
(1, 0, 1)
(1, 1, 0)
(1, 1, 1)

Simply change repeat=n and you are done.

Cheers!

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.