Algorithm for Human Towering

后端 未结 4 1916
悲哀的现实
悲哀的现实 2021-01-02 22:39

In Cracking the Coding Interview, Fourth Edition, there is such a problem:

A circus is designing a tower routine consisting of people standing atop

4条回答
  •  不知归路
    2021-01-02 22:44

    Tried solving this myself, did not meant to give 'ready made solution', but still giving , more to check my own understanding and if my code(Python) is ok and would work of all test cases. I tried for 3 cases and it seemed to work of correct answer.

    #!/usr/bin/python
    #This function takes a list of tuples. Tuple(n):(height,weight) of nth person
    def htower_len(ht_wt):
        ht_sorted = sorted(ht_wt,reverse=True)
        wt_sorted = sorted(ht_wt,key=lambda ht_wt:ht_wt[1])
        max_len = 1 
    
        len1 = len(ht_sorted)
        i=0
        j=0
        while i < (len1-1):
            if(ht_sorted[i+1][1] < ht_sorted[0][1]):
                max_len = max_len+1
            i=i+1           
    
        print "maximum tower length :" ,max_len
    
    ###Called above function with below sample app code.
    testcase =1 
    print "Result of Test case ",testcase   
    htower_len([(5,75),(6.7,83),(4,78),(5.2,90)])
    
    testcase = testcase + 1
    print "Result of Test case ",testcase   
    htower_len([(65, 100),(70, 150),(56, 90),(75, 190),(60, 95),(68, 110)])
    
    testcase = testcase + 1
    print "Result of Test case ",testcase   
    
    htower_len([(3,2),(5,9),(6,7),(7,8)])   
    

提交回复
热议问题