以下代碼應該提供一個框架,在該框架上構建和擴展您的問題中的程序。大部分代碼應該與當前編寫的一樣好,但是如果需要,您可以擴展它的功能。要繼續構建可以問什麼問題以及給出了什麼答案,請考慮在文件頂部的數據庫中添加更多部分。案例可以很容易地擴充。
#! /usr/bin/env python3
"""Cell Phone Self-Diagnoses Program
The following program is designed to help users to fix problems that they may
encounter while trying to use their cells phones. It asks questions and tries
to narrow down what the possible cause of the problem might be. After finding
the cause of the problem, a recommended action is provided as an attempt that
could possibly fix the user's device."""
# This is a database of questions used to diagnose cell phones.
ROOT = 0
DATABASE = {
# The format of the database may take either of two forms:
# LABEL: (QUESTION, GOTO IF YES, GOTO IF NO)
# LABEL: ANSWER
ROOT: ('Does your phone turn on? ', 1, 2),
1: ('Does it freeze? ', 11, 12),
2: ('Have you plugged in a charger? ', 21, 22),
11: ('Did you drop your device in water? ', 111, 112),
111: 'Do not charge it and take it to the nearest specialist.',
112: 'Try a hard reset when the battery has charge.',
12: 'I cannot help you with your phone.',
21: 'Charge it with a different charger in a different phone '
'socket.',
22: ('Plug it in and leave it for 20 minutes. Has it come on? ',
221, 222),
221: ('Are there any more problems? ', 222, 2212),
222: ('Is the screen cracked? ', 2221, 2222),
2212: 'Thank you for using my troubleshooting program!',
2221: 'Replace in a shop.',
2222: 'Take it to a specialist.'
}
# These are possible answers accepted for yes/no style questions.
POSITIVE = tuple(map(str.casefold, ('yes', 'true', '1')))
NEGATIVE = tuple(map(str.casefold, ('no', 'false', '0')))
def main():
"""Help diagnose the problems with the user's cell phone."""
verify(DATABASE, ROOT)
welcome()
ask_questions(DATABASE, ROOT)
def verify(database, root):
"""Check that the database has been formatted correctly."""
db, nodes, visited = database.copy(), [root], set()
while nodes:
key = nodes.pop()
if key in db:
node = db.pop(key)
visited.add(key)
if isinstance(node, tuple):
if len(node) != 3:
raise ValueError('tuple nodes must have three values')
query, positive, negative = node
if not isinstance(query, str):
raise TypeError('queries must be of type str')
if len(query) < 3:
raise ValueError('queries must have 3 or more characters')
if not query[0].isupper():
raise ValueError('queries must start with capital letters')
if query[-2:] != '? ':
raise ValueError('queries must end with the "? " suffix')
if not isinstance(positive, int):
raise TypeError('positive node names must be of type int')
if not isinstance(negative, int):
raise TypeError('negative node names must be of type int')
nodes.extend((positive, negative))
elif isinstance(node, str):
if len(node) < 2:
raise ValueError('string nodes must have 2 or more values')
if not node[0].isupper():
raise ValueError('string nodes must begin with capital')
if node[-1] not in {'.', '!'}:
raise ValueError('string nodes must end with "." or "!"')
else:
raise TypeError('nodes must either be of type tuple or str')
elif key not in visited:
raise ValueError('node {!r} does not exist'.format(key))
if db:
raise ValueError('the following nodes are not reachable: ' +
', '.join(map(repr, db)))
def welcome():
"""Greet the user of the application using the provided name."""
print("Welcome to Sam's Phone Troubleshooting program!")
name = input('What is your name? ')
print('Thank you for using this program, {!s}.'.format(name))
def ask_questions(database, node):
"""Work through the database by asking questions and processing answers."""
while True:
item = database[node]
if isinstance(item, str):
print(item)
break
else:
query, positive, negative = item
node = positive if get_response(query) else negative
def get_response(query):
"""Ask the user yes/no style questions and return the results."""
while True:
answer = input(query).casefold()
if answer:
if any(option.startswith(answer) for option in POSITIVE):
return True
if any(option.startswith(answer) for option in NEGATIVE):
return False
print('Please provide a positive or negative answer.')
if __name__ == '__main__':
main()
我需要添加什麼代碼?並btw非常感謝你 –
將邏輯分成單獨的問題,你可以單獨調用。 – poke
可以請你這樣做,我會非常感謝 –