I am writing a code from Hackerrank and the code is given as
def miniMaxSum(arr):
minsum,maxsum=0
arr.sort()
for i in range(4):
minsum+=arr[i]
print(minsum)
for j in range(1,5):
maxsum+=arr[i]
print(maxsum)
if __name__ == '__main__':
arr = list(map(int, input().rstrip().split()))
miniMaxSum(arr)
we are supposed to find the min sum and max sum out of 4 elements out of the five but it gives me following error
Traceback (most recent call last):
File "solution.py", line 24, in <module>
miniMaxSum(arr)
File "solution.py", line 11, in miniMaxSum
minsum,maxsum=0
TypeError: 'int' object is not iterable
I am using range function properly still I am getting the error.
答案 0 :(得分:0)
You get this error cause by doing minsum, maxsum = 0
.
You have to use a sequence (list, tuple, dict or range for example). Python will iterate on it then attribute corresponding values to the variables. Of course, the left and right side must have the same number of elements. If there is only one, it have to be a sequence.
As comments told you, you can do minsum, maxsum = 0, 0
.
Range() is not involved, of course.
In addition to that, you can do this :
for value in arr[:4]:
minsum += value
for value in arr[1:]:
maxsum += value
It's better than using range and index. And I suggest you to follow the PEP8 recommendation for function name (mini_max_sum
instead of miniMaxSum
: PEP8 function and variable names
Function names should be lowercase, with words separated by underscores as necessary to improve readability.
Variable names follow the same convention as function names.
mixedCase is allowed only in contexts where that's already the prevailing style (e.g. threading.py), to retain backwards compatibility.