📜  Python程序从与字符的最高和最低的ASCII值句子打印字

📅  最后修改于: 2021-04-17 17:05:14             🧑  作者: Mango

鉴于长度为N的字符串S,代表一个句子,任务是打印最高和最低平均字符的ASCII值的话。

例子:

方法:想法是使用split()函数。请按照以下步骤解决问题:

  • 使用split()函数拆分所有用空格分隔的字符串单词。将其存储在列表中,例如lis []。
  • 初始化四个变量,分别是maxi,mini,maxIdminId 存储ASCII值的平均值的最大值,最小ASCII平均值,列表lis中具有最大ASCII平均值的单词的索引以及列表lis []中具有ASCII平均最小值的单词的索引分别。
  • 定义一个函数,例如averageValue(),以查找字符串的平均ASCII值。
  • 遍历列表lis []并执行以下操作:
    • 对于列表lis []中的i单词, 并将其存储在变量中,例如curr。
    • 如果curr> maxi,则将maxi更新为maxi = curr并分配maxId = i。
    • 如果curr 则将mini更新为mini = curr并分配minId = i。
  • 完成上述步骤后,打印单词lis [minId]lis [maxId]及其字符的ASCII值的最小和最大平均值

下面是上述方法的实现:

Python3
# Python implementation of the above approach
  
# Function to find the average
# of ASCII value of a word
def averageValue(s):
  
    # Stores the sum of ASCII
    # value of all characters
    sumChar = 0
  
   # Traverse the string
    for i in range(len(s)):
  
        # Increment sumChar by ord(s[i])
        sumChar += ord(s[i])
  
    # Return the average
    return sumChar // len(s)
  
# Function to find words with maximum
# and minimum average of ascii values
def printMinMax(string):
  
    # Stores the words of the
    # string S seprated by spaces
    lis = list(string.split(" "))
  
    # Stores the index of word in
    # lis[] with maximum average
    maxId = 0
  
    # Stores the index of word in
    # lis[] with minimum average
    minId = 0
  
    # Stores the maximum average
    # of ASCII value of characters
    maxi = -1
  
    # Stores the minimum average
    # of ASCII value of characters
    mini = 1e9
  
    # Traverse the list lis
    for i in range(len(lis)):
  
        # Stores the average of
        # word at index i
        curr = averageValue(lis[i])
  
        # If curr is greater than maxi
        if(curr > maxi):
  
            # Update maxi and maxId
            maxi = curr
            maxId = i
  
        # If curr is lesser than mini
        if(curr < mini):
  
            # Update mini and minId
            mini = curr
            minId = i
  
    # Print string at minId in lis
    print("Minimum average ascii word = ", lis[minId])
  
    # Print string at maxId in lis
    print("Maximum average ascii word = ", lis[maxId])
  
  
# Driver Code
  
S = "every moment is fresh beginning"
printMinMax(S)


输出:
Minimum average ascii word =  beginning
Maximum average ascii word =  every

时间复杂度: O(N)
辅助空间: O(1)