'Unexpected Output error in array analyzer program
Currently I am trying to solve the following problem:
Ratiorg got statues of different sizes as a present from CodeMaster for his birthday, each statue having an non-negative integer size. Since he likes to make things perfect, he wants to arrange them from smallest to largest so that each statue will be bigger than the previous one exactly by 1. He may need some additional statues to be able to accomplish that. Help him figure out the minimum number of additional statues needed.
Example
For statues = [6, 2, 3, 8], the output should be
solution(statues) = 3.
Ratiorg needs statues of sizes 4, 5 and 7.
To solve this, I have written the code below. In this example, the output should be 3, but for some reason it is 2. I don't have experience using the debugger in my IDE, so it is difficult to tell what the problem is. I'm assuming it has something to do with the way I'm handling variables in my loops but I am not sure. Any help would be much appreciated.
def solution(statues):
statues.sort()
n = 0
needed = 0
additor = 1
while n < len(statues) - 2:
if (statues[n] + 1) == statues[n+1]:
n+=1
else:
while (statues[n] + additor) != statues[n+1]:
needed +=1
additor +=1
n+=1
additor = 0
print(needed)
return needed
statues = [6, 2, 3, 8]
solution(statues)
Solution 1:[1]
I have this solution
def solution(statues):
return len([i for i in range(min(statues), max(statues) +1)]) - len(statues)
statues = [6, 2, 3, 8]
print(solution(statues))
Solution 2:[2]
def solution(statues):
statues.sort()
if len(statues) > 1:
difference = [y-x for x, y in zip(statues[:-1], statues[1:])]
return sum(i-1 for i in difference)
else:
return 0
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Peterrabbit |
Solution 2 | zapa |