Tuesday, October 30, 2018

Q2: Highest scoring word in a string of words

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

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

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.

eg:

string = "Hi this is tish"
Ranks for each word will be like: [17, 56, 28, 56]
And highest rand words are this and tish. But "this" is the answer since it is first occurrence.

4 comments:

  1. Hi,
    Below is one of the possible way. feel free to add your answer for the same.

    string = "hi this is tish"

    sl = string.lower().split()
    print("splited string " + str(sl))
    rl = [sum([ord(i) - 96 for i in str]) for str in sl]
    print("rank of each word" + str(rl))

    output = sl[rl.index(max(rl))]
    print("Highest rank word :" + output)

    ReplyDelete
  2. Solution 1:
    def high(x):
    import string
    high_score_word = ''
    count=0
    for word in x.split(' '):
    temp=0
    for i in word:
    temp+=string.ascii_lowercase.index(i)+1
    if temp>count:
    count=temp
    high_score_word=word
    return high_score_word

    print(high('hi hello')


    Solution 2:
    import string
    s=x.split(' ')
    scores = [sum([string.ascii_lowercase.index(i)+1 for i in word])for word in s]
    ind= scores.index(sorted(scores)[-1])
    return s[ind]

    print(high('hi hello')

    ReplyDelete
  3. One liner ;p(Haha)
    inp = "Hi this is tish"

    print(inp.split()[max(enumerate([sum([{chr(i):j for i,j in zip(range(ord('a'), ord('z')),range(1,27))}[ch] for ch in s]) for s in inp.lower().split()]), key=lambda v: v[1])[0]])

    ReplyDelete