微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

python:字符的熵条件

如何解决python:字符的熵条件

我希望它根据波兰字母和所用符号来计算熵:

  • 如果仅大写或小写字母为32
  • 对于64个而言,它们既大又小
  • 如果有+10个数字
  • 如果有特殊字符+33

不幸的是,这些条件的第二个公式对我不起作用。当我键入“ Apple”时,它会弹出 NameError:名称“ entropia2”未定义

import math

def entropy_poland(n):
    print("Znaki nie powtarzają się,więc liczymy ze wzoru Hartleya: ")
    if count_upper == True and count_lower == False and count_other == False and count_number == False:
        entropy2 = math.log2(32)
    elif count_upper == False and count_lower == True and count_other == False and count_number == False:
        entropy2 = math.log2(32)
    elif count_upper == False and count_lower == False and count_other == False and count_number == False:
        entropy2 = math.log2(64)
    elif count_upper == True and count_lower == False and count_other == False and count_number == True:
        entropy2 = math.log2(42)
    elif count_upper == False and count_lower == True and count_other == False and count_number == True:
        entropy2 = math.log2(42)
    elif count_upper == False and count_lower == False and count_other == False and count_number == True:
        entropy2 = math.log2(74)
    elif count_upper == False and count_lower == True and count_other == True and count_number == False:
        entropy2 = math.log2(65)
    elif count_upper == True and count_lower == False and count_other == True and count_number == False:
        entropy2 = math.log2(65)
    elif count_upper == False and count_lower == False and count_other == True and count_number == False:
        entropy2 = math.log2(97)
    elif count_upper == True and count_lower == False and count_other == True and count_number == True:
        entropy2 = math.log2(75)
    elif count_upper == False and count_lower == True and count_other == True and count_number == True:
        entropy2 = math.log2(75)
    elif count_upper == False and count_lower == False and count_other == True and count_number == True:
        entropy2 = math.log2(107)
    return entropy2


count_number = False
count_upper = False
count_lower = False
count_other = False

odp = "Reks"

for ascii in odp:
    if chr(32) <= ascii <= chr(47) or chr(58) <= ascii <= chr(64) or chr(91) <= ascii <= chr(96) or chr(
            123) <= ascii <= chr(126):
        count_other = True
    if chr(48) <= ascii <= chr(57):
        count_number = True
    if chr(65) <= ascii <= chr(90):
        count_upper = True
    if chr(97) <= ascii <= chr(122):
        count_lower = True


print(entropy_poland(odp))
````

解决方法

如果您插入行

print(count_upper,count_lower,count_other,count_number)

entropy_poland定义的开头,您会看到它打印出来

True True False False

在引发错误之前。布尔组合不是您的条款涵盖的组合之一。有4个变量的16个布尔组合,但是您仅为其中12个定义了entropy2。您需要重新考虑自己的逻辑,或者添加一个else子句,或者如果此布尔组合实际上是一个错误,则可能引发(然后处理)错误。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。