300字范文,内容丰富有趣,生活中的好帮手!
300字范文 > 使用python解决codewar中问题 个人答题思路及代码总结(3)

使用python解决codewar中问题 个人答题思路及代码总结(3)

时间:2021-06-23 00:43:33

相关推荐

使用python解决codewar中问题 个人答题思路及代码总结(3)

6 kyu Back and forth then Reverse!

A list S will be given. You need to generate a list T from it by following the given process:

1、Remove the first and last element from the list S and add them to the list T.

Reverse the list S

2、Repeat the process until list S gets emptied.

3、The above process results in the depletion of the list S. Your task is to generate list T without mutating the input List S.

题意:给定一个列表,将列表中第一个和最后一个元素放到一个新的列表中去,然后再将列表元素翻转,再将第二个以及倒数第二个元素放到新的列表中去。以此类推直到数组所有元素都放到一个新的列表中去。这个过程不能改变给定输入列表。

思路:

不能改变给定输入,就得新建一个新的列表进行操作,然后有需要一个列表来装返回值,

第一次的思路是将数组中的值使用pop()进行删除,然后装到一个新的列表中去,然后使用reverse()将列表翻转。但是答案是对的,耗时太高没有跑过!!!

def arrange(s):

ls1 = []

ls2 = []

if len(s) <= 2:

return s;

for i in s:

ls1.append(i)

while len(ls1) > 1:

ls2.append(ls1.pop(0))

ls2.append(ls1.pop())

ls1.reverse()

if len(ls1)>0:

ls2.append(ls1[0])

return ls2

第二次思路是不使用while,用for来循环,设置两个指针分别指向列表的第一个和最后一个元素,两者同时进行移动,这样就减少了循环次数,可是还是⑧行,时间复杂度高!!!

import math

def arrange(s):

lens = len(s)

ls = []

ls2 = []

a = 0

b = lens -1

if lens < 3:

return s

else:

for i in s:

ls.append(i)

if lens%2 == 0:

for j in range(math.ceil(lens/2)):

ls2.append(ls[a])

ls2.append(ls[b])

a = a + 1

b = b - 1

ls.reverse()

return ls2

else:

for j in range(math.ceil(lens/2)-1):

ls2.append(ls[a])

ls2.append(ls[b])

a = a + 1

b = b - 1

ls.reverse()

ls2.append(ls[math.ceil(lens/2)-1])

return ls2

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。