0

Here's the problem:

Given a list of integers, make it so that the first and last integers are added and that result will be the first integer of the new list, the second and second-to-last integers are added and the result will be the second integer of that new list and so on. if your list is odd, leave the central number in the original list.

Two problems I'm having. I don't know how to get my code to keep iterating while taking the first and last values, adding it to the new list, and working it's way to the middle. Also how do I get it to iterate and stop at a middle value if it's odd?

Here's my code so far:

myList = [1,2,3,4,5,6]
newList = []

def switch(myList):
    for i in range(len(myList)):
        if len(myList) % 2 == 0:
            firstPart = newList+myList[0:+1]
            secondPart = myList[len(myList)-1:len(myList)+1]
            thirdPart = firstPart + secondPart
            return thirdPart
        else:
            if len(myList) % 2 == 1:
MLW
  • 21
  • 3
  • You may wish to consult [this question](http://stackoverflow.com/questions/36533553/cycle-a-list-from-alternating-sides/36533770#36533770) for a nice way to simplify your task. – Akshat Mahajan May 29 '16 at 17:58

3 Answers3

4

Update: After going through all the zipping, summing, mapping, slicing and reversing, this solution struck me as surprisingly simple, actually:

def switch(my_list):
    new_list = my_list[:]  # make a copy not to harm the original
    for i in range(len(my_list)//2):   # at the appropriate index ...
        new_list[i] += new_list.pop()  # ... add the element popped from the end
    return new_list

>>> switch([1,1,1,1])
[2, 2]
>>> switch([1,1,1,1,1])
[2, 2, 1]
user2390182
  • 72,016
  • 6
  • 67
  • 89
0
def switch(a_list):
    N = len(a_list)
    HALF = N//2

    new_list = []
    for i in range(HALF):
        j = N-i-1
        new_list.append(a_list[i] + a_list[j])
    if N % 2:
        new_list.append(a_list[HALF])

    return new_list

print(switch([1,2,3,4,5,6]))    # -> [7, 7, 7]
print(switch([1,2,3,4,5,6,7]))  # -> [8, 8, 8, 4]
martineau
  • 119,623
  • 25
  • 170
  • 301
-1
import itertools
n=len(myList)
new_list=[e+f for e, f in itertools.izip(myList[:n/2], reversed(myList)[:n/2])]

myList[:n/2] extract the first part of the list [1,2,3]
reversed(myList) reverse the initial list [6,5,4,3,2,1] then truncate using [:n/2]

Then it is possible to iterate over the two lists in the mean time using izip which makes it easy then to do what you want to do:

e,f in itertools.izip([1,2,3], [6, 5,4]) => e,f= (1,6), then (2,5) then (3,4)

In the case of an odd length, I add to add a special case:

if len(myList)%2==1:
    new_list.append(myList[n/2+1])
Dvx
  • 289
  • 2
  • 10