Search code examples
pythonlogic

Could someone point out the error in my logic. (Coding Exercise)


So this is a question form the website HackerRank. I've given it my best shot and I can't for the life of me figure out what I'm doing wrong. The question goes as follows:

"It is New Year's Day and people are in line for the Wonderland rollercoaster ride. Each person wears a sticker indicating their initial position in the queue from 1 to n. Any person can bribe the person directly in front of them to swap positions, but they still wear their original sticker. One person can bribe at most two others.

Determine the minimum number of bribes that took place to get to a given queue order. Print the number of bribes, or, if anyone has bribed more than two people, print Too chaotic."

This is my attempt:

def minimumBribes(q):
    bribes = 0
    sorted_q  = sorted(q)
    total_moves = 0
    for i in range(len(q)):
        origin = sorted_q[i]
        current = q[i]
        moved = current - origin
        if moved > 0:
            if moved > 2:
                print("Too chaotic")
                return
            else:
                total_moves += moved
    print(total_moves)

I realize it's a bit wordy but I wanted to make my logic as clear as possible.

If I input q = [1,2,5,3,7,8,6,4] the expected output is 7 but I get 6

WHY!


Solution

  • q=[1,2,5,3,7,8,6,4]

    as you look in the question there is no order of bribe is mention one could bribe 2 people at a time or 1 people at a time

    there is no restriction that you cannot bribe if you get bribed by someone

    let us reverse the hole process and create this situation back like that in "q"

    '''

       sorted_q=[1,2,3,4,5,6,7,8]
       5 bribed 3 and 4 
       total_moved = 2
       
       sorted_q=[1,2,5,3,4,6,7,8]
       7 bribed 4 and 6 
       total_moved = 4
        
       sorted_q=[1,2,5,3,7,4,6,8]
       8 bribed 4 and 6
       total_moved = 6
    
       sorted_q=[1,2,5,3,7,8,4,6]
       here at this bribe by 6 to 4 just make your logic fail
       total_moved = 7
       
    
       sorted_q=[1,2,5,3,7,8,6,4]
        
    

    '''