Thursday, April 30, 2015

Palindrome of first characters of strings in a list

I've scored 70/100 for this problem because i've missed few cases like empty list,list with one word(although this is implemented in actual algorthm).There might be some error crept
"""
Problem: Take first letters of a words in a list and check if it is palindrome or not,you can remove as many as letters and see if the word is
palindrome or not

Ex:  

inputlist=["Ajay","IS","ALIEN"]
Solution: 
First letters of words ==> AIA
Check if the word is palindrome or not ;
if word is not a palindrome drop any letter and check if it is a palindrome.
do this till you find a palindrome.

"""

from itertools import *
def PalindromeLengthPuzzle(input1): #==> ['ADAM','EVE','ABRAHAM','ELVIS']
  myList=[]
  for i in range(len(input1)):
   myList.append(input1[i][0]) #==> adding first letters to myList( myList = ['A','E','A','E']

  """
 Concept 1:

 1. How to join elements in a list to a single string? (Most frequently you will come across )
 Ex:1 ===> no space between ('') so you'll get an output :abc
 >>> myList=['a','b','c']
 >>> mystring=''.join(myList)
 >>> mystring
 'abc'
 Ex:2 ==> Space (' ') so you'll get an output : abc
 >>> mystring1=' '.join(myList)
 >>> mystring1
 'a b c'


  """
  mystring=''.join(myList) #==> mystring='AEAE'
  print mystring

  if len(input1) == 0:
   return 0,''
  elif len(input1) ==1:
   return mystring,1
  elif len(input1) == 2:
   if mystring[0:] == mystring[::-1] :
    return mystring,len(mystring)


  elif len(input1)>2:
   for i in reversed(range(len(mystring)+1)):
    #print i

    my_list=[''.join(item) for item in combinations(mystring,i)] # generate different combinations of 'AEAE' into a list
    #print my_list

    for item in my_list:
     #print my_list

     if item[0:] == item[::-1]:

      return len(item),item








input1=["Bharati","Akash","Bharat","BUMM","CAT","BAT","CUT","ATE","BY"]
input2=["Bharati"]
input3=['BOB','BAAB','BAABS']

print PalindromeLengthPuzzle(input1)
print PalindromeLengthPuzzle(input2)
print PalindromeLengthPuzzle([])
print PalindromeLengthPuzzle(input3)
"""
Output:

BABBCBCAB
(7, 'BABBBAB')
B
('B', 1)

(0, '')
BBB
(3, 'BBB')
[Finished in 0.0s]

"""





Learn python for fun.The popular blog with questions and answers to the python.Solutions to facebookhackercup,codejam,codechef.The fun way to learn python with me.Building some cool apps.

No comments:

Post a Comment