Last active
June 11, 2019 23:46
-
-
Save clementi/866f905ddd7b46cdfaeb4fa72f992276 to your computer and use it in GitHub Desktop.
Naive string entropy calculator
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
import os | |
import fileinput | |
import string | |
import math | |
def get_string(): | |
return fileinput.input()[0] | |
pools = [string.ascii_lowercase, string.ascii_uppercase, string.digits, string.punctuation, " "] | |
def entropy(s): | |
member_pools = filter(lambda pool: has_members(s, pool), pools) | |
pool_size= sum(map(lambda pool: len(pool), member_pools)) | |
return len(s) * lg(pool_size) | |
def lg(x): | |
return math.log(x) / math.log(2) | |
def has_members(s, chars): | |
for c in s: | |
if c in chars: | |
return True | |
return False | |
def main(): | |
s = get_string() | |
print(entropy(s)) | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment