Home > Software engineering >  My code works but it is very different from the solution?
My code works but it is very different from the solution?

Time:01-15

The problem is:

SPY GAME: Write a function that takes in a list of integers and returns True if it contains 007 in order

def spy_game(nums):
    for x in range(0,len(nums)):
        if nums[x]==0:
            for y in range(x,len(nums)):
                if nums[y]==0:
                    for z in range(y,len(nums)):
                        if nums[z]==7:
                            return True

    return False

but the solution given is:

def spy_game(nums):

    code = [0,0,7,'x']
    
    for num in nums:
        if num == code[0]:
            code.pop(0)   # code.remove(num) also works
       
    return len(code) == 1

Can someone explain the solution please? Is my code still fine?

CodePudding user response:

You solution is poor because it only allows for a specific 3-digit sequence - i.e., 0,0,7. Imagine what you would have to do if the sequence was changed.

The provided solution is broken. For example, if the input is [0, 2, 3, 0, 7, 1] it will return True.

Here's something that actually works:

def spy_game(nums):
    code = [0, 0, 7]
    for i in range(len(nums)-len(code)):
        if nums[i:i len(code)] == code:
            return True
    return False

CodePudding user response:

There is nothing wrong with different implementations, per se. Both algorithms loop through the list in O(n).

However, your code also works if the term '07' is in the code, as it looks at the index x twice: once in the first loop, and again at the start of the second loop. Use y in range(x 1, len(nums)) instead.

The given solution uses the fact that the list contains only integers, so that if '007' is encountered, the list will have an 'x' in it still. It feels a bit weird to me, since I cant see a use case where having a list [0, 0, 7] and checking len(code) == 0 after the code.pop(0) wouldn't work.

  •  Tags:  
  • Related