Write a function, lenWords(STRING), that takes a string as an argument and returns a tuple containing length of each word of a string.

For example, if the string is "Come let us have some fun", the tuple will have (4, 3, 2, 4, 4, 3)

Answer

Answer by student

Write a function, lenWords(STRING), that takes a string as an argument - CBSE Class 12 Sample Paper for 2024 Boards

Detailed answer by teachoo

The question asks us to write a function, lenWords(STRING), that takes a string as an argument and returns a tuple containing the length of each word of a string. The function should perform the following steps:

  • Split the string into a list of words using space as a separator. The split() method returns a list of strings after breaking the given string by the specified separator. 
  • Create an empty list to store the lengths of words . A list is a collection of items that can be changed or modified. We can create an empty list using square brackets [ ].
  • Loop through each word in the list using a for loop . A for loop is used to iterate over a sequence, such as a list, tuple, or string. 
  • Get the length of the word using len() function. The len() function returns the number of items in an object, such as a list, tuple, or string.
  • Append the length to the lengths list. The append() method adds an item to the end of the list.
  • Convert the lengths list into a tuple using tuple() function . A tuple is a collection of items that cannot be changed or modified. The tuple() function creates a tuple from an iterable object, such as a list, set, or string.
  • Return the result tuple using return statement. The return statement exits a function and returns a value to the caller.

The final code for the function is as follows:

part 2 - Question 21 (Choice 2) - CBSE Class 12 Sample Paper for 2024 Boards - Solutions to CBSE Sample Paper - Computer Science Class 12 - Computer Science - Class 12

Remove Ads
Teachoo · Class 12 Explore Class 12
Davneet Singh's photo - Co-founder, Teachoo

Made by

Davneet Singh

Davneet Singh is an IIT Kanpur graduate and has been teaching for 16+ years. At Teachoo, he breaks down Maths, Science and Computer Science into simple steps so students understand concepts deeply and score with confidence.

Many students prefer Teachoo Black for a smooth, ad-free learning experience.