Reputation: 1447
I am trying to check if 2 elements in a list are incrementing by 1.
For instance, in a list like this [1,3,4,5,6,7,9,11,12]
, my code should return a new list like this [3,4,5,6,11,12]
This is my code:
same = [1,3,4,5,6,7,9,11,12]
new_datalist = []
index = 0
for k in same:
try:
new_index = index+1
if k+1 == same[new_index]:
new_datalist.append(k)
new_datalist.append(k+1)
index += 1
except:
pass
new_datalist
But it is returning this - [3, 4, 4, 5, 5, 6, 6, 7, 11, 12]
How do I solve this?
Just to explain further:
Let's look at it like this, elements in the list represents the monthly salary of a worker. I want to check if the worker receives half-salary for 2 consecutive months. For example, a list like this [3,4,5,6,7,8,1,44]
would return a list like [3,4,5,6,7,8]
. This means the worker receives half-salary for months 3&4, 5&6 and 7&8
Upvotes: 0
Views: 48
Reputation: 11
Here.
same = [1,3,4,5,6,7,9,11,12]
output = []
i = 0
while i < len(same) - 1:
if same[i] + 1 == same[i + 1]:
output.extend([same[i], same[i + 1]])
i += 2
else:
i += 1
print(output)
Upvotes: 0
Reputation: 51683
You need to fix the algorythm - currently you are adding twice.
You can use zip() to solve it:
same = [1,3,4,5,6,7,9,11,12]
# create pairs: [ (1,3),(3,4),(4,5),(5,6),(7,9),(9,11),(11,12),(12,12) ]
z = zip(same, same[1:]+same[-1:])
r =[]
# take pairs into a,b
for a,b in z:
if r and r[-1] == a: # if we added a already, skip it
continue # last run added 3 and 4, now it checks 4 and 5: skip
if a==b-1: # if a is b-1 add both
r.append(a)
r.append(b)
print(r) # [3, 4, 5, 6, 11, 12]
To look for stringently raising numbers, use:
same = [1,3,4,5,6,7,9,11,12]
a = iter(same)
b = iter(same)
next(b)
r = []
while a and b:
aa = next(a)
try:
bb = next(b)
if aa == bb-1:
r.append(aa)
elif r and r[-1] == aa-1:
r.append(aa)
except StopIteration:
if bb-1== r[-1]:
r.append(bb)
break
print(r) # [3, 4, 5, 6, 7, 11, 12]
Upvotes: 1