Open In App

Python program to print words from a sentence with highest and lowest ASCII value of characters

Given a string S of length N, representing a sentence, the task is to print the words with the highest and lowest average of ASCII values of characters.

Examples:



Input: S = "every moment is fresh beginning"
Output:
Word with minimum average ASCII values is "beginning".
Word with maximum average ASCII values is "every".

Explanation:
The average of ASCII values of characters of the word "every" = ((101+118+101+114+121)/5 =111)
The average of ASCII values of characters of the word "moment" =: (( 109+111+109+101+110+116)/6 = 109.33333)
The average of ASCII values of characters of the word "is" = ((105+115)/2 =)
The average of ASCII values of characters of the word "fresh" = ((102+114+101+115+104)/5 = 110)
The average of ASCII values of characters of the word "beginning" = ((98+101+103+105+110+110+105+110+103)/9 =105).
Therefore, the word with minimum of average of ASCII values is "beginning” and maximum of average ASCII values is "every".
Input: S = "sky is blue"
Output:
Word with minimum average ASCII values is "blue".
Word with maximum average ASCII values is "sky".

Approach 1: The idea is to use the split() function. Follow the steps below to solve the problem:

Below is the implementation of the above approach:






# 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 separated 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)

Output
Minimum average ascii word =  beginning
Maximum average ascii word =  every

Time Complexity: O(N), as we are using a loop to traverse N times so it will cost us O(N) time 
Auxiliary Space: O(1), as we are not using any extra space.

Approach 2: Using ord(),statistics.mean(),sort(),extend(),index() methods

  1. Split the given string
  2. Defined a method avg to find the average of ascii values of each string using ord(),statistics.mean() and for loop
  3. Append the average of ASCII values to a list
  4. Sort the list and display the minimum average ascii word and maximum average ascii word using sort(),extend() and index() methods




# Python implementation of the above approach
 
import statistics
S = "every moment is fresh beginning"
 
 
def avg(a):
    v = []
    for i in a:
        v.append(ord(i))
    return statistics.mean(v)
 
 
x = S.split()
y = []
for i in x:
    y.append(avg(i))
z = []
z.extend(y)
z.sort()
# Print string at minId in lis
print("Minimum average ascii word = ", x[y.index(z[0])])
# Print string at maxId in lis
print("Maximum average ascii word = ", x[y.index(z[-1])])

Output
Minimum average ascii word =  beginning
Maximum average ascii word =  every

Time Complexity: O(N) N – length of splitted list
Auxiliary Space: O(N) N – length of sorted list

Approach#3:using split and dictionary

Algorithm

1.Split the sentence into words.
2.Convert each word into a list of ASCII values of its characters.
3.Compute the average ASCII value of each word and store it along with the word in a dictionary.
4.Find the word with the minimum and maximum average ASCII values in the dictionary.
5.Print the words with the minimum and maximum average ASCII values.




s = "sky is blue"
 
words = s.split()
 
avg_ascii_dict = {}
 
for word in words:
    ascii_list = [ord(c) for c in word]
    avg_ascii = sum(ascii_list) / len(ascii_list)
    avg_ascii_dict[word] = avg_ascii
 
min_word = min(avg_ascii_dict, key=avg_ascii_dict.get)
max_word = max(avg_ascii_dict, key=avg_ascii_dict.get)
 
print(f"Word with minimum average ASCII values is '{min_word}'.")
print(f"Word with maximum average ASCII values is '{max_word}'.")

Output
Word with minimum average ASCII values is 'blue'.
Word with maximum average ASCII values is 'sky'.

Time complexity: O(n * m), where n is the number of words in the sentence and m is the maximum length of a word.

Space complexity: O(n * m), as we are storing the average ASCII values of each word in a dictionary that can potentially have n entries of length m.


Article Tags :