0
def remove_duplicates(strng):
    """
    Returns a string which is the same as the argument except only the
    first occurrence of each letter is present.  Upper and lower case
    letters are treated as different.  Only duplicate letters are removed,
    other characters such as spaces or numbers are not changed. 

    >>> remove_duplicates('apple')
    'aple'
    >>> remove_duplicates('Mississippi')
    'Misp'
    >>> remove_duplicates('The quick brown fox jumps over the lazy dog')
    'The quick brown fx jmps v t lazy dg'
    >>> remove_duplicates('121 balloons 2 u')
    '121 balons 2 u'
    """
    s = strng.split()
    return strng.replace(s[0],"")

重複した文字を取り除く関数を書いていますが、これまでのところ 1 時間遊んでいて何も得られません。助けていただければ幸いです、ありがとう。

4

3 に答える 3

3

最も効率的ではありませんが、最も簡単な方法は次のとおりです。

>>> s = 'The quick brown fox jumps over the lazy dog'
>>> import string
>>> n = ''
>>> for i in s:
        if i not in string.ascii_letters:
            n += i
        elif i not in n:
            n += i


>>> n
'The quick brown fx jmps v t lazy dg'
于 2010-05-19T12:01:20.710 に答える
2

リスト内包表記の使用:

>>> from string import whitespace, digits
>>> s = 'The quick brown fox jumps over the lazy dog'
>>> ''.join([c for i, c in enumerate(s) if c in whitespace+digits \
                                                      or not c in s[:i]])
于 2010-05-19T20:22:27.567 に答える
0

これを試して ...

def remove_duplicates(s):
    result = ""
    dic = {}
    for i in s:
        if i not in dic:
            result+=i
            if ord(i.lower()) >= ord('a') and ord(i.lower()) <= ord('z'):
                dic[i] = 1
    return result
于 2010-05-19T12:07:21.210 に答える