0

My assignment is this:

Let L be a list of non-negative integers. Write an expression that replaces the centermost element of L with that many copies of 0. Note that "centermost" here is defined the usual way for a list of odd length, but may seem a bit unusual for a list of even length. So, for example, if L = [1, 2, 3, 4, 5], the modified value of L will be [1, 2, 0, 0, 0, 4, 5], but if L = [1, 2, 0, 3], the modified value would be [1, 2, 3], as the 0 – here the centermost element of an even-length list – would be replaced with 0 copies of 0.

The expression I came up with is

L[len(L)/2] = [0] * L[(len(L)/2)]

and output for L = [1, 2, 3, 4, 5] is

[1, 2, [0, 0, 0], 4, 5]

I need to eliminate that inner list element such that the zeroes are part of the outer list. We are restricted to a single line and no for/while loops.

Dan Lowe
  • 51,713
  • 20
  • 123
  • 112

2 Answers2

1

As @saulspatz suggests use slicing:

middle = len(L) / 2
L = L[:middle] + ([0] * L[middle]) + L[middle + 1:]
Reut Sharabani
  • 30,449
  • 6
  • 70
  • 88
  • and this can obviously be done in one line per your requirements by not using the variable middle, and just using len(L)/2 where it appears. To read more on slicing I find this question super helpful: http://stackoverflow.com/questions/509211/explain-pythons-slice-notation – jdf Sep 12 '15 at 22:23
  • 1
    Actually, I meant "assign to a slice" as ekhumoro did in his answer, but this works too, of course. – saulspatz Sep 12 '15 at 23:54
  • I never knew this was possible. Thanks :-) – Reut Sharabani Sep 12 '15 at 23:55
1

Since Python 2.3, it is possible to assign to slices:

>>> L = [1, 2, 3, 4, 5]
>>> L[len(L)//2:len(L)//2 + 1] = [0] * L[(len(L)//2)]
>>> L
[1, 2, 0, 0, 0, 4, 5]   
>>> L = [1, 2, 0, 3]
>>> L[len(L)//2:len(L)//2 + 1] = [0] * L[(len(L)//2)]
>>> L
[1, 2, 3]
ekhumoro
  • 115,249
  • 20
  • 229
  • 336