Max Lobur
Max Lobur

Reputation: 6040

Increase each list element in all possible ways

I have a list: test = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]

Need to increase each list element in all possible ways using Python standard library. It's a puzzle, and I've already done this:

test = [elem + 1 for elem in test]

for i in range(len(test)): test[i] += 1

test = map(lambda x : x + 1, test)

test = [sum(elem) for elem in zip(test, [1]*len(test))]

Any others ideas?

Upvotes: 3

Views: 7411

Answers (3)

agf
agf

Reputation: 176910

You could use recursion, (and you could use True and False instead of 1 and 0, but that's just crazy talk):

def recurseadd(test):
    if test:
        return [test[False] + True] + recurseadd(test[True:])
    else:
        return test

Instead of that + you could use [test[0] + 1].extend(recurseadd(test[1:])).

You coud use operator.add instead of +, with functools.partial and itertools.imap if you wanted:

from functools import partial
from operator import add
from itertools import imap

addone = partial(add, 1)

test = list(imap(addone, test))  # don't really use imap if you want a list

You could use itertools's izip and repeat:

test = [sum(elem) for elem in izip(test, repeat(1))]

Another method with sum, inspired by Eren's comment to GWW's answer:

test = sum(([x+1] for x in test), [])

Yyou could use xrange instead of range, you could use itertools.count(1).next() to generate the 1s...

There are an infinite number of minor variations, but your three plus the recursive version seem to cover the basic ones. Eren's reduce version is nice too.

Upvotes: 3

unutbu
unutbu

Reputation: 880289

In [23]: import operator

In [24]: import itertools

In [25]: list(itertools.starmap(operator.add,zip(test,itertools.repeat(1))))
Out[25]: [2, 3, 4, 5, 6, 7, 8, 9, 10, 1]

In [26]: list(itertools.imap(operator.add,test,itertools.repeat(1)))
Out[26]: [2, 3, 4, 5, 6, 7, 8, 9, 10, 1]

In [30]: list(itertools.starmap(operator.add,itertools.izip_longest(test,[],fillvalue=1)))
Out[30]: [2, 3, 4, 5, 6, 7, 8, 9, 10, 1]

Upvotes: 2

GWW
GWW

Reputation: 44131

I thought of two using pythons reduce function, however, they are similar to what you have already done.

>>> [reduce(lambda x,y: x + y, l) for l in zip(li, [1]*len(li))]
[2, 3, 4, 5, 6, 7, 8, 9, 10, 1]
>>> [reduce(lambda x,y: x + y, (z,1)) for z in li]
[2, 3, 4, 5, 6, 7, 8, 9, 10, 1]

Upvotes: 1

Related Questions