Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

dictionary with palindromes to non palindromes?

I am sorry if this is too easy but I can't figure out how to build this dictionary.

I have a string for example

"Bob and Anna are meeting at noon"

and I want a dictionary with all palindromes pointing to a list of the following not-palindromes, so

{"Bob": ["and"], "Anna": ["are", "meeting", "at"], "noon": []}

I found out that I can check if a word is a palindrome with

word.lower() == word.lower()[::-1]

and I can also split a string into words with

string.split()

but I don't understand how to loop over the string and build the dictionary so that only the palindromes are keys and make a list at the same time.

Thanks for any help

like image 901
Flo Avatar asked Sep 25 '22 07:09

Flo


2 Answers

This code should work:

text = "Bob and Anna are meeting at noon"
words = {}
last_p = None
for word in text.split():
    word2 = word.lower()
    if word2 == word2[::-1]:
        words[word] = []
        last_p = word
    elif last_p:
        words[last_p].append(word)
print(words)

If there are any words in the sentence before the first palindrome, they will be ignored. If you want the items in the dictionary to stay in their original order, use the collections.OrderedDict class instead of the builtin dict.

like image 187
tjohnson Avatar answered Sep 28 '22 04:09

tjohnson


def is_palindrome(word):
    return word.lower() == word.lower()[::-1]


def task(string):
    words = string.split(' ')
    returned = dict()
    i = 0
    while i < len(words):
        if is_palindrome(words[i]):  # if palindrome
            returned[words[i]] = []
            j = i + 1
            while j < len(words) and not is_palindrome(words[j]):
                returned[words[i]].append(words[j])
                j += 1
        i += 1
    return returned

print(task("Bob and Anna are meeting at noon"))

Try to understand how it works, it's one of the things that you need to figure out for yourself sometimes.

Also it's worth mentioning that dictionaries aren't ordered so the end result's pairs may be differently arranged.

like image 32
Amit Gold Avatar answered Sep 28 '22 05:09

Amit Gold