我正在编写一个 Python 脚本,该脚本读取文本文件,将其拆分为字符串列表,并计算每个字符串的 ASCII 值之和。我已将这些数据存储在字典中,其中字符串是键,ASCII 和是值。现在,我需要帮助从这本字典中找到最大的素值。任何建议或代码示例将不胜感激!
if __name__ == "__main":
# Opening the file in read mode with all words in a txt file
my_file = open("english FILTERED.ALL.txt", "r")
# Reading the file
data = my_file.read()
# Replacing and splitting the text when newline ('\n') is seen.
data_into_list = data.split("\n")
print(data_into_list)
my_file.close()
# Create a dictionary to store the list values and the ASCII values with them
result_dict = {}
# Loop through the list and calculate the sum of ASCII values for each string
for x in data_into_list:
ascii_sum = sum(ord(char) for char in x)
result_dict[x] = ascii_sum
# Printing the original list
print("The original list: " + str(data_into_list))
# Printing the dictionary containing string-sum pairs
print("String and their ASCII sum: " + str(result_dict))
我已经成功计算出每个字符串的 ASCII 值之和并将它们存储在字典中。然而,我现在正在尝试找到这些总和中最大的素值。
这是我当前输出的示例
String and their ASCII sum : {'ACM': 209, 'ANSI': 299, 'ASAP': 293, 'ASCII': 361, 'Achilles': 805, 'Ada': 262, 'Afghanistan': 1124, 'Africa': 582, 'African': 692, 'Africans': 807, 'Airedale': 791, 'Alabama': 671, 'Alabamian': 886, 'Alaska': 589, 'Albania': 680, 'Albanian': 790, 'Albanians': 905, 'Alcibiades': 993, 'Alden': 484, 'Algeria': 693}
我正在寻求有关如何从 ASCII 和字典中有效识别最大素数值的指导,因为我想找到字典中最大的素数 ASCII 和。
质数:
def is_prime(n):
if n <= 1:
return False
if n <= 3:
return True
if n % 2 == 0 or n % 3 == 0:
return False
i = 5
while i * i <= n:
if n % i == 0 or n % (i + 2) == 0:
return False
i += 6
return True
我会适应你的清单