将Python中的函数和字典映射为ASCII值之和

给我们一个英语句子(也可以包含数字),我们需要计算并打印该句子中每个单词字符的ASCII值之和。

null

例如:

Input :  GeeksforGeeks, a computer science portal
         for geeks
Output : Sentence representation as sum of ASCII 
         each character in a word:
         1361 97 879 730 658 327 527 
         Total sum -> 4579
Here, [GeeksforGeeks, ] -> 1361, [a] -> 97, [computer] 
-> 879, [science] -> 730 [portal] -> 658, [for] 
-> 327, [geeks] -> 527 

Input : I am a geek
Output : Sum of ASCII values:
         73 206 97 412 
         Total sum -> 788

此问题已有解决方案,请参考 句子中每个单词的ASCII值之和 链接我们将使用python快速解决这个问题 地图() 功能和 词典 数据结构。方法很简单,

  1. 首先将句子中的所有单词用空格隔开。
  2. 创建一个空字典,其中包含单词作为键,其字符的ASCII值之和作为值。
  3. 现在遍历拆分单词的列表,并为每个单词映射 ord(chr) 函数对当前单词的每个字符执行操作,并计算当前单词每个字符的ascii值之和。
  4. 遍历每个单词时,在上面创建的结果字典中对应单词上的ascii值之和。
  5. 遍历拆分的单词列表,并通过查找结果字典打印相应的ascii值。

      # Function to find sums of ASCII values of each
      # word in a sentence in
      def asciiSums(sentence):
      # split words separated by space
      words = sentence.split( ' ' )
      # create empty dictionary
      result = {}
      # calculate sum of ascii values of each word
      for word in words:
      currentSum = sum ( map ( ord ,word))
      # map sum and word into resultant dictionary
      result[word] = currentSum
      totalSum = 0
      # iterate list of splited words in order to print
      # sum of ascii values of each word sequentially
      sumsOfAscii = [result[word] for word in words]
      print ( 'Sum of ASCII values:' )
      print ( ' ' .join( map ( str ,sumsOfAscii)))
      print ( 'Total Sum -> ' , sum (sumsOfAscii))
      # Driver program
      if __name__ = = "__main__" :
      sentence = 'I am a geek'
      asciiSums(sentence)

      
      

      输出:

      Sum of ASCII values:
      1361 97 879 730 658 327 527 
      Total sum -> 4579
      
© 版权声明
THE END
喜欢就支持一下吧
点赞12 分享