Answer the question
In order to leave comments, you need to log in
How to swap the first and second halves of an ODD list?
Hello!
Here is tz:
Given a list of numeric values with N elements. Swap
the first and second halves of the list.
a = [4,6,7,8,1,5]
b = len(a)//2
for i in range(b):
temp = a[b]
a[b] = a[i]
a[i] = temp
b = b + 1
print(a)
a = [4,6,7,8,1,5,3]
[8, 1, 5, 4, 6, 7, 3]
8,1,5,3, 4,6,7or
1,5,3, 4,6,7,8
Answer the question
In order to leave comments, you need to log in
a = [4,6,7,8,1,5,3]
b = len(a) // 2
print(a[b:] + a[:b])
def f(a):
b = len(a) // 2
c = []
for i in range(len(a)):
idx = (i + b) % len(a)
c.append(a[idx])
return c
The second is in fact your array but inverted
Those. the last value of the list a[-1] "flies". The output should be something similar:
8,1,5,3, 4,6,7
or
1,5,3, 4,6,7,8
I'm talking about a solution. You can add a condition like
if b / 10 != 0: # тоесть массив нечетный z = b/2 # делим список пополам result = [] # переменная для записи результата while z >= 0: # перебор значений массива от середины до начала result.append(a[z]) # добавление каждого значения z -= 1 if not z: # если z вышел за пределы размера массива z = b/2 # то мы его обнуляем while z < b: result.append(a[z]) # добавление всех значений после массива z+=1 result.append(a[-1]) # добавление в конец последнее значение массива print(result)
The code is a little hacky and you have to jump a little with a tambourine, but I think I got the point across.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question