[英]python: how to check if string has the same characters / the probability of repeating them is the same
How to check if a given string has the same characters or their probability is the same, which gives me True?如何检查给定的字符串是否具有相同的字符或它们的概率是否相同,这给了我正确的结果?
For example, if there is string = "aaaa"
the result is True and:例如,如果有string = "aaaa"
结果为 True 并且:
string = "aabb" True
string = "aabbcc" True
p = "1122" True
p = "aaaaBBBB9999$$$$" True
but:但:
string = "korara" False
p = "33211" False
For "aaa"
I can use (len (set ("aaa")) == 1)
, but I don't know about the others.对于"aaa"
我可以使用(len (set ("aaa")) == 1)
,但我不知道其他的。
Have you try ?你试过吗?
from collections import Counter
def check(v):
return len(set(Counter(v).values())) <= 1
assert check("aabb")
assert check("aabbcc")
assert check("1122")
assert check("aaaaBBBB9999$$$$")
assert check("")
assert not check("korara")
assert not check("33211")
You can use the collection which will create a dictionary and then you can check for each value if they are equal.您可以使用将创建字典的集合,然后您可以检查每个值是否相等。
The following piece of code does that:下面的一段代码就是这样做的:
import collections
counter = dict(collections.Counter("aabbcc"))
expected_value = next(iter(counter.values()))
are_equal = all(value == expected_value for value in counter.values())
print("Result for aabbcc: ", are_equal)
counter = dict(collections.Counter("korara"))
expected_value = next(iter(counter.values()))
are_equal = all(value == expected_value for value in counter.values())
print("Result for korara: ", are_equal)
Pass your string in this function在这个函数中传递你的字符串
def repeating_probability(s):
sarr={}
for i in s:
if i in sarr.keys():
sarr[i] += 1
else:
sarr[i] = 1
if len(list(set(sarr.values()))) == 1:
return True
else:
return False
不过有一个用于字符串的 length() 函数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.