Calculate shanon entropy of the string
(data: str, iterator=lambda: range(255))
| 83 | |
| 84 | |
| 85 | def calculate_entropy(data: str, iterator=lambda: range(255)) -> float: |
| 86 | """ |
| 87 | Calculate shanon entropy of the string |
| 88 | """ |
| 89 | if not data: |
| 90 | return 0 |
| 91 | |
| 92 | entropy = 0 |
| 93 | for x in iterator(): |
| 94 | p_x = float(data.count(chr(x))) / len(data) |
| 95 | if p_x > 0: |
| 96 | entropy += -p_x * math.log(p_x, 2) |
| 97 | |
| 98 | return entropy |