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:

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

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:

Flowchart: Python - Find the sum of the even elements that are at odd indices.

Python Code Editor :

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

Previous: Find the sum of the even elements that are at odd indices in a given list.
Next: Circular shift number.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://198.211.115.131/python-exercises/puzzles/python-programming-puzzles-64.php