antonydeepak
BAN USERLittle cowboy coding but it should work. The idea is to go recursive and solve each bracket seprately. Follow the BODMAS rule and set priorities (except 'B' has a -ve priority because w want to remove that.
expression = "(a+(b*c))*(d*(f*j))"
operations = {'*':2,'+':1,'(':-1,')':-1}
operators = ['*','+']
bracket_stack = []
brackets = ['(',')']
def remove_brackets(expr,start_location,total_length,left_operator,bracket_stack):
i = start_location+1
is_bracket_removable = True
while expr[i] != ')':
element = expr[i]
if element == '(':
i = remove_brackets(expr,i,total_length,operations[expr[i-1]],bracket_stack)
else:
if element in operators and is_bracket_removable:
if left_operator > operations[element]:
is_bracket_removable = False
i+=1
if is_bracket_removable and i+1 < total_length and operations[expr[i+1]] > left_operator:
is_bracket_removable = False
if is_bracket_removable:
expr[start_location] = ''
expr[i] = ''
return i
i=0
expr = list(expression)
while i<len(expr):
c = expr[i]
if c == '(':
i = remove_brackets(expr,i,len(expr),-1 if i==0 else operations[expr[i-1]],bracket_stack)
i+=1
print ''.join([c for c in expr if c!=''])
May not be the best algorithm but something that I came up quick.
#!/usr/bin/python3
dictionary =['abacus','deltoid','gaff','giraffe','microphone','reef','qar']
letters = ['a','e','f','f','g','i','r','q']
def isContained(source_word,destination_word):
j=0
for i in range(len(source_word)):
while(j<len(destination_word)):
if source_word[i] == destination_word[j]:
break;
j=j+1
else:
return False
return True
if __name__=='__main__':
sorted_dictionary = {word:''.join(sorted(word)) for word in dictionary} #change to dict(), if you are using python2.
sorted_letters = ''.join(sorted(letters))
longest_word = None
for word,sorted_word in sorted_dictionary.items():
if isContained(sorted_word,sorted_letters) and (not longest_word or len(sorted_word) > len(longest_word)):
longest_word = word
print(longest_word)
Naive implementation. When in doubt just brute
- antonydeepak April 18, 2013