Tuesday, February 25, 2014

Write a program to find the longest word made of other words in a list of words.

__author__ = 'nitin'

   
EXAMPLE 
Input: test, tester, testertest, testing, testingtester
Output: testingtester

import sys

DEFAULT_FILE = 'words.txt'

def recsol(word, first=False):
    if not word or (not first and word in wordset): return True
    for i in range(1, len(word)):
        start = word[0:i]
        end = word[i:]
        if start in wordset and recsol(end):
            return True
    return False

filename = sys.argv[1] if len(sys.argv) > 1 else DEFAULT_FILE

header = '# Largest to Smallest Composable Strings #'
print '\n' + '#'*len(header) + '\n' + header + '\n' + '#'*len(header)
with open(filename, 'r') as f:
    wordstr = f.read()
wordlst = wordstr.split()
wordlst.sort(key=len, reverse=True)
wordset = set(wordlst)
cnt = 1
for s in wordlst:
    if recsol(s, True):
        print str(cnt) + '. ' + s
        cnt += 1

You are given an array of integers (both positive and negative). Find the continuous sequence with the largest sum. Return the sum.

__author__ = 'nitin'

def get_max_sum(a):
    max_sum=0
    sum_int=0
    i=0
    iter_a=len(a)
    result_list=[]
    while iter_a!=0:
        sum_int=sum_int+ a[i]
        if max_sum < sum_int:
            result_list.append(a[i])
        if max_sum>sum_int and sum_int >0:
            result_list.append(a[i])
        elif sum_int<0 and="" iter_a="">1:
            sum_int=0
            sum_int, result_list=negative_check(iter_a,i,sum_int,a,result_list)
        i=i+1
        iter_a=iter_a -1
    return max_sum, result_list

def negative_check(sec_iter_a,j,sum_int,a,result_list):
    while sec_iter_a>1:
        sum_int=sum_int + a[j+1]
        if sum_int>0:
            result_list=[]
            break
        j=j+1
        sec_iter_a=sec_iter_a -1
    sum_int=0
    return sum_int, result_list

if __name__=="__main__":
    a_list=[-2,-3,-4,3,4]
    result,result_list=get_max_sum(a_list)
    print "Result :",result, "and Result List :",result_list

My Profile

My photo
can be reached at 09916017317