Easy Unpack

问题描述:

Input: A tuple, at least 3 elements long.

OutputA tuple.

def easy_unpack(elements: tuple) -> tuple:
    """
        returns a tuple with 3 elements - first, third and second to the last
    """
    # your code here
    return ()

if __name__ == '__main__':
    print('Examples:')
    print(easy_unpack((1, 2, 3, 4, 5, 6, 7, 9)))
    
    #These "asserts" using only for self-checking and not necessary for auto-testing
    assert easy_unpack((1, 2, 3, 4, 5, 6, 7, 9)) == (1, 3, 7)
    assert easy_unpack((6, 2, 9, 4, 3, 9)) == (6, 9, 3)
    assert easy_unpack((1, 1, 1, 1)) == (1, 1, 1)
    assert easy_unpack((6, 3, 7)) == (6, 7, 3)
    print('Done! Go Check!')

一个最基础的索引问题,可以直接返回第一、第三和倒数第二位置的元素。

return (elements[0],elements[2],elements[-2])

思考:

来自其他用户的解决方案。

方案一:for 循环

def easy_unpack(elements):
    """
        returns a tuple with 3 elements - first, third and second to the last
    """
    return tuple(elements[i] for i in [0,2,-2])

class tuple([iterable])

可以用多种方式构建元组:

  • 使用一对圆括号来表示空元组: ()

  • 使用一个后缀的逗号来表示单元组: a, 或 (a,)

  • 使用以逗号分隔的多个项: a, b, c or (a, b, c)

  • 使用内置的 tuple()tuple() 或 tuple(iterable)

 所以如果直接返回一个元组,应该会更加严谨一点。

有时候看别人的回答,真的会给自己一个不一样的思路。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值