所以我們的目標是創建一個布爾(true和false)表達式求值器。我採取的方式是從我正在使用的書中獲得所有真實的表達,並將它們放入列表中。然後從輸入文件我只是採取了第一行,並使用「如果在字符串中的行:」給我,如果輸入完全匹配列表中的一個字符串。但我想讓它讀取文本文件的每一行,並告訴我每行是真還是假,並且不知道如何使其工作,我知道它是讀第一行並告訴我它是真/假,假,但我不知道如何做多行。如何讀取輸入文本文件中的每一行並確定每行是真還是假?
這裏是我到目前爲止的代碼:
input_file = open('input.txt', 'r')
output_file = open('output.txt', 'w')
#List expressions that are true
strings = ['T', '(~ F)','T & T', 'T | T', 'T | F', 'F | T', '~ (T & F)',
'~ (F & T)', '~ (F & F)', '(T | F) & ~ (T & F)' , '(F | T) & ~ (F & T)',
'(T & T) | (~ T)', '(T & T) | (~ F)', '(T & F) | (~ F)', '(F & T) | (~ F)',
'(F & F) | (~ F)', '~ (~ T)', '(~ F) & (~ F)', '(~ T) | (~ F)', '(~ F) | (~ T)',
'(~ F) | (~ F)', 'T | (~ T)']
#read input// only use the first line// if line == strings then return true if not return false
lines = input_file.readline()
lines = input_file.readline()
def readline(line):
if lines in strings:
return True
else:
return False
if readline(lines) == True:
output_file.write('True')
print('Check output.txt.')
else:
output_file.write('False')
## 'The expression in BooleanExpression.txt is FALSE or the following:\n'
## 'You typed it in wrong, or expression was not defined in the\n'
## '"Discrete Mathematics with Applications" book.')
print('Check output.txt.')
#close files
input_file.close()
output_file.close()
所以,如果我的input.txt中看起來是這樣的:
(~ F)
(~ T)
T | T
此output.txt應該是這樣的:
True
False
True
您可以將代碼粘貼到此處而不是pastebin,它足夠簡短並且可讀性更好。 –
尋求調試幫助的問題(**「爲什麼這個代碼不工作?」**)必須包含所需的行爲,*特定的問題或錯誤*和*在問題本身中重現它所需的最短代碼* **。沒有**明確問題陳述**的問題對其他讀者沒有用處。請參閱:[如何創建最小,完整和可驗證示例](http://stackoverflow.com/help/mcve)。請***請勿***將您的代碼發佈到外部網站上。 – MattDMo
請問您可以發佈您的代碼,以及您在問題本身中嘗試過的內容。謝謝。 –