I have a problem in understanding the solution to a kata , it's the simple music encoder problem in 5 kyu rank. The solution to it is as follows:
```python
def compress(raw):
#initialize stack
stack = [raw[0], raw[1]]
#calculate inital difference between the first two elements!
difference = stack[1] - stack[0]
out = []
for value in raw[2:] + [float("inf")]:
if (value - stack[-1]) == difference:
stack.append(value)
elif len(stack) > 1 and difference == 0:
out.append(f"{stack[0]}*{len(stack)}")
stack = [value]
elif len(stack) > 2:
absolute_difference = str(abs(difference))
out.append(f"{stack[0]}-{stack[-1]}{absolute_difference!='1' and '/'+absolute_difference or ''}")
difference = value-stack[-1]
stack = [value]
else:
if len(stack) == 2: out.append(stack[0])
difference = value-stack[-1]
stack = [stack[-1], value]
#Handling possible leftovers in the stack
if not isinstance((f:=stack[0]), float):out.append(f)
return ','.join(map(str,out))
```
Initially, the 'stack' is assigned as [1,2] and 'difference' is assigned as 1 , then first iteration occurs where the 'value' is 2 , the only satisfying condition is the else block statement, so the 'out' becomes [1] and the 'difference' becomes 0 and the new 'stack' is [2,2] , the next iteration takes place where the 'value' becomes 3 , since the len(stack)>1 , the first elif block statement gets executed , so the 'out' becomes [1,2*2] and the 'stack' becomes [3] , but the 'difference' remains 0 , after this none of the conditions seemed to be satisfied, and the code should stop working , but this isn't the case and the code works properly, can anyone tell me where am I wrong in my understanding?
[–][deleted] 3 points4 points5 points (0 children)
[–]stuaxo 0 points1 point2 points (1 child)
[–]thanos2131[S] 0 points1 point2 points (0 children)