﻿ Python: Find the string consisting of all the words whose lengths are prime numbers - w3resource

Python: Find the string consisting of all the words whose lengths are prime numbers

Python Programming Puzzles: Exercise-64 with Solution

Write a Python program to find the string consisting of all the words whose lengths are prime numbers.

```Input:
The quick brown fox jumps over the lazy dog.
Output:
The quick brown fox jumps the

Input:
Omicron Effect: Foreign Flights Won't Resume On Dec 15, Decision Later.
Output:
Omicron Effect: Foreign Flights Won't On Dec 15,
```

Visual Presentation:

Sample Solution:

Python Code:

``````# License: https://bit.ly/3oLErEI

def test(strs):
# Join words whose lengths are prime numbers using list comprehension
return " ".join(strs for strs in strs.split() if is_prime(len(strs)))

def is_prime(n):
# Check if a number is prime
return n > 1 and all(n % j for j in range(2, int(n ** 0.5) + 1))

# Example 1
strs1 = "The quick brown fox jumps over the lazy dog."
print("Original list of words:")
print(strs1)
print("Words whose lengths are prime numbers in the said string:")
print(test(strs1))

# Example 2
strs2 = "Omicron Effect: Foreign Flights Won't Resume On Dec 15, Decision Later."
print("\nOriginal list of words:")
print(strs2)
print("Words whose lengths are prime numbers in the said string:")
print(test(strs2))
``````

Sample Output:

```Original list of numbers:
The quick brown fox jumps over the lazy dog.
Words whose lengths are prime numbers in the said string:
The quick brown fox jumps the

Original list of numbers:
Omicron Effect: Foreign Flights Won't Resume On Dec 15, Decision Later.
Words whose lengths are prime numbers in the said string:
Omicron Effect: Foreign Flights Won't On Dec 15,
```

Flowchart:

Python Code Editor :

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.

﻿