Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (45.3k points)

I am doing a per-word character-counter from a user input.

However, it seems that if there are duplicate words (of the similar case) from the input, my codes will only output the first word (the duplicates will not be included).

I have used the split, len and for loop for this.

sentence = input("Enter a sentence: ")

splitting = sentence.split()

final = {x:len(x) for x in splitting}

print(final)

  • Sample input: New phone alert! Your new phone will be available next week.

  • Expected output: {'New': 3, 'phone': 5, 'alert!': 6, 'Your': 4, 'new': 3, 'phone': 5, 'will': 4, 'be': 2 ...}

  • Actual output: {'New': 3, 'phone': 5, 'alert!': 6, 'Your': 4, 'new': 3, 'will': 4, 'be': 2 ...}

It shows both 'New' and 'new' as their cases don't match. However, 'phone' is displayed only once.

1 Answer

0 votes
by (16.8k points)

You can get word, characterCount in that word in a list of list.

listOfList = [[x , len(x)] for x in splitting]

print(listOfList)

Result:

[['New', 3], ['phone', 5], ['alert!', 6], ['Your', 4], ['new', 3], ['phone', 5], ['will', 4], ['be', 2], ['available', 9], ['next', 4], ['week.', 5]]

Related questions

0 votes
2 answers
asked Oct 3, 2019 in Python by Tech4ever (20.3k points)
0 votes
1 answer
0 votes
1 answer
asked Oct 3, 2019 in Python by Sammy (47.6k points)

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...