Reputation: 39
Given that a list, has N
elements. Suppose i
represents the i
th element of list_1
with all elements initially 0. Also there is a list:
a = [ 1 , 2 , 3, 4, ., . , N]
I need to increment elements in list_1
by 1, which are in the range [x-y , x+y]
inclusive, where y
is the i
th element of list a
.
I tried list comprehension, but could not come up with a possible way of doing it. I am new to python so I couldn't think about any other possible way!
Sample Input:
list_1 = [ 0, 0, 0, 0, 0]
a = [ 1, 2, 3, 4, 5]
Sample Output:
list_1 = [5, 5, 4, 4, 3]
Example: The problem asks to increment elements that fall in the given range i.e. say x-y= 0
and x+y = 4
, it means increment 0th
, 1st
, 2nd
, 3rd
and 4th
element of the list.
I would like to know a way to get the desired list, and overcoming the errors.
Upvotes: 0
Views: 1299
Reputation: 3406
I think this is what you are looking for. This will increment in the range of indices x-y
to x+y
.
list_1 = list(range(10))
def incList(ls, x, y):
return [e + 1 if x-y <= i <= x+y else e for i, e in enumerate(ls)]
print(incList(list_1, x=3, y=2))
print(incList(list_1, x=3, y=4))
Output:
[0, 2, 3, 4, 5, 6, 6, 7, 8, 9]
[1, 2, 3, 4, 5, 6, 7, 8, 8, 9]
You can use enumerate
to check the index and manipulate the element value in a single list comprehension.
Alternatively, if you want to iterate from the x-y
th element to the x+y
th element, use x-y-1 <= i <= x+y-1
in the list comprehension instead.
The original question suggested that a copy of the list with incremented values is fine, but the comments suggest otherwise. In order to change the original list directly, we can make a small alteration to the function.
def incList(ls, x, y):
for i in range(max(0, x-y), min(len(ls), x+y+1)):
ls[i] += 1
As before, change x-y
and x+y+1
to x-y-1
and x+y
if desired.
Upvotes: 3