Accumulating lists with letters
I am trying to change the code that accumulates a list. The code I guessed so far does this, but I want it to work with emails, for example. ("a", "b", "c") will exit as a, ab, abc.
def accumulate(L):
theSum = 0
for i in L:
theSum = theSum + i
print(theSum)
return theSum
accumulate([1, 2, 3])
source to share
While @WillemVanOnsem has provided you with a method that will work to shorten your code, you can use itertools.accumulate
from the standard library
>>> from itertools import accumulate
>>>
>>> for step in accumulate(['a', 'b', 'c']):
print(step)
a
ab
abc
>>>
source to share
If you want it to work on strings, you must initialize it with an empty string :
def accumulate(*args):
theSum = ''
for i in args:
theSum += i # we can here shorten it to += (kudos to @ChristianDean)
print(theSum)
return theSum
Also, if you want to use an arbitrary number of arguments, you must use *args
(or *L
).
Now, of course, this won't work with numbers anymore. theSum += i
here is shorthand for theSum = theSum + i
(since strings are immutable). Note, however, that this is not always the case: there is a difference for lists, for example.
Now it prints:
>>> accumulate("a", "b", "c")
a
ab
abc
'abc'
The latter is 'abc'
not the result of an operator print(..)
, but they are return
functions accumulate
.
source to share
You can try this:
import string
l = string.ascii_lowercase
the_list = []
letter = ""
for i in l:
letter += i
the_list.append(letter)
Even better in a function with a generator:
def accumulation():
l = string.ascii_lowercase
letter = ""
for i in l:
letter += i
yield letter
the_letters = list(accumulation())
print(the_letters)
Output:
['a', 'ab', 'abc', 'abcd', 'abcde', 'abcdef', 'abcdefg', 'abcdefgh', 'abcdefghi', 'abcdefghij', 'abcdefghijk', ...]
source to share