找回密码
 立即注册

扫一扫,访问微社区

QQ登录

只需一步,快速开始

查看: 2536|回复: 2

[求助] 循环function求解

0

主题

2

帖子

2

积分

贫民

积分
2
Arya 发表于 2021-4-20 15:11:49 | 显示全部楼层 |阅读模式
本帖最后由 Arya 于 2021-4-20 15:39 编辑

有个循环题目,哪位大神能帮我看看吗?要求写一个function叫answer_mask(reo, attempt),然后通过测试如下表得出结果。我写的程序只能通过第1和3,通过不了2和4。代码和测试已经复制到附件。
QQ图片20210420190714.png

def answer_mask(reo, attempt):
   """produce a string the same length as the reo string. Acharacter by
    charactercomparison is done  between the stringsreo and attempt. If a
    character matchesthen a * character is used, if they do not match then
    the letter fromthe reo string is added."""
    collect =' '
    for i inrange(0,len(reo)):
        if reo ==attempt:
            collect +='*'
        else:
            collect +=reo
    returncollect   
# test
print(answer_mask("Ōtautahi","Otautahe"))
print(answer_mask("Rāapa", "Rāpa"))
word = 'Aotearoa'
print(answer_mask(word, word))
print(answer_mask("Tahi", ""))

loop.docx

14.14 KB, 下载次数: 2

回复

使用道具 举报

0

主题

17

帖子

17

积分

贫民

积分
17
一杆钓起满天星 发表于 2021-5-3 19:19:44 | 显示全部楼层
def answer_mask(reo, attempt):
    collect = ''
    if len(reo) == len(attempt):
        if reo == attempt:
            for i in range(len(reo)):
                collect +='*'
            return collect
        else:
            for i in range(len(reo)):
                if reo[i] == attempt[i]:
                    collect += '*'
                else:
                    collect += reo[i]
        return collect
    elif len(reo) < len(attempt):
        for i in range(len(reo)):
            if reo[i] == attempt[i]:
                collect += '*'
            else:
                collect += attempt[i]
        return collect
    else:
        for i in range(len(attempt)):
            if reo[i] == attempt[i]:
                collect += '*'
            else:
                collect = collect + reo[i]
        collect = collect + reo[len(attempt):]
        return collect


# test
print(answer_mask("Ōtautahi", "Otautahe"))
print(answer_mask("Rāapa", "Rāpa"))
word = 'Aotearoa'
print(answer_mask(word, word))
print(answer_mask("Tahi", ""))
回复 支持 反对

使用道具 举报

0

主题

2

帖子

2

积分

贫民

积分
2
Arya  楼主| 发表于 2021-5-12 17:33:56 | 显示全部楼层
谢顶楼, 我研究到了:

def answer_mask(reo, attempt):
    """call me docstring"""
    collect = ''
    length = len(reo)
    for i in range(length):
        if i < len(reo) and i < len(attempt):
            if reo[i] == attempt[i]:
                collect += '*'
            else:
                collect += reo[i]
        else:
            if i < len(reo):
                collect += reo[i]
            else:
                collect += attempt[i]
    return collect
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

快速回复 返回顶部 返回列表