เราต้องการคำนวณผลรวม ASCII สำหรับแต่ละคำในประโยคและประโยคโดยรวมโดยใช้ฟังก์ชันแผนที่และพจนานุกรม ตัวอย่างเช่น ถ้าเรามีประโยค −
"hi people of the world"
ผลรวม ASCII ที่สอดคล้องกันสำหรับคำจะเป็น:209 645 213 321 552
และยอดรวมจะเป็น :พ.ศ. 2483
เราสามารถใช้ฟังก์ชันแผนที่เพื่อค้นหาค่า ASCII ของตัวอักษรแต่ละตัวในคำโดยใช้ฟังก์ชัน ord จากนั้นใช้ฟังก์ชันผลรวม เราสามารถสรุปได้ สำหรับแต่ละคำ เราสามารถทำซ้ำขั้นตอนนี้และรับผลรวมของค่า ASCII สุดท้าย
ตัวอย่าง
sent = "hi people of the world"
words = sent.split(" ")
result = {}
# Calculate sum of ascii values for every word
for word in words:
result[word] = sum(map(ord,word))
totalSum = 0
# Create an array with ASCII sum of words using the dict
sumForSentence = [result[word] for word in words]
print ('Sum of ASCII values:')
print (' '.join(map(str, sumForSentence)))
print ('Total of all ASCII values in sentence: ',sum(sumForSentence)) ผลลัพธ์
สิ่งนี้จะให้ผลลัพธ์ -
Sum of ASCII values: 209 645 213 321 552 Total of all ASCII values in a sentence: 1940