Reputation: 11
Hi I have a problem with my code and I don't know how to solve it. The challenge is :"How many consecutive numbers are needed?" ... to fill an array. Example: [1, 2, 4, 6] the answer should be 2. This is what I got.
def consecutive(arr):
arr.sort()
minimum = min(arr)
maximum = max(arr)
diff = maximum - minimum - len(arr) + 1
return diff
the proble is when arr is [] then it doesnt work. What can I change about my code.
Upvotes: 0
Views: 969
Reputation: 530990
You can only compute the minimum and maximum of a non-empty list, so you have two alternatives: raise an exception if the input is empty, or provide a default value to return in the case of an empty list. (Both cases defer to the caller to decide what is needed if the list is empty, rather than forcing the function to guess at an appropriate value.)
Raise an exception.
def consecutive(arr):
if not arr:
raise ValueError("List is empty")
minimum = min(arr)
maximum = max(arr)
diff = maximum - minimum - len(arr) + 1
return diff
Provide a default
def consecutive(arr, if_empty=None):
if not arr:
return if_empty
minimum = min(arr)
maximum = max(arr)
diff = maximum - minimum - len(arr) + 1
return diff
Note that in neither case do you have to sort the list first; both min
and max
handle unsorted lists just fine.
Upvotes: 1
Reputation: 8219
Maybe I am reading too much into the question, but the answers provided so far, as well as the OP's own answer, are wrong if arr
has repeated elements such as [1,2,2,6]
. So the correct answer, 'borrowing'' error handling code from @chepner, is
def consecutive(arr):
if not arr:
raise ValueError("List is empty")
minimum = min(arr)
maximum = max(arr)
diff = maximum - minimum - len(set(arr)) + 1
return diff
Here set(arr)
returns unique elements of arr
Upvotes: 0