Codewars--Fold an array

Fold an array

Problem Description:

在这里插入图片描述

在这里插入图片描述
As you see, if the count of numbers is odd, the middle number will stay. Otherwise the fold-point is between the middle-numbers, so all numbers would be added in a way.

The array will always contain numbers and will never be null. The parameter runs will always be a positive integer greater than 0 and says how many runs of folding your method has to do.

If an array with one element is folded, it stays as the same array.

The input array should not be modified!

Version of Python:

在这里插入图片描述

Solution:

def fold_array(array, runs):
    if runs<=0:
        return array
    n=len(array)
    list=[]
    for i in range(n//2):
        list.append(array[i]+array[n-i-1])
    if n%2==0:
        return fold_array(list,(runs-1))
    else:
        list.append(array[n//2])
        return fold_array(list,(runs-1))

在这里插入图片描述

Grammar:

Within Python list, compare append() with extend():
list.append(array[i]+array[n-i-1])

Let’s give an example:

>>> a.extend([1,2])
>>> print a
[1, 2, '3', '1', 1, 2]
>>> a.append([1,2])
>>> print a
[1, 2, '3', '1', 1, 2, [1, 2]]
Conlusion:
  • A list can contain elements of any data type, and elements in a single list need not all be of the same type.
  • The append() function adds a new element to the end of the list.
  • Lists are implemented as classes. Creating a list is actually instantiating a class. Therefore, lists can be manipulated in many ways. The extend() method takes a single list as an argument , and adds each element of that parameter list to the original list.
  • Both append() and extend() accept only one parameter.
  • The parameter of append() is random as you like.
  • The parameter of extend() must be a list.
Wish you succeed!
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值