Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Python program to calculate the number of words and characters in the string
Next article icon

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

Last Updated : 08 Feb, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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:

  • Split all the words of the string separated by spaces using the split() function. Store it in a list, say lis[].
  • Initialize four variables say maxi, mini, maxId, and minId, to store the maximum of average of ASCII values, the minimum average ASCII value, the index of the word with the maximum average ASCII value in the list lis, and the index of the word with the minimum average ASCII value in the list lis[] respectively.
  • Define a function, say averageValue(), to find the average ASCII value of a string.
  • Traverse the list lis[] and perform the following operations:
    • For every ith word in the list lis[], and store it in a variable, say curr.
    • If curr> maxi, then update maxi as maxi = curr and assign maxId = i.
    • If curr< mini, then update mini as mini = curr and assign minId = i.
  • After completing the above steps, print the words lis[minId] and lis[maxId] with minimum and maximum average of ASCII value of its characters.

Below is the implementation of the above approach:

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 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
Python3
# 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.

Python3
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.


Next Article
Python program to calculate the number of words and characters in the string
author
vikkycirus
Improve
Article Tags :
  • Strings
  • Searching
  • Mathematical
  • Technical Scripter
  • Competitive Programming
  • Python Programs
  • DSA
  • ASCII
  • python-list-functions
Practice Tags :
  • Mathematical
  • Searching
  • Strings

Similar Reads

  • Python program to capitalize the first and last character of each word in a string
    In this article, we will explore how to capitalize the first and last character of each word in a string in Python. It involves processing each word to transform its first and last letters to uppercase, while making the other characters lowercase. Using List Comprehensionlist comprehension and strin
    2 min read
  • Python program to find the character position of Kth word from a list of strings
    Given a list of strings. The task is to find the index of the character position for the word, which lies at the Kth index in the list of strings. Examples: Input : test_list = ["geekforgeeks", "is", "best", "for", "geeks"], K = 21 Output : 0Explanation : 21st index occurs in "geeks" and point to "g
    3 min read
  • Python Program to Find ASCII Value of a Character
    Given a character, we need to find the ASCII value of that character using Python. ASCII (American Standard Code for Information Interchange) is a character encoding standard that employs numeric codes to denote text characters. Every character has its own ASCII value assigned from 0-127. Examples:
    2 min read
  • Python program to calculate the number of words and characters in the string
    We are given a string we need to find the total number of words and total number of character in the given string. For Example we are given a string s = "Geeksforgeeks is best Computer Science Portal" we need to count the total words in the given string and the total characters in the given string.
    3 min read
  • Python program to find the longest word in a sentence
    In this article, we will explore various methods to find the longest word in a sentence. Using LoopFirst split the sentence into words using split() and then uses a loop (for loop) to iterate through the words and keeps track of the longest word by comparing their lengths. [GFGTABS] Python s =
    1 min read
  • Python Program for Convert characters of a string to opposite case
    Given a string, convert the characters of the string into the opposite case,i.e. if a character is the lower case then convert it into upper case and vice-versa. Examples: Input : geeksForgEeksOutput : GEEKSfORGeEKSInput: hello every oneOutput: HELLO EVERY ONEExample 1: Python Program for Convert ch
    7 min read
  • Python program to count upper and lower case characters without using inbuilt functions
    Given a string that contains both upper and lower case characters in it. The task is to count a number of upper and lower case characters in it. Examples :Input : Introduction to Python Output : Lower Case characters : 18 Upper case characters : 2 Input : Welcome to GeeksforGeeks Output : Lower Case
    3 min read
  • Python Program that Extract words starting with Vowel From A list
    Given a list with string elements, the following program extracts those elements which start with vowels(a, e, i, o, u). Input : test_list = ["all", "love", "get", "educated", "by", "gfg"] Output : ['all', 'educated'] Explanation : a, e are vowels, hence words extracted.Input : test_list = ["all", "
    5 min read
  • Python Program to get the Longest Alphabetic order of Kth index from list values
    Given a string list, the task is to write a Python program to extract Strings that form the longest increasing alphabetic order at the Kth index. K should be less than the minimum length of all strings. Input : test_list = ["gfg", "is", "best", "for", "geeks", "and", "cs"], K = 0 Output : ['best', '
    4 min read
  • Python program to find Maximum value from dictionary whose key is present in the list
    Given a list with dictionary keys and a dictionary, extract maximum from dictionary values, whose key is present in list. Examples: Input : test_dict = {"Gfg": 4, "is" : 5, "best" : 10, "for" : 11, "geeks" : 3}, test_list = ["Gfg", "best", "geeks"] Output : 10 Explanation : Max value is 11, but not
    6 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences