Can you assume that each word is separated by a space (one and only one), and that there are no leading and trailing spaces? If so, let's say your list of strings is "list-1". Then you could make a list of word counts as:
list-2=[i.count(" ")+1 for i in list-1]
Then the max word count is:
and the string in list-1 with that count is:
There are several ways to do this, including dictionaries, loops, etc.
A simple solution would be to use a DSU (decorate, sort, undecorate).
Let's assume you have the following list:
my_list = ["I like apples", "Remember to eat your greens", Drink plenty of water"]
We can use the split() method on every string in my_list to get a list of the words composing it:
"I like apples".split()
["I", "like", "apples"]
Now we can call the built in len() method on the result:
len(["I", "like", "apples"])
Which is exactly the amount of words in that sentence.
Now that we know how to count the amount of words in each item, we can create nice pairs (tuples) of (amount of words in item, item):
Once you have all pairs in a separate list, and since Python sorts tuples based on the value of their first item (second if first is identical and so forth), you can just call max(seperate_list) and min(seperate_list) and you'll have your answers.
We basically decorated each item in the original list with the "key" we wanted to sort by. We could have also used a DSU pattern to sort my_list by any other criteria we wished (e.g. has the word "rice" in it, has an odd number of letters, etc.)
Hi, the replies were really helpful..thanks for that !!!
Write a C program that should create a 10 element array of random integers (0 to 9). The program should total all of the numbers in the odd positions of the array and compare them with the total of the numbers in the even positions of the array and indicate ...
Hi. so this is actually a continuation from another question of mineHere but i was advised to start a new thread as the original question was already answered.
This is the result of previous question answered :
code for the listbox - datagridview interaction
At the top of the code ...
I have a 2d matrix with dimension (3, n) called A, I want to calculate the normalization and cross product of two arrays (b,z) (see the code please) for each column (for the first column, then the second one and so on).
the function that I created to find the ...