Given an odd length list of values in Python, how can I swap all values other than the final value in the list? -


in regards python 2.7.12 (disclaimer: understand python2 being phased out python3, course i'm taking started here, perhaps understand older code bases):

i have list of integers whom i'd swap each neighboring value. far, works great lists in number of integers contain, when list length odd, it's not easy swap each value, number of integers uneven.

giving following code example, how can swap values other final value in list?

arr = [1, 2, 3, 4, 5]  def swaplistpairs(arr):     idx, val in enumerate(arr):         if len(arr) % 2 == 0:             arr[idx], arr[val] =  arr[val], arr[idx]  # traditional swap using evaluation order         else:             arr[0], arr[1] = arr[1], arr[0]  # line not solution know need conditions swap list values other len(arr)-1, not sure how this?     return arr  print swaplistpairs(arr) 

bonus points ultimate pythonic master: how can code modified swap strings? right now, can use function using integers , curious how can make work both int , str objects?

thank insight or suggestions point me in right direction! everyone's @ times here has been invaluable , thank reading , help!

here's shorter, faster way based on slice assignment:

def swap_adjacent_elements(l):     end = len(l) - len(l) % 2     l[:end:2], l[1:end:2] = l[1:end:2], l[:end:2] 

the slice assignment selects elements of l @ indices (l[:end:2]) or odd indices (l[1:end:2]) , excluding index end, uses same kind of swapping technique you're using swap slices.

end = len(l) - len(l) % 2 selects index @ stop. set end closest number less or equal len(l) subtracting len(l) % 2, remainder when len(l) divided 2.

alternatively, have done end = len(l) & ~1, using bitwise operations. construct integer use mask (~1), 0 in 1 bit , 1s everywhere else, apply mask (with &) set 1 bit of len(l) 0 produce end.


Comments