使所有数组元素在Python中相等所需的操作数

我们给定了一个元素数组,我们必须通过将元素递增1来使它们全部相等。我们被允许在每一步中递增n-1元素。我们的目标是计算使所有数组元素相等所需的操作总数。

例如,如果采用列表[1、2、3],则需要进行三个操作才能使所有元素相等。解决该问题的一种方法是。在每个步骤中找到最重要的数字,并将其余元素加1。让我们编写代码。

示例

def main():
   # intializing the array
   arr = [1, 2, 3]
   # initializing operations count to 0
   no_of_operations = 0
   flag = 0
   # performing the operations on array to make them equal
   while not are_equal(arr):
      flag = 1
      # finding the maximum from the list
      maximum = max(arr)
      # incrementing all the elements except maximum
      for i in range(len(arr)):
         if arr[i] != maximum:
            arr[i] += 1
      # incrementing the operations count by 1
      no_of_operations += 1
   print(no_of_operations) if flag == 0 else print(no_of_operations + 1)
# checking whether all the elements are equal or not
def are_equal(arr):
   global no_of_operations
   for i in range(len(arr) - 1):
      if arr[i] != arr[i + 1]:
         return False
   return True
if __name__ == '__main__':
   main()

输出结果

如果运行上面的程序,您将得到以下结果。

3

上面的方法需要更多的时间来计算大型数组。我们可以通过求和和数组的最小元素来找到操作数。

  • 查找数组的总和。

  • 查找数组中所有元素中的最小元素。

  • 打印从表达式sum- (length-smallest)得到的值。

示例

请参见下面的代码。

# initializing an array
arr = [1, 2, 3]
# length
length = len(arr)
# sum of element fo the array
elements_sum = sum(arr)
# smallest among all the elements
smallest = min(arr)
# calculating the number of operations
print(elements_sum - (length * smallest))

输出结果

如果运行上面的代码,您将得到以下结果。

3

结论

与第一种方法相比,我们讨论的第二种方法更容易且耗时更少。如果您对本教程有任何疑问,请在评论部分中提及。