2017-03-16 93 views
0

编写一个名为remove_duplicates的函数,它将接受一个名为string的参数。该字符串输入将只包含a-z之间的字符。在python中编写函数remove_duplicates

功能应该删除所有重复的字符字符串中,并用两个值返回一个元组:

的新字符串只有独特的,分类的字符。

删除重复项的总数。

例如:

remove_duplicates('aaabbbac') => ('abc', 5) 

remove_duplicates('a') => ('a', 0) 

remove_duplicates('thelexash') => ('aehlstx', 2) 

这里是我的解决方案,我是新来的Python:

string = raw_input("Please enter a string...") 

def remove_duplicates(string): 
    string = set(string) 
    if only_letters(string): 
    return (string, string.length) 
    else: 
    print "Please provide only alphabets" 

remove_duplicates(string) 

什么可能我被错误地做什么?这是我得到以下

有错误/ BUG在你的代码 结果错误: /bin/sh的:1:蟒蛇/ nose2 /斌/ nose2:找不到

感谢。

+2

这听起来像是在验证支架的错误,而不是你的代码。 –

+1

我想如果代码无效,测试部分可能会以模糊的方式失败Python:它是'len(string)'而不是'string.length'。在发送提交内容之前,您应该先在本地进行测试以查看此类错误。 – polku

+0

请参阅http://stackoverflow.com/questions/9841303/removing-duplicate-characters-from-a-string。在你的代码中你没有定义“only_letters” – manvi77

回答

0

由于顺序并不重要,你可以使用

string = raw_input("Please enter a string...") 

def remove_duplicates(string): 
    new_string = "".join(set(string)) 
    if new_string: 
    return (new_string, len(string)-len(new_string)) 
    else: 
    print "Please provide only alphabets" 

remove_duplicates(string) 

Please enter a string...aaabbbac 
Out[27]: ('acb', 5) 

集()将创建一组串中不同的字母,而“”。加入()将加入信回字符串以任意顺序。

0

是从测试我的工作收到了同样的错误,我觉得错误是不是从你的结束,但测试人员的最终

2

这一切正常。输出应该排序。

def remove_duplicates(string): 
    new_string = "".join(sorted(set(string))) 
    if new_string: 
    return (new_string, len(string)-len(new_string)) 
    else: 
    print "Please provide only alphabets" 

无需包括此:

string = raw_input("Please enter a string...") 

remove_duplicates(string)