我目前正在从破解编码面试的书中解决这个问题:
9.3。数组A [0 ... n-1]中的魔术索引被定义为这样的索引 A [i] = i。给定一个不同整数的排序数组,编写一个方法来查找 魔术索引(如果存在),在数组A中。
这是我的代码:
def magic_index(seq, start = None, end = None):
if start is None:
start = 0
if end is None:
end = len(seq) - 1
if start > end:
return -1
index = (start + end) // 2
if index == seq(index):
print("Equal to index. Value of index = " + index)
return index
if index > seq[index]:
print("Greater than loop. Value of Index =" + index)
return magic_index(seq, start=index + 1, end=end)
else:
print("Else part of Greater. Value of index = " + index)
return magic_index(seq, start=start, end=index - 1)
def main():
magic_index(seq=[1, 2, 3, 4, 6], start=None, end=None).
但是,当我运行我的代码时。我没有得到正确的输出。我能得到任何帮助或建议吗?提前致谢
答案 0 :(得分:2)
修复语法错误后,您的代码对我有用,即:
[]
而不是()
%
而不是+
修复后,以下工作正如我所料:
def magic_index(seq, start = None, end = None):
if start is None:
start = 0
if end is None:
end = len(seq) - 1
if start > end:
return -1
index = (start + end) // 2
if index == seq[index]: # array indexing with `[]` not `()`
print("Equal to index. Value of index = %s" % index) # use % to print index
return index
if index > seq[index]:
print("Greater than loop. Value of Index = %s" % index)
return magic_index(seq, start=index + 1, end=end)
else:
print("Else part of Greater. Value of index = %s" % index)
return magic_index(seq, start=start, end=index - 1)
def main():
result = magic_index(seq=[1, 2, 3, 4, 6], start=None, end=None)
if result == -1:
print('No Result Found!')
输出为No Result Found
,这对于提供的数组是正确的。
print magic_index(seq=[0, 1, 2, 3, 4, 5], start=None, end=None)
# prints 2
print magic_index(seq=[0, 2, 4, 6], start=None, end=None)
# prints 0
答案 1 :(得分:0)
修正了语法错误,试试这个:
def magic_index(seq, start = None, end = None):
if start is None:
start = 0
if end is None:
end = len(seq) - 1
if(start > end or start < 0 or end >= len(seq)):
return -1
index = (start + end) // 2
if(seq[index] == index):
print("Equal to index. Value of index = %d" % index)
return index
if(seq[index] < index):
print("Greater than loop. Value of Index = %d" % index)
return magic_index(seq, index + 1, index)
return magic_index(seq, start, index - 1)