#!/usr/bin/env python # coding: utf-8 # # Logik # # * `and`: und # * `or`: oder # * `not`: negation # * `^`: xor # # Wahr, Falsch oder [Unbekannt](http://de.wikipedia.org/wiki/Unvollständigkeitssatz). # In[1]: True and True # In[2]: not True or not False # In[3]: not (True or False) # In[4]: True ^ False # In[5]: True ^ True # In[6]: not (False or False) # ## Wahrheitstabelle # In[7]: fmt = lambda t : "X" if t else "." # In[8]: def print_table(prop): from itertools import product print("A B C => P") print("-" * 14) for state in product([True, False], repeat=3): args = ' '.join(fmt(s) for s in state) res = prop(*state) print("{} => {}".format(args, fmt(res))) # In[9]: prop1 = lambda a, b, c : (a or (not a and b)) and c print_table(prop1) # In[10]: prop2 = lambda a, b, c : (a or b) and c print_table(prop2) # In[11]: prop3 = lambda a, b, c : a and (b ^ c) print_table(prop3) # ## Addition zweier Boolscher Vektoren # # Die zwei Vektoren werden nach den üblichen Regeln addiert. # In[12]: a = [True, True, False, True, True, False] b = [True, True, False, False] # In[13]: def boolean_add(a, b): size = max(len(a), len(b)) # padding for v in [a, b]: while len(v) < size: v.insert(0, False) result = [] c = False for pos in reversed(range(size)): s = a[pos] ^ b[pos] ^ c c = (a[pos] and b[pos]) or (c and (a[pos] ^ b[pos])) result.insert(0, s) result.insert(0, c) return result # In[14]: ab = boolean_add(a, b) ab # In[15]: def boolean_to_decimal(b): result = 0 for i, x in enumerate(reversed(b)): result += 2**i * x return result # In[16]: print boolean_to_decimal(a) print boolean_to_decimal(b) print boolean_to_decimal(ab)