-1

I'm dealing with such script in python:

In the input I have such array:

a = [2,4,7,2]

On the output I need to return elements of the array, starting with the first one

[2]
[2, 4]
[2, 4, 7]
[2, 4, 7, 2]

How can I retrieve elements, starting with the second and further elements:

//start with a[1]
[4]
[4, 7]
[4, 7, 2]

//start with a[2]
[7]
[7,2]

//start with a[3]
[2]

So, by now my code is looking like this:

def ar(a):
    result = 0
    res_arr = []
    for i in a:
        res_arr.append(i)
        k = sum(res_arr)
        print (res_arr,k)

but I understand, that I need to add external loop, for going through all elements of the array. What is the most efficient way for writing it?

Daniel Chepenko
  • 2,229
  • 7
  • 30
  • 56
  • Do you want the lists starting with the second and further elements in the output, or is that your current strategy for producing the result in the second code block? – TigerhawkT3 Oct 30 '16 at 09:43

3 Answers3

3

In Python you can use slicing (see this question for details).

For example,

for i in range(1, len(a) + 1):
    print(a[:i])

will output

[2]
[2, 4]
[2, 4, 7]
[2, 4, 7, 2]

To start with nth element you can use this code:

n = 1  # Start with second element (list indexes start with 0)
for i in range(n + 1, len(a) + 1):
    print(a[n:i])

which will output:

[4]
[4, 7]
[4, 7, 2]
Community
  • 1
  • 1
Franz Wexler
  • 1,112
  • 2
  • 9
  • 15
1

Just loop over a range of values to use in a slice:

def ar(a):
    for i in range(1, len(a)+1):
        print(a[:i])

Result:

>>> ar([1,2,3])
[1]
[1, 2]
[1, 2, 3]

You can start at an arbitrary index by simply adding it in a few key places:

def ar(a, start):
    for i in range(1+start, len(a)+1):
        print(a[start:i])

Result:

>>> ar([1,2,3], 1)
[2]
[2, 3]
TigerhawkT3
  • 48,464
  • 6
  • 60
  • 97
  • This is not the question. Daniel is asking how to print the array from the second or further element. – Hugal31 Oct 30 '16 at 09:30
  • @Hugal31 - OP says "I need to return elements of the array, starting with the first one." I think the part about starting from the second element is part of his attempt at a solution. That attempt has a function that _only takes one argument_ - the list. There is no way for that function to start at an index of the user's choosing. Of course, it's trivial to add, and I'll do so. – TigerhawkT3 Oct 30 '16 at 09:35
0

You can use the slices.

With you code:

def ar(a, start=0):
    result = 0
    res_arr = []
    for i in a[start:]:
        res_arr.append(i)
        k = sum(res_arr)
        print (res_arr,k)

With a more pythonic code:

def ar(a, start=0):
    for i in range(start + 1, len(a) + 1):
        print(a[start:i], sum(a[start:i]))
Hugal31
  • 1,610
  • 1
  • 14
  • 27