Python - Maximum Scoring word
Last Updated :
02 May, 2023
Given a String, the task is to write a Python program to compute maximum scoring words i.e words made of characters with a maximum positional summation.
Examples:
Input : test_str = 'geeks must use geeksforgeeks for cs knowledge'
Output : geeksforgeeks
Explanation : Sum of characters positional values for "geeksforgeeks" word is maximum, hence result.
Input : test_str = 'geeks love geeksforgeeks'
Output : geeksforgeeks
Explanation : Sum of characters positional values for "geeksforgeeks" word is maximum, hence result.
Method #1 : Using split() + loop + ord() + ascii_lowercase
In this, we initially split each word using split(), get positional magnitude using ord(), ascii_lowercase checks for correct pool of characters chosen for evaluation.
Python3
# Python3 code to demonstrate working of
# Maximum Scoring word
# Using split() + loop + ord() + ascii_lowercase
import string
# initializing string
test_str = 'geeks must use geeksforgeeks for cs knowledge'
# printing original string
print("The original string is : " + str(test_str))
score = 0
max_sc = 0
res = ''
for wrd in test_str.split():
score = 0
# computing score
for lttr in wrd:
if lttr in string.ascii_lowercase:
score += ord(lttr) - 96
# updating maximum
if score > max_sc:
max_sc = score
res = wrd
# printing result
print("Maximum scoring word : " + str(res))
Output:
The original string is : geeks must use geeksforgeeks for cs knowledge
Maximum scoring word : geeksforgeeks
Method #2 : Using sum() + loop + ord()
Similar to above method, only difference here being sum() is used for task of summation rather than internal loop.
Python3
# Python3 code to demonstrate working of
# Maximum Scoring word
# Using sum() + loop + ord()
import string
# initializing string
test_str = 'geeks must use geeksforgeeks for cs knowledge'
# printing original string
print("The original string is : " + str(test_str))
score = 0
max_sc = 0
res = ''
for wrd in test_str.split():
# computing score
# sum for cumulation
score = sum(ord(lttr) - 96 for lttr in wrd if lttr in string.ascii_lowercase)
# updating maximum
if score > max_sc:
max_sc = score
res = wrd
# printing result
print("Maximum scoring word : " + str(res))
Output:
The original string is : geeks must use geeksforgeeks for cs knowledge
Maximum scoring word : geeksforgeeks
Time Complexity: O(n2)
Auxiliary Space: O(n)
Method 3: Using a dictionary to store scores of each word:
Step-by-step approach:
- Split the string into words
- Initialize a dictionary scores to an empty dictionary
- For each word in the list of words:
- Initialize a variable score to 0
- For each character in the word:
- Add the ASCII value of the character to the score
- Add the score as a value to the dictionary with the word as the key
- Return the key with the maximum value in the dictionary
Python3
def max_scoring_word_2(test_str):
words = test_str.split()
scores = {}
for word in words:
score = 0
for char in word:
score += ord(char)
scores[word] = score
return max(scores, key=scores.get)
test_str = 'geeks love geeksforgeeks'
print(max_scoring_word_2(test_str)) # Output: geeksforgeeks
Time complexity: O(n*m), where n is the number of words and m is the maximum length of a word
Auxiliary Space: O(n)
Method #3: Using map() + sum() + max()
- Convert the input string into a list of words using the split() method.
- Define a lambda function to calculate the score of each word. This function will use the map() function to map each character to its corresponding score, using ord() - 96, and then calculate the sum of those scores using the sum() function.
- Use the max() function to find the word with the maximum score.
- Print the result.
Python3
import string
# initializing string
test_str = 'geeks must use geeksforgeeks for cs knowledge'
# printing original string
print("The original string is : " + str(test_str))
# define function to calculate score of a word
score_func = lambda word: sum(map(lambda c: ord(c) - 96, word))
# split input string into a list of words
words = test_str.split()
# calculate the score of each word and find the word with maximum score
res = max(words, key=score_func)
# printing result
print("Maximum scoring word : " + str(res))
OutputThe original string is : geeks must use geeksforgeeks for cs knowledge
Maximum scoring word : geeksforgeeks
Time Complexity: O(nk + m).
- The code splits the input string into words using the split() method, which takes O(n) time where n is the length of the string.
- Then it uses the map() function to apply the lambda function to each word, which takes O(k) time where k is the length of the longest word in the string.
- The max() function takes O(m) time, where m is the number of words in the list.
- Therefore, the overall time complexity of this code is O(nk + m).
Auxiliary Space: O(k + m).
- This code uses O(k) extra space to store the lambda function and O(m) extra space to store the list of words.
- The max() function uses O(1) extra space.
- Therefore, the overall auxiliary space complexity of this code is O(k + m).
Similar Reads
Python Tutorial | Learn Python Programming Language
Python Tutorial â Python is one of the most popular programming languages. Itâs simple to use, packed with features and supported by a wide range of libraries and frameworks. Its clean syntax makes it beginner-friendly.Python is:A high-level language, used in web development, data science, automatio
10 min read
Python Interview Questions and Answers
Python is the most used language in top companies such as Intel, IBM, NASA, Pixar, Netflix, Facebook, JP Morgan Chase, Spotify and many more because of its simplicity and powerful libraries. To crack their Online Assessment and Interview Rounds as a Python developer, we need to master important Pyth
15+ min read
Python OOPs Concepts
Object Oriented Programming is a fundamental concept in Python, empowering developers to build modular, maintainable, and scalable applications. By understanding the core OOP principles (classes, objects, inheritance, encapsulation, polymorphism, and abstraction), programmers can leverage the full p
11 min read
Python Projects - Beginner to Advanced
Python is one of the most popular programming languages due to its simplicity, versatility, and supportive community. Whether youâre a beginner eager to learn the basics or an experienced programmer looking to challenge your skills, there are countless Python projects to help you grow.Hereâs a list
10 min read
Python Exercise with Practice Questions and Solutions
Python Exercise for Beginner: Practice makes perfect in everything, and this is especially true when learning Python. If you're a beginner, regularly practicing Python exercises will build your confidence and sharpen your skills. To help you improve, try these Python exercises with solutions to test
9 min read
Python Programs
Practice with Python program examples is always a good choice to scale up your logical understanding and programming skills and this article will provide you with the best sets of Python code examples.The below Python section contains a wide collection of Python programming examples. These Python co
11 min read
Enumerate() in Python
enumerate() function adds a counter to each item in a list or other iterable. It turns the iterable into something we can loop through, where each item comes with its number (starting from 0 by default). We can also turn it into a list of (number, item) pairs using list().Let's look at a simple exam
3 min read
Python Data Types
Python Data types are the classification or categorization of data items. It represents the kind of value that tells what operations can be performed on a particular data. Since everything is an object in Python programming, Python data types are classes and variables are instances (objects) of thes
9 min read
Python Introduction
Python was created by Guido van Rossum in 1991 and further developed by the Python Software Foundation. It was designed with focus on code readability and its syntax allows us to express concepts in fewer lines of code.Key Features of PythonPythonâs simple and readable syntax makes it beginner-frien
3 min read
Input and Output in Python
Understanding input and output operations is fundamental to Python programming. With the print() function, we can display output in various formats, while the input() function enables interaction with users by gathering input during program execution. Taking input in PythonPython input() function is
8 min read