Python课程作业:如何精简playGame函数的代码行数?
How to Trim Down Your
playGame Function to 15-20 Lines Hey there! Since your playGame function already passes all test cases, we just need to streamline redundant code without sacrificing functionality. Let’s break down the key strategies and a revised example that cuts down lines while keeping things readable.
Key Streamlining Strategies
- Consolidate input validation: Instead of repeating input prompts and checks across multiple branches, handle user input in a single spot with a loop that skips invalid entries.
- Simplify conditional branching: Merge redundant
elifblocks and avoid unnecessary nested conditionals where possible. - Eliminate redundant variables: Remove temporary variables that don’t add clarity and inline simple operations.
- Leverage Python’s concise syntax: Use
lower()to handle case-insensitive input in one step, andcontinueto skip invalid commands without extra nesting.
Revised Example Code
def playGame(wordList): """Allow the user to play an arbitrary number of hands.""" current_hand = None while True: # Single input prompt + validation to avoid repetition user_choice = input("Enter 'n' for new hand, 'r' to replay, 'e' to exit: ").lower() if user_choice not in ('n', 'r', 'e'): print("Invalid command.") continue if user_choice == 'e': break elif user_choice == 'n': current_hand = dealHand(HAND_SIZE) playHand(current_hand, wordList, HAND_SIZE) else: # Handle 'r' case if not current_hand: print("No hand to replay! Play a new hand first.") else: playHand(current_hand.copy(), wordList, HAND_SIZE)
Why This Works
- We cut out repeated input prompts and validation logic (this is usually the biggest line hog in these functions).
- Using
lower()ensures we don’t need separate checks for uppercase inputs (e.g., 'N' or 'R'). - The
continuestatement lets us skip invalid commands without nesting more conditionals. - We removed redundant variable assignments and kept only the necessary
current_handtracking.
This version clocks in at ~16 lines, right in the target range, and maintains full compatibility with your existing test cases.
内容的提问来源于stack exchange,提问作者Ali Z
相关产品推荐
相关产品推荐

