Skip to content

Instantly share code, notes, and snippets.

@vpetro
Created August 8, 2012 15:23
Show Gist options
  • Save vpetro/3295892 to your computer and use it in GitHub Desktop.
Save vpetro/3295892 to your computer and use it in GitHub Desktop.
add1
def add1(lst, val, n):
start, stop, step = 0, len(lst), 1
cond = n == 0
if n < 0:
start, stop = stop-1, start-1
step = -1
n = abs(n)
for idx in range(start, stop, step):
if (lst[idx] == val and n > 0) or cond:
lst[idx] += 1
n -= 1
if __name__ == "__main__":
lst = [1,4,1,5,1]
add1(lst, 1, 0)
print lst
lst = [1,4,1,5,1]
add1(lst, 1, 2)
print lst
lst = [1,4,1,5,1]
add1(lst, 1, -2)
print lst
@vpetro
Copy link
Author

vpetro commented Aug 8, 2012

def add1(lst, val, n):
    start, stop, step = 0, len(lst), 1
    n = n or len(lst)

    if n < 0:
        start, stop = stop - 1, start - 1
        step = -1
        n = abs(n)

    for idx in range(start, stop, step):
        if lst[idx] == val and n > 0:
            lst[idx] += 1
            n -= 1

if __name__ == "__main__":
    lst = [1, 4, 1, 5, 1]
    add1(lst, 1, 0)
    print lst

    lst = [1, 4, 1, 5, 1]
    add1(lst, 1, 2)
    print lst

    lst = [1, 4, 1, 5, 1]
    add1(lst, 1, -2)
    print lst

@vpetro
Copy link
Author

vpetro commented Aug 8, 2012

def add1(lst, val, n, in_place=True):
    to_update = lst
    if not in_place:
        to_update = lst

    start, stop, step = 0, len(to_update), 1
    n = n or len(to_update)

    if n < 0:
        start, stop = stop - 1, start - 1
        step = -1
        n = abs(n)

    for idx in range(start, stop, step):
        if to_update[idx] == val and n > 0:
            to_update[idx] += 1
            n -= 1

    return to_update


def add2(lst, val, n):
    return_list = []
    if n == 0:
        for i in lst:
            if i == val:
                val += 1
            return_list.apend(val)
        return return_list

    if n > 0:
        for i in lst:
            if i == val and n > 0:
                val += 1
                n -= 1
            return_list.append(val)
        return return_list

    if n < 0:
        for i in reversed(lst):
            if i == val and n < 0:
                val += 1
                n += 1
            return_list.append(val)
        return list(reversed(return_list))


if __name__ == "__main__":
    lst = [1, 4, 1, 5, 1]
    add1(lst, 1, 0)
    print lst

    lst = [1, 4, 1, 5, 1]
    add1(lst, 1, 2)
    print lst

    lst = [1, 4, 1, 5, 1]
    add1(lst, 1, -2)
    print lst

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment