我正在尝试运行一个程序,该程序查找比数组中所有其他数字至少大两倍的数字的索引。
这是我的代码
def dominantIndex(self, nums):
max_num = max(nums)
max_i =nums.index(max_num)
if len(nums) == 1:
return nums.index(max_num)
for num in nums:
if max_num >= 2*num:
return num.index(max_num)
return -1
但是,它并不适用于所有输入。有人可以修复它并检查输入,例如:
[1,0]
[0,3,4,8]
[0,3,5,2]
最佳答案
这会检查许多可能的输入问题。
然后它会对列表进行排序以获得您正在寻找的答案。为简单起见,我决定进行排序,但您也可以使用其他方法。我添加了注释,以便一切都清楚,特别是按照要求进行输入测试。
def dominantIndex(nums):
# If the array is empty or None or not a list, return -1
if not nums or type(nums) != list:
return -1
# If the array is of length 1, return the only index, 0
elif len(nums) == 1:
return 0
sorted_numbers = sorted(nums)
# If the highest number is twice the second largest, return it's index
if sorted_numbers[-2] * 2 <= sorted_numbers[-1]:
return nums.index(sorted_numbers[-1])
else:
return -1
关于python - 找出数组中最大的元素是否至少是数组中其他每个数字的两倍?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50543265/