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 - Word starting at Index
Next article icon

Python - Maximum Scoring word

Last Updated : 02 May, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

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 

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

Output
The 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).
     

Next Article
Python - Word starting at Index
author
manjeet_04
Improve
Article Tags :
  • Python
  • Python Programs
  • Python string-programs
Practice Tags :
  • python

Similar Reads

  • Python - Word starting at Index
    Sometimes, while working with Python, we can have a problem in which we need to extract the word which is starting from a particular index. This can have a lot of applications in school programming. Let's discuss certain ways in which this task can be performed. Method #1: Using a loop This is a bru
    2 min read
  • Word location in String - Python
    Word location in String problem in Python involves finding the position of a specific word or substring within a given string. This problem can be approached using various methods in Python, such as using the find(), index() methods or by regular expressions with the re module. Using str.find()str.f
    4 min read
  • Python - Words Lengths in String
    We are given a string we need to find length of each word in a given string. For example, we are s = "Hello world this is Python" we need to find length of each word so that output should be a list containing length of each words in sentence, so output in this case will be [5, 5, 4, 2, 6]. Using Lis
    2 min read
  • Python | Maximum Difference in String
    Sometimes, we might have a problem in which we require to get the maximum difference of 2 numbers from Strings but with a constraint of having the numbers in successions. This type of problem can occur while competitive programming. Let’s discuss certain ways in which this problem can be solved. Met
    4 min read
  • Python - Sort Strings by Maximum ASCII value
    Given strings list, perform sort by Maximum Character in String. Input : test_list = ["geeksforgeeks", "is", "best", "cs"] Output : ["geeksforgeeks", "is", "cs", "best"] Explanation : s = s = s < t, sorted by maximum character. Input : test_list = ["apple", "is", "fruit"] Output : ["apple", "is",
    4 min read
  • Maximum String Value Length of Key - Python
    The task of finding the maximum string length of a specific key in a list of dictionaries involves identifying the longest string associated with the given key. Given a list of dictionaries, the goal is to extract the string values of the specified key, compute their lengths and determine the maximu
    3 min read
  • Python - Maximum of String Integer list
    Sometimes, while working with data, we can have a problem in which we receive a series of lists with data in string format, which we wish to find the max of each string list integer. Let’s discuss certain ways in which this task can be performed. Method #1 : Using loop + int() This is the brute forc
    4 min read
  • Python - Row with Maximum Record Element
    Sometimes, while working with Python Records, we can have a problem in which we need to find the row with maximum record element. This kind of problem can come in domains of web development and day-day programming. Let's discuss certain ways in which this task can be performed. Input : test_list = [
    7 min read
  • Python | Extract words from given string
    In Python, we sometimes come through situations where we require to get all the words present in the string, this can be a tedious task done using the native method. Hence having shorthand to perform this task is always useful. Additionally, this article also includes the cases in which punctuation
    4 min read
  • Python - Sequence Assignment to Words
    Given a String of words, assign an index to each word. Input : test_str = 'geeksforgeeks is best' Output : {0: 'geeksforgeeks', 1: 'is', 2: 'best'} Explanation : Index assigned to each word. Input : test_str = 'geeksforgeeks best' Output : {0: 'geeksforgeeks', 1: 'best'} Explanation : Index assigned
    5 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