python - 找出数组中最大的元素是否至少是数组中其他每个数字的两倍?

标签 python arrays list

我正在尝试运行一个程序,该程序查找比数组中所有其他数字至少大两倍的数字的索引。

这是我的代码

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/

相关文章:

java - 如何区分同一个整数对象?

python - 如何在python中将对象列表转换为json格式

python - 有没有办法用python自动化/脚本视频编辑?

python - 使用 Keras 和 Python 进行一类分类

javascript - 遍历二维数组并找到 "enclosed rooms"

C++ 多线程数组

list - 在 Prolog 中将元素附加到列表的开头

Python 正则表达式首先找到 '&'

python - 将推文创建时间转换为 UTC

javascript - 有没有办法防止字符串表现得像多维数组?