【Python CheckiO 题解】Right to Left


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


题目描述

【Right to Left】:给定一个字符串序列,以元组的形式输入,将其中的 right 关键字替换成 left,要求输出为字符串,原来元组之间的元素用逗号连接。

【链接】https://py.checkio.org/mission/right-to-left/

【输入】:元组

【输出】:字符串

【前提】:0 < len(phrases) < 42

【范例】

left_join(("left", "right", "left", "stop")) == "left,left,left,stop"
left_join(("bright aright", "ok")) == "bleft aleft,ok"
left_join(("brightness wright",)) == "bleftness wleft"
left_join(("enough", "jokes")) == "enough,jokes"

解题思路

先用 join() 方法将元组转换成字符串,并用逗号连接,再用 replace() 方法将 right 替换成 left 即可

代码实现

def left_join(phrases):
    """
        Join strings and replace "right" to "left"
    """
    return ','.join(phrases).replace('right', 'left')

if __name__ == '__main__':
    print('Example:')
    print(left_join(("left", "right", "left", "stop")))
    
    #These "asserts" using only for self-checking and not necessary for auto-testing
    assert left_join(("left", "right", "left", "stop")) == "left,left,left,stop", "All to left"
    assert left_join(("bright aright", "ok")) == "bleft aleft,ok", "Bright Left"
    assert left_join(("brightness wright",)) == "bleftness wleft", "One phrase"
    assert left_join(("enough", "jokes")) == "enough,jokes", "Nothing to replace"
    print("Coding complete? Click 'Check' to review your tests and earn cool rewards!")

大神解答

大神解答 NO.1

def left_join(phrases):
    """
        Join strings and replace "right" to "left"
    """
    text = ''
    for word in phrases: text +=word+','
    text = text[:-1]
    text = text.replace('right','left')

大神解答 NO.2

def left_join(x):   
    return ','.join([i.replace('right','left') for i in x])
发布了135 篇原创文章 · 获赞 475 · 访问量 44万+
展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 数字20 设计师: CSDN官方博客

分享到微信朋友圈

×

扫一扫,手机浏览