我正在做 Hackerrank 基本的 Python 編程挑戰。這個叫做Mini-Max Sum * 問題的鏈接是:https ://www.hackerrank.com/challenges/one-week-preparation-kit-mini-max-sum/problem?isFullScreen=true&h_l=interview&playlist_slugs []=preparation-kits&playlist_slugs[]=one-week-preparation-kit&playlist_slugs[]=one-week-day-one
我能夠為示例案例編譯我的代碼,但它不適用于任何其他案例。我很困惑為什么會收到運行時錯誤。請幫忙!
#!/bin/python3
import math
import os
import random
import re
import sys
#
# Complete the 'miniMaxSum' function below.
#
# The function accepts INTEGER_ARRAY arr as parameter.
#
def miniMaxSum(arr):
# Find the minimum number:
minimum = 10^9
for integer in arr:
if integer < minimum:
minimum = integer
# Search the list to find the minimum and remove it:
arr.remove(minimum)
# Sum all of the entries in the array; this gives the maximum sum for four integers:
max_sum = 0
for number in arr:
max_sum = number
# --------------------------------------------------------
arr.append(minimum)
# Find the maximum number:
maximum = 1
for integer in arr:
if integer > maximum:
maximum = integer
# Search the list to find the maximum and remove it:
arr.remove(maximum)
# Sum all of the entries in the array; this gives the maximum sum for four integers:
min_sum = 0
for number in arr:
min_sum = number
print(min_sum, max_sum)
if __name__ == '__main__':
arr = list(map(int, input().rstrip().split()))
miniMaxSum(arr)
uj5u.com熱心網友回復:
問題出在函式的第一行miniMaxSum()。
def miniMaxSum(arr):
# Find the minimum number:
minimum = 10^9
^表示異或運算不是冪/冪。改為在 python 中使用**。
10^9 = 3(二進制1010 ^ 1001 = 0011)。因此,您minimum使用 3 而不是 1000,000,000 進行初始化
那為什么會出現運行時錯誤?
arr.remove(minimum)
minimum= 3 可能不存在于arr.
您的問題鏈接已過期,最好包含該宣告。當前問題鏈接:https ://www.hackerrank.com/challenges/mini-max-sum/problem
陳述:
給定五個正整數,找出可以通過將五個整數中的四個恰好相加來計算的最小值和最大值。然后將各自的最小值和最大值列印為單行的兩個空格分隔的長整數。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/438424.html
標籤:数组 python-3.x for循环 最大限度 分钟
