""" CTCI - Question 1.3 """ # returns true if the two strings are anagram # else false # do we care about captial and small strings? - if yes use string.toLower() # do we care about white spaces? - if yes use string.strip() def isAnagram(s1, s2): s1 = sorted(list(s1.strip().lower())) s2 = sorted(list(s2.strip().lower())) return s1 == s2 # test case: Matches: # 1. capital letters print isAnagram("aBcc", "bCca") == True # 2. white spaces print isAnagram("hello ", "hello") == True # test case: Fails # 1. print isAnagram("aBc", "bCca") == False # 2. white spaces print isAnagram("hello ", "hllo") == False # Q 1.4 # compress a string like "aaabbcaa" to -> "a3b2c1a2" # what about capital small? def compress(s): l = [] last = s[0] count = 1 for i in range(1, len(s)): if s[i] == last: count += 1 else: l.extend([last, str(count)]) last = s[i] count = 1 l.extend([last, str(count)]) return ''.join(l) print compress("aaabbcaa")
Run
Reset
Share
Import
Link
Embed
Language▼
English
中文
Python Fiddle
Python Cloud IDE
Follow @python_fiddle
Browser Version Not Supported
Due to Python Fiddle's reliance on advanced JavaScript techniques, older browsers might have problems running it correctly. Please download the latest version of your favourite browser.
Chrome 10+
Firefox 4+
Safari 5+
IE 10+
Let me try anyway!
url:
Go
Python Snippet
Stackoverflow Question