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 = "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.
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() 函数。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.