2015-05-16 82 views
0

該程序返回指定字符串的truth_table。我想從控制檯讀取一個字符串,但我不知道如何創建dinamically變量。我試過(幾乎)一切,但沒有奏效。請幫幫我。對不起我的英語不好。自動創建Python變量

from itertools import izip, product, tee 

# Logic functions: take and return iterators of truth values 

def AND(a, b): 
    for p, q in izip(a, b): 
     yield p and q 

def OR(a, b): 
    for p, q in izip(a, b): 
     yield p or q 

def NOT(a): 
    for p in a: 
     yield not p 

def EQUIV(a, b): 
    for p, q in izip(a, b): 
     yield p is q 

def IMPLIES(a, b): 
    for p, q in izip(a, b): 
     yield (not p) or q 

def XOR(a,b): 
    for p,q in izip(a,b): 
     yield (p and (not q)) or ((not p) and q) 

def create(num=2): 
#''' Returns a list of all of the possible combinations of truth for the 
given number of variables. 
#ex. [(T, T), (T, F), (F, T), (F, F)] for two variables ''' 
    return list(product([True, False], repeat=num)) 

def unpack(data): 
#''' Regroups the list returned by create() by variable, making it suitable 
for use in the logic functions. 
#ex. [(T, T, F, F), (T, F, T, F)] for two variables ''' 
    return [[elem[i] for elem in lst] for i, lst in enumerate(tee(data, 
    len(data[0])))] 

def print_result(data, result): 
''' Prints the combinations returned by create() and the results returned 
by the logic functions in a nice format. ''' 
    n = len(data[0]) 
    headers = 'abcdefghijklmnopqrstuvwxyz'[:n] 
    print headers + "|RESULT" 
    print '-' * len(headers) + '+------' 
    for row, result_cell in izip(data, result): 
     print ''.join({True: 'T', False:'F'}[cell] for cell in row) + '|' + 
     ' ' + {True: 'T', False:'F'}[result_cell] 




if __name__ == '__main__': 
    data = create(num = 2) 
    a,b = unpack(data) 
    result = IMPLIES(a,b)  
    print_result(data, result)  
+2

如果你想要動態變量名稱,你應該使用一個字典。例如'{'name1':value,'name2':value2,...} – IanAuld

回答

2

我以前遇到過這個問題,答案是使用字典。 這裏基本上是你需要的

var_dict = {} 
my_list = ['a', 'b', 'c', 'd'] 
for each in my_list:  
    #Create a new dictionary key if it the current iteration doesn't already exist 
    if each not in var_dict.keys(): 
     var_dict[each] = <THE VALUE YOU WISH TO SET THE VARIABLE TO> 
    else: 
     pass 
     #Or do something if the variable is already created 
+0

我覺得我不是很聰明,因爲它不起作用。如果替換: a,b =解包(數據) 通過: a =解包(數據)[0] b =解壓縮(數據)[1] 它可以很好地工作,但如果創建變量則不起作用動態。 –