Highest Scoring Word

jenny
انضم: 2025-08-24 15:11:06
2024-06-05 05:25:58

Given a string of words, you need to find the highest scoring word.

Each letter of a word scores points according to its position in the alphabet: `a = 1, b = 2, c = 3` etc.

For example, the score of `abad` is `8` (1 + 2 + 1 + 4).

You need to return the highest scoring word as a string.

If two words score the same, return the word that appears earliest in the original string.

All letters will be lowercase and all inputs will be valid.

Image preview

jenny
انضم: 2025-08-24 15:11:06
2024-07-02 22:23:16

The solution here is:

`def highest_scoring_word(s):`

` def word_score(word):`

` # Calculate the score of a word by summing the position values of its characters`

` return sum(ord(char) - ord('a') + 1 for char in word)`

` `

` words = s.split() # Split the input string into words`

` max_score = 0`

` highest_word = ""`

` `

` for word in words:`

` score = word_score(word)`

` # Update the highest word if the current word has a higher score`

` if score > max_score:`

` max_score = score`

` highest_word = word`

` # If scores are equal, keep the first occurring word`

` elif score == max_score and highest_word == "":`

` highest_word = word`

` `

` return highest_word`

`# Example usage:`

`input_string = "abad ace bat cat"`

`print(highest_scoring_word(input_string)) # Output: "ace"`

jenny
انضم: 2025-08-24 15:11:06
2024-07-25 10:37:07
[[9,31],[29]]
Facebook X (Twitter) Instagram LinkedIn Telegram WhatsApp