我目前正在上edX课程中的计算机科学课程,而在其中一项递归练习中,我陷入了这个问题。我已经在“纸”上检查了几次代码,但看不到它是怎么回事。
概括地说,问题如下: 使用二等分搜索方法,找出字符串(aStr)中是否存在isIn(char,aStr)函数中的char
这是我编写的代码:
def isIn(char,aStr):
aStrSorted = sorted(aStr)
if len(aStrSorted)==0:
print('The string you have given to me is empty')
if len(aStrSorted)==1:
print('The character you are looking for is in the ' + str(aStrSorted))
if char == aStrSorted[len(aStrSorted) // 2]:
print('The character you are looking for is in the string ' + str(aStrSorted))
elif char<aStrSorted[len(aStrSorted) // 2]:
return isIn(char,aStrSorted[0:len(aStrSorted)//2])
elif char>aStrSorted[len(aStrSorted) // 2]:
return isIn(char, aStrSorted[len(aStrSorted) // 2:-1])
else:
print('The character you are looking for is not in the string ' + str(aStrSorted))
isIn('f', 'abcdegghkl')
错误消息是:
Traceback (most recent call last):
The string you have given to me is empty
File "C:/Users/abkk1l/PycharmProjects/edX/edX-2.py", line 29, in <module>
isIn('f', 'abcdegghkl')
File "C:/Users/abkk1l/PycharmProjects/edX/edX-2.py", line 22, in isIn
return isIn(char,aStrSorted[0:len(aStrSorted)//2])
File "C:/Users/abkk1l/PycharmProjects/edX/edX-2.py", line 24, in isIn
return isIn(char, aStrSorted[len(aStrSorted) // 2:-1])
File "C:/Users/abkk1l/PycharmProjects/edX/edX-2.py", line 24, in isIn
return isIn(char, aStrSorted[len(aStrSorted) // 2:-1])
File "C:/Users/abkk1l/PycharmProjects/edX/edX-2.py", line 18, in isIn
if char == aStrSorted[len(aStrSorted) // 2]:
IndexError: list index out of range
答案 0 :(得分:1)
鉴于isIn()
是谓词函数名称(应返回True
或False
),并且对字符串进行排序(并且不必要地对所有排序后的字符串的子字符串进行排序)似乎是过分的,我可能是您误解了这个问题,并提出了一个更简单的解决方案,例如:
def isIn(char, aStr):
length = len(aStr)
if length == 0:
return False
if length == 1:
return aStr[0] == char
halfway = length // 2
return isIn(char, aStr[:halfway]) or isIn(char, aStr[halfway:])
if isIn('f', 'abcdefghkl'):
print('The character you are looking for is in the string')
else:
print('The character you are looking for is not in the string')