【Python CheckiO 题解】Index Power


CheckiO 是面向初学者和高级程序员的编码游戏,使用 Python 和 JavaScript 解决棘手的挑战和有趣的任务,从而提高你的编码技能,本博客主要记录自己用 Python 在闯关时的做题思路和实现代码,同时也学习学习其他大神写的代码。

CheckiO 官网:https://checkio.org/

我的 CheckiO 主页:https://py.checkio.org/user/TRHX/

CheckiO 题解系列专栏:https://itrhx.blog.csdn.net/category_9536424.html

CheckiO 所有题解源代码:https://github.com/TRHX/Python-CheckiO-Exercise


题目描述

【Index Power】:给定一个数组 array 和一个整数 n,求该数组 n 位置元素的 n 次方,如果整数 n 大于数组的长度,则输出 -1, 如果数组 n 位置元素为 0,则输出 1.

【链接】https://py.checkio.org/mission/index-power/

【输入】:两个参数,一个数组,一个整数。

【输出】:计算结果(整数)

【范例】

代码实现

def index_power(array: list, n: int) -> int:
    """
        Find Nth power of the element with index N.
    """
    if n < len(array):
        return array[n] ** n
    else:
        return -1

if __name__ == '__main__':
    print('Example:')
    print(index_power([1, 2, 3, 4], 2))
    
    #These "asserts" using only for self-checking and not necessary for auto-testing
    assert index_power([1, 2, 3, 4], 2) == 9, "Square"
    assert index_power([1, 3, 10, 100], 3) == 1000000, "Cube"
    assert index_power([0, 1], 0) == 1, "Zero power"
    assert index_power([1, 2], 3) == -1, "IndexError"
    print("Coding complete? Click 'Check' to review your tests and earn cool rewards!")

大神解答

大神解答 NO.1
def index_power(array: list, n: int) -> int:
    """
        Find Nth power of the element with index N.
    """
    if n < len(array):
        for x in array[n:n+1]:
            return x**n
    else:
        return -1
大神解答 NO.2
def index_power(array: list, n: int) -> int:
    """
        Find Nth power of the element with index N.
    """
    return array[n]**n if len(array) > n else -1
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

IT.BOB

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值