0

I'm trying to write a smart snippet of code that does the following:

Given a list and an integer-valued parameter k:

k = 2 
myList = [1, 2, 3, 4, 5]

I would like to find a way of slicing my list such that I can later construct the following dictionary:

{1: [5, 4, 2, 3], 
 2: [1, 5, 3, 4],
 3: [2, 1, 4, 5],
 4: [3, 2, 5, 1],
 5: [4, 3, 1, 2]}

i.e, I need to slice my list and extract my last k and next k elements (the order of the elements in the list after slicing does not matter), given an index. For example, if my index is 0, then I would expect [5, 4, 2, 3].

My problem is similar to this question. However not exactly the same.

I'd appreciate any help, hint, or reference to any source.

Sophie_s
  • 25
  • 4
  • I find your description not very clear. How could slicing produce a dict? What do you mean by "extract last `k` ... digits ... given a position in list"?. – VPfB Nov 18 '20 at 17:06
  • @VPfB I apologize for the bad wording, I'll try to improve my description. – Sophie_s Nov 18 '20 at 17:09
  • Thank you, but you have already received and accepted an answer. Maybe the problem with understanding is on my side... – VPfB Nov 18 '20 at 17:17

2 Answers2

1

You could do:

k = 2
myList = [1, 2, 3, 4, 5]

offset = len(myList)
padded_list = myList * 3

result = {myList[i]: padded_list[j - k: j][::-1] + padded_list[j + 1: j + k + 1] for i, j in
          zip(range(offset), range(offset, 2 * offset))}
print(result)

Output

{1: [5, 4, 2, 3], 2: [1, 5, 3, 4], 3: [2, 1, 4, 5], 4: [3, 2, 5, 1], 5: [4, 3, 1, 2]}

The idea is to pad the list with itself before and after, and the iterate in the middle section. This should work without problem while k < len(myList).

Dani Mesejo
  • 61,499
  • 6
  • 49
  • 76
0

I think simple python list slicing should suffice. Basically I sliced the list two times and concatenated the resulting two lists.

>>> l = [1, 2, 3, 4, 5]
>>> k = 2
>>> l[:k-1] + l[k:]
[1, 3, 4, 5]

Good luck!

Adam
  • 46
  • 3