python函数问题

函数main()接收一个任意字符串text作为参数,要求返回其中每个唯一字符按最后一次出现位置的先后顺序拼接组成的新字符串。例如,main('Beautiful is better than ugly.')返回'Bfisberthan ugly.’。不能导入任何模块,不能使用字符串方法index()和rindex(),要求使用for循环。
def main(text):

def func(text):
    lookup = set()
    res = []
    for t in text[::-1]:
        if t not in lookup:
            lookup.add(t)
            res.insert(0, t)
    return ''.join(res)

使用set集合来判断是否出现做,从右向左判断最后一次

如有帮助,望采纳~😁

直接用字典好了,先倒序取字符串的字符为键,也就是最后一次出现的位置,然后拼起来,再倒序返回

def main(text):
    res = dict.fromkeys(text[::-1],1)
    return ''.join(res.keys())[::-1]

print(main('Beautiful is better than ugly.'))

一定要使用for循环的话就把fromkeys换掉:

def main(text):
    t = text[::-1]
    res = {}
    for i in t:
        res[i]=1
    return ''.join(res.keys())[::-1]
def main(text):
    res = []
    for i in text[::-1]:
        if i not in res:
            res.append(i)
    return ''.join(res[::-1])

>>> main('Beautiful is better than ugly.')
'Bfisberthan ugly.'