【发布时间】:2017-10-01 05:03:52
【问题描述】:
puzzle gameValueError 的一些输入。谁能帮我解决一下,好吗?
def update_letter_view(puzzle: str, view: str, index: int, letter: str) -> str:
>>>"""Return a single character string representing the next view of the
character at the given index.If the character at that index
of the puzzle matches the guess, then return that character. Otherwise,
return the character at that index of the view.
>>>update_letter_view('chicken', 'ch^^ken', 2, 'i')
'i'
>>>update_letter_view('banana', 'b^n^n^', 1,'t')
'^'
"""
symbol = '^'
if letter in puzzle:
return puzzle[puzzle.index(letter, index)]
return symbol
【问题讨论】:
-
请展示运行代码的示例。哪些输入会导致 ValueError?
-
@Code-Apprentice 嗨,我在帖子开头上传了一张图片。这是一个演示,展示了此代码打算如何工作。代码实际上是我整个项目的一部分。当我输入 S 时(如果我的拼图在图片中相同),那么我会得到 ValueError。
-
这不只是检查
letter是否在puzzle的索引index上吗?如果是这样,更直观的方法是if puzzle[index] == letter: return letter。检查字母是否在拼图中没有任何帮助 - 仅仅因为它存在并不意味着它在正确的索引处。 -
@Mark 如果向函数调用传递了错误的索引(即 index > len(puzzle))怎么办?
-
@HuyVo 我并不是说这是完整的解决方案。那将类似于this。可以改用 try-catch 块或处理此函数之外的异常。
标签: python python-3.x