编写一个函数repfree,将一个字符串s作为输入,并检查是否有一个字符出现多次。如果没有重复,该函数应返回True,否则返回False。
我已经尝试过了,但是我觉得这不是解决问题的有效方法。您能为此建议一个有效的代码吗,谢谢?
def repfree(s):
newlist = []
for i in range(0, len(s)):
newlist.append(s[i])
newlist2 = set(newlist)
if len(newlist) == len(newlist2):
print("True")
else:
print("False")
尝试
chars = 'abcdefghijklmnopqrstuvwxyz'
def repfree(s):
for char in chars:
count = s.count(char)
if count > 1:
return False
return True
但是,这很漫长,因为它会扫描列表26次。一种更好的Python方式是
import collections
def repfree(s):
results = collections.Counter(s)
for i in results:
if results[i] > 1:
return False
return True
这里results
是一个字典,其中包含s的所有字符作为键,以及它们各自的频率作为值。此外,检查是否有任何值大于1,重复发生。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句