2012-08-26 09:15:44 -04:00
|
|
|
import os
|
2015-01-23 09:31:25 -05:00
|
|
|
import re
|
2012-08-26 09:15:44 -04:00
|
|
|
import sys
|
|
|
|
|
2015-04-13 07:18:21 -04:00
|
|
|
|
2012-09-17 11:27:50 -04:00
|
|
|
def is_number(x):
|
2015-04-13 07:09:44 -04:00
|
|
|
try:
|
|
|
|
_ = float(x)
|
|
|
|
except ValueError:
|
|
|
|
return False
|
|
|
|
return True
|
2012-09-17 11:27:50 -04:00
|
|
|
|
2015-04-13 07:18:21 -04:00
|
|
|
|
2012-09-17 11:27:50 -04:00
|
|
|
def remove_numbers(seq):
|
2015-04-13 07:09:44 -04:00
|
|
|
return [x for x in seq if not is_number(x)]
|
2012-09-17 11:27:50 -04:00
|
|
|
|
2015-04-13 07:18:21 -04:00
|
|
|
|
2012-09-14 06:26:48 -04:00
|
|
|
def remove_duplicates(seq):
|
2015-04-13 07:09:44 -04:00
|
|
|
seen = set()
|
|
|
|
seen_add = seen.add
|
|
|
|
return [x for x in seq if x not in seen and not seen_add(x)]
|
2012-09-14 06:26:48 -04:00
|
|
|
|
2015-04-13 07:18:21 -04:00
|
|
|
|
2012-08-26 09:15:44 -04:00
|
|
|
def get_operands(s):
|
2015-04-13 07:09:44 -04:00
|
|
|
operands = re.findall("[A-z0-9_]+", s)
|
|
|
|
operands = remove_duplicates(operands)
|
|
|
|
operands = remove_numbers(operands)
|
|
|
|
return sorted(operands)
|
2012-08-26 09:15:44 -04:00
|
|
|
|
2015-04-13 07:18:21 -04:00
|
|
|
|
2012-08-26 09:15:44 -04:00
|
|
|
def gen_truth_table(s):
|
2015-04-13 07:09:44 -04:00
|
|
|
operands = get_operands(s)
|
|
|
|
width = len(operands)
|
|
|
|
stim = []
|
|
|
|
for i in range(width):
|
|
|
|
stim_op = []
|
|
|
|
for j in range(2**width):
|
|
|
|
stim_op.append((int(j/(2**i)))%2)
|
|
|
|
stim.append(stim_op)
|
|
|
|
|
|
|
|
truth_table = []
|
|
|
|
for i in range(2**width):
|
|
|
|
for j in range(width):
|
2015-04-13 07:37:46 -04:00
|
|
|
exec("{} = stim[j][i]".format(operands[j]))
|
2015-04-13 07:09:44 -04:00
|
|
|
truth_table.append(eval(s) != 0)
|
|
|
|
return truth_table
|
2012-08-26 09:15:44 -04:00
|
|
|
|
2015-04-13 07:18:21 -04:00
|
|
|
|
2012-08-26 09:15:44 -04:00
|
|
|
def main():
|
2015-04-13 07:09:44 -04:00
|
|
|
print(gen_truth_table("(A&B&C)|D"))
|
2015-01-23 09:31:25 -05:00
|
|
|
|
2012-08-26 09:15:44 -04:00
|
|
|
if __name__ == '__main__':
|
2015-04-13 07:09:44 -04:00
|
|
|
main()
|