创建一个仅包含原始短语中字母的首次出现的函数

时间:2018-10-17 01:13:51

标签: python string loops iteration

该函数的行为如下:enter image description here

首字母出现可以是大写或小写(newPhrase)。 非字母字符-保持不变。

到目前为止,我想到的是:

def keepFirstLetter(phrase):
'''Returns a new string that contains only the first occurrence of a 
letter from the original phrase. 

    letterSeenSoFar = ''
    newPhrase = ''
    if (letterSeenSoFar == '' or letterSeenSoFar[-1] != letterSeenSoFar):
         letterSeenSoFar += c
    for letter in letterSeenSoFar:
        if letter.isalpha:
            newPhrase += char
        else:
            newPhrase += letter
    return newPhrase

3 个答案:

答案 0 :(得分:3)

您似乎在正确的轨道上。如果要提高效率,可以将看到的字母存储为一组。搜索集合为O(1)。

def unique_first(s):
    letters = set()
    out = ''
    for x in s:
        if not x.isalpha():
            out += x
            continue
        if not x.lower() in letters:
            out += x
            letters.add(x.lower())
    return out

答案 1 :(得分:2)

最简单,必定要学习的解决方案可能是:

def keepFirstLetter(phrase):
    output = ''
    for letter in phrase:
        if (letter.lower() not in output.lower()) or (not letter.isalpha()):
            output += letter

    return output

print(keepFirstLetter('Amy says, "Me?"'))       #  Amy s, "e?"

(两个if子句的括号是可选的)

詹姆斯的解决方案仍然获得了我的投票。

答案 2 :(得分:1)

我的名字是我的问题,所以让我尝试一下。 我是第一次从James学习set.add()。 (谢谢James。)James的代码更短,运行得更快(在我的PC上为3.48us与3.76us)。

def keepFirstLetter(phrase):
    phrase = list(phrase)
    '''Returns a new string that contains only the first occurrence of a 
    letter from the original phrase.'''
    letterSeenSoFar = []
    newPhrase = ''
    for char in phrase:
        # if char is not an alphabet, add char to the newPhrase as is
        if not char.isalpha():
            newPhrase += char
        # if char is an alphabet and not seen so far, add char to the newPhrase and append it to letterSeenSoFar
        elif char.lower() not in letterSeenSoFar:
            letterSeenSoFar.append(char.lower())
            newPhrase += char
    return newPhrase

print(keepFirstLetter('Amy says, " Me?"'))

这将输出:

Amy s, " e?"