In this post:

  • anagram example
    • check two words if they are anagrams
    • extract anagrams from list
  • palindrome example
    • palindrome - python way
    • palindrome - with iteration

You can check also Anagrams and Palindromes in Java

Anagrams with python

Anagram is any word or sentence whose scrambled letters create a different word or phrase. Anagrams are words or phrases that share the same letters that appear in a different order.

Several examples:

  • ASTRONOMER -> MOON STARER
  • ELEVEN PLUS TWO -> TWELVE PLUS ONE
  • DORMITORY -> DIRTY ROOM

check two words if they are anagrams

Code example checking if two words are anagrams:

def checkAnagram(word1, word2):
    listWord1 = list(word1)
    listWord1.sort()
    listWord2 = list(word2)
    listWord2.sort()
    return (listWord1 == listWord2)

print(checkAnagram("face", "cafe"))
print(checkAnagram("face", "caffe"))

result:

True
False

Extract anagrams from list with python:

from collections import defaultdict

def extractAnagrams(word_List):
    d = defaultdict(list)
    for word in word_List:
        key = "".join(sorted(word))
        d[key].append(word)
    return d

def printAnagrams(word):
    d = extractAnagrams(word)
    for key, anagrams in d.items():
        if len(anagrams) > 1:
            print(key, anagrams)

word_List = ["face", "caffe", "cafe", "milk", "limk", "abc"]
printAnagrams(word_List)

result:

acef ['face', 'cafe']
iklm ['milk', 'limk']

Palindromes with python

Palindrome is a word or phrase that reads the same way - backwards and forwards. Palindromes are anagrams which differs from an anagram because it requires specific order. Checking if a word is a palindrome is much easier than anagrams.

Examples:

  • RADAR
  • RACECAR
  • CIVIC
  • NOON

palindrome - python way

Sample code checking if two words are palindromes:

wordA = 'banana'
wordB = 'ana'

def isPalindrome(word):
    return str(word) == str(word)[::-1]

def isPalindromeRev(word):
    return word == ''.join(reversed(word))

def isPalindromeLis(word):
    return list(word) == list(reversed(word))

print(isPalindrome(wordA))
print(isPalindrome(wordB))

print(isPalindromeRev(wordA))
print(isPalindromeRev(wordB))

print(isPalindromeLis(wordA))
print(isPalindromeLis(wordB))

result:

False
True
False
True
False
True

palindrome with iteration

The example above use more pythonic way of palindrome check. Another way by checking for palindromes is by iterating over the word. The next example show how to check a number if it's a palindrome:

numberA = 101
numberB = 1010

def numberPalidrome(n):
    temp=n
    rev=0
    while(n>0):
        dig=n%10
        rev=rev*10+dig
        n=n//10
    print(temp==rev)

numberPalidrome(numberA)
numberPalidrome(numberB)

result:

True
False