Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Python program to print words from a sentence with highest and lowest ASCII value of characters
ASCII (American Standard Code for Information Interchange) is a character encoding system that represents every character as a unique 7-bit binary code. ASCII values range from 0 to 127, where each character has a specific numerical representation. For example, the ASCII code for a space character is 32, and for digit '1' it is 49.
In Python, you can find the ASCII code of a character using the ord() function, which takes a character as input and returns its ASCII value. For example, ord('A') returns 65.
Problem Statement
Given a string, find and print the words that have the highest and lowest average ASCII values of their characters.
Sample Example
Input: "today is a sunny day"
Output:
Highest ASCII value = "sunny" Lowest ASCII value = "a"
Explanation:
Average ASCII values: today = (116 + 111 + 100 + 97 + 121) / 5 = 109 is = (105 + 115) / 2 = 110 a = 97 / 1 = 97 sunny = (115 + 117 + 110 + 110 + 121) / 5 = 114.6 day = (100 + 97 + 121) / 3 = 106
Method 1: Using Simple Iteration
Split the sentence into words and calculate the average ASCII value for each word to find the highest and lowest ?
def ascii_avg(word):
"""Returns the average ASCII value of a word."""
return sum(ord(c) for c in word) / len(word)
def find_highest_lowest_ascii(sentence):
"""Finds words with highest and lowest average ASCII values."""
words = sentence.split()
high_word = words[0]
low_word = words[0]
high_avg = ascii_avg(words[0])
low_avg = ascii_avg(words[0])
for word in words[1:]:
avg = ascii_avg(word)
if avg > high_avg:
high_word = word
high_avg = avg
elif avg < low_avg:
low_word = word
low_avg = avg
print(f"Highest ASCII value: {high_word}")
print(f"Lowest ASCII value: {low_word}")
# Test the function
find_highest_lowest_ascii("today is a sunny day")
Highest ASCII value: sunny Lowest ASCII value: a
Method 2: Using Built-in Functions
Use Python's max() and min() functions with a custom key function ?
def find_highest_lowest_builtin(sentence):
"""Uses built-in functions to find highest and lowest ASCII words."""
words = sentence.split()
# Define key function for average ASCII calculation
avg_ascii = lambda word: sum(ord(c) for c in word) / len(word)
high_word = max(words, key=avg_ascii)
low_word = min(words, key=avg_ascii)
print(f"Highest ASCII value: {high_word}")
print(f"Lowest ASCII value: {low_word}")
# Test the function
find_highest_lowest_builtin("today is a sunny day")
Highest ASCII value: sunny Lowest ASCII value: a
Method 3: Using Sorting
Sort all words by their average ASCII values and pick the first and last elements ?
def find_highest_lowest_sorting(sentence):
"""Sorts words by average ASCII values to find extremes."""
words = sentence.split()
# Sort words by average ASCII values
sorted_words = sorted(words, key=lambda w: sum(ord(c) for c in w) / len(w))
print(f"Highest ASCII value: {sorted_words[-1]}")
print(f"Lowest ASCII value: {sorted_words[0]}")
# Test the function
find_highest_lowest_sorting("today is a sunny day")
Highest ASCII value: sunny Lowest ASCII value: a
Method 4: Using Dictionary and Heap
Store word-ASCII mappings in a dictionary and use a heap for efficient retrieval ?
import heapq
def find_highest_lowest_heap(sentence):
"""Uses heap to efficiently find highest and lowest ASCII words."""
words = sentence.split()
# Calculate average ASCII for each word
word_avg = {}
for word in words:
word_avg[word] = sum(ord(c) for c in word) / len(word)
# Create heaps for max and min
max_heap = [(-avg, word) for word, avg in word_avg.items()]
min_heap = [(avg, word) for word, avg in word_avg.items()]
heapq.heapify(max_heap)
heapq.heapify(min_heap)
high_word = heapq.heappop(max_heap)[1]
low_word = heapq.heappop(min_heap)[1]
print(f"Highest ASCII value: {high_word}")
print(f"Lowest ASCII value: {low_word}")
# Test the function
find_highest_lowest_heap("today is a sunny day")
Highest ASCII value: sunny Lowest ASCII value: a
Comparison
| Method | Time Complexity | Space Complexity | Best For |
|---|---|---|---|
| Simple Iteration | O(n*m) | O(1) | Small datasets, memory-efficient |
| Built-in Functions | O(n*m) | O(1) | Clean, readable code |
| Sorting | O(n log n) | O(n) | When you need sorted order |
| Heap | O(n log n) | O(n) | Large datasets, priority queues |
Note: n = number of words, m = average word length
Conclusion
The built-in function approach using max() and min() provides the cleanest and most readable solution. For large datasets, consider the heap approach, while simple iteration works best for memory-constrained environments.
