1

SPY GAME: Write a function spy_game() that takes in a list of integers and returns as per cases- Case 1: spy_game([1,2,4,0,0,7,5]) --> '007'
Case2: spy_game([1,7,2,0,4,5,0]) --> '700'

This below code is not working. My spy_list is also changing even it is outside the for loop

def spy_game(nums):
spy_num=''
spy = True
spy_list=nums
for num in nums:
    while spy:
        if num == 0 or num == 7:
            spy_num += str(num)
            spy_list.pop(0)
            break
        else:
            spy = False
            
    while not spy:
        spy_list.pop(0)
        spy = True            
return (spy_num)

While when I pass the list itself instead of nums in for loop, it works

please suggest

def spy_game(nums):
spy_num=''
spy = True
spy_list=nums
for num in [1,0,2,4,0,5,7]:
    while spy:
        if num == 0 or num == 7:
            spy_num += str(num)
            spy_list.pop(0)
            break
        else:
            spy = False
            
    while not spy:
        spy_list.pop(0)
        spy = True            
return (spy_num)
kanishk kashyap
  • 63
  • 1
  • 10

1 Answers1

1

I do not know python very well but I do see the issue. When setting

syp_nums = nums

you are stating that these two lists are they same so one action applys to the other one. You need to initialize a new list for spy nums that have the same value. Python will also allow you to copy

see this stackoverflow question How to clone or copy a list

spy_nums = nums.copy()
Mike
  • 623
  • 6
  • 26