Distinct words and their length, excluding those with lengths not Fibonacci, in a sentence
The code defines a function is_fibonacci_length(n) to check whether a given number is a Fibonacci number (by checking if its length is in the Fibonacci sequence). It then uses this function to create a dictionary named distinct_word_length_fibonacci using a dictionary comprehension in Python. This dictionary maps distinct words from the sentence to their respective lengths, but only for words with lengths that are Fibonacci numbers. Here's a step-by-step explanation of the code:
- def is_fibonacci_length(n) : This line defines a function named is_fibonacci_length that takes an integer n as input and checks whether n is a Fibonacci number by comparing its length to the Fibonacci sequence.
- Inside the function, a list fib is initialized with the first two Fibonacci numbers (0 and 1).
- A while loop checks whether the last number in the fib list (fib[-1]) is less than or equal to n. It continues to calculate Fibonacci numbers until the last one is less than or equal to n.
- If fib[-1] is equal to n, the function returns True because n is a Fibonacci number based on its length.
- If the loop completes without finding a Fibonacci number of the given length, the function returns False.
- sentence = "Hello, how are you?": This line defines a string variable called sentence containing the sentence "Hello, how are you?"
- distinct_word_length_fibonacci = {word: len(word) for word in set(sentence.split()) if is_fibonacci_length(len(word))}: This line creates the distinct_word_length_fibonacci dictionary using a dictionary comprehension. Here's how it works:
- {word: len(word) for word in set(sentence.split()) if is_fibonacci_length(len(word)} is the dictionary comprehension. It performs the following steps:
- sentence.split() splits the sentence string into a list of words.
- set(sentence.split()) creates a set of distinct words by removing duplicates.
- for word in set(sentence.split()) iterates over each distinct word in the set.
- is_fibonacci_length(len(word)) checks if the length of the word is a Fibonacci number using the is_fibonacci_length function.
- If a word's length is a Fibonacci number, it creates a key-value pair in the dictionary. The key (word) is the word itself, and the value (len(word)) is the length of the word.
- print(sentence): This line prints the original sentence, which is "Hello, how are you?", to the console.
- print(distinct_word_length_fibonacci): This line prints the distinct_word_length_fibonacci dictionary to the console.
Source Code
def is_fibonacci_length(n):
fib = [0, 1]
while fib[-1] <= n:
if fib[-1] == n:
return True
fib.append(fib[-1] + fib[-2])
return False
sentence = "Hello, how are you?"
distinct_word_length_fibonacci = {word: len(word) for word in set(sentence.split()) if is_fibonacci_length(len(word))}
print(sentence)
print(distinct_word_length_fibonacci)
Output
Hello, how are you?
{'how': 3, 'are': 3}