I'm making a program which completes the following:
When inputted a list a
, it will subtract consecutive elements (starting from the beginning) if the results are non-negative numbers.
For example, if
a=[3,2,1]
then consecutive numbers will be subtracted, so a=[1,1]
, and then a=[0]
. Also, in the result, all numbers must be ascending (for example a 2,1
cannot be in the list). Another example:
a=[1, 10, 7, 3, 2]
[1, 3, 3, 2] #10-7 (10 and 7 get replaced with 3)
[1, 0, 2] #3-3 (precedence goes to the left: 3-3 gets subtracted, not 3-2)
[1, 2] #1-0
Here is my current code (where a is being generated randomly):
import random
a=[random.randint(1,10) for e in range(20)]
print(a)
loop=1
while True:
try:
#print(loop,a)
subloop=0
while subloop<loop:
if a[loop-subloop]<=a[loop-1-subloop]:
a[loop-1-subloop]=a[loop-1-subloop]-a.pop(loop-subloop)
if loop!=1:
loop-=1
subloop+=1
if a[loop]<=a[loop-1]:
a[loop-1]=a[loop-1]-a.pop(loop)
else:
loop+=1
except IndexError:
break
print(a)
This code feels kind of long/ineffiecient. Is there a better or more short/efficient way to do this?
Here's my take on it:
a = [1, 10, 7, 3, 2]
b = [3, 2, 1]
def index_helper(l):
for i, x in enumerate(l[:-1]):
if l[i] >= l[i+1]:
return i
def reduce(l):
i = index_helper(l)
while i is not None:
l[i:i + 2] = [l[i] - l[i + 1]]
i = index_helper(l)
return l
>>> reduce(a)
[1, 2]
>>> reduce(b)
[0]