简体   繁体   中英

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

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 .

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.

from collections import OrderedDict

s = "Bob and Anna are meeting at noon"
d = OrderedDict()
lastKey = None

for i in s.split():
  if i.upper() == i.upper()[::-1]:
    d[i] = []
    lastKey = i
  else:
    if lastKey: d[lastKey].append(i)

print d

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM