How to repeat an element in a list by the number of times that is the magnitude of that element

Viewed 89

The question I am trying to answer is this: Create a function numstack(n) that returns a list of integers from 1 to n (inclusively) but where each integer mm in the list appears, consecutively, a total of mm times, so that, for example: numstack(4) = [1,2,2,3,3,3,4,4,4,4]

So far my best attempt has been:

def numstack(n):
for i in range(1,n+1):
    z = [i]*i
            
return z

print(numstack(3))

But this is far from correct, any ideas of how to do this?

4 Answers

You can use a nested list comprehension to get what you want. You already seem to know what [i]*i does.

def numstack(n):
    return [j for i in range(1, n + 1) for j in [i]*i]


print(numstack(4))

Output

[1, 2, 2, 3, 3, 3, 4, 4, 4, 4]

From the comments a better approach would be to write the comprehension as return [i for i in range(1, n + 1) for j in range(i)]

You need to use one more loop like this:

def numstack(n):
    result = []  # we put results here
    for i in range(1, n + 1):  # for each number <1,n>
        for _ in range(1, i + 1):  # repeat i times
            result.append(i)  # insert "i" to the result list
    return result

print(numstack(5))

Using [i]*i construction:

def numstack(n):
    res = []
    for i in range(1, n + 1):
        res += [i] * i
    return res

print(numstack(5))

Your attempt is not so bad, we can extend it to arrive at the solution.

def numstack(n): 
     result = [] 
     for i in range(1,n+1): 
         z = [i]*i 
         result.extend(z) 
          
     return result 

Shorter solution with itertools:

from itertools import chain                                                                                                                                                                                                        
def numstack(n): 
     return list(chain.from_iterable([i]*i for i in range(1, n + 1))) 

This should solve it for you:

def numstack(n):
    num = []
    for i in range(1, n+1):
        data = []
        data.append(i)
        num.append(data * i)
    result = [item for sublist in num for item in sublist]
    return result
Related