0

I have an array, p=(1,2,4,5,7,10...) and I would like to input a 0 in where the array deviates from f=(1,2,3,4,5,6...). I have tried using nested for loops but I can't work out how to make the desired output=(1,2,0,4,5,0,7,0,0,10...) using python.

This is all I have really got so far, but it iterates for p[0] with all the elements of f before moving on to p[1] and I don't know how to prevent this:

for x in f:
    for y in p:
        if x==y:
            print(x)
            break
        else:
            print('0')

Thank you!

k_marsh
  • 13
  • 2
  • 1
    Please provide **exact** inputs and the **exact** expected output. It isn't clear what oyu are trying to accomplish. I *thing* you just want `[x if x == y else 0 for x, y in zip(p,f)]` – juanpa.arrivillaga May 26 '21 at 09:45

3 Answers3

1

I'd suggest to make p a set so that checking membership is fast:

>>> p = (1,2,4,5,7,10)
>>> p_set = set(p)
>>> tuple([i if i in p_set else 0 for i in range(11)])
(0, 1, 2, 0, 4, 5, 0, 7, 0, 0, 10)
ignoring_gravity
  • 6,677
  • 4
  • 32
  • 65
0

code:

p =(1,2,4,5,7,10)
f =tuple(range(1,11))
for x in f:
    for y in p:
        if x == y:
            print(x)
            break
    else:
        print('0')

result:

1
2
0
4
5
0
7
0
0
10
leaf_yakitori
  • 2,232
  • 1
  • 9
  • 21
0

You don't need a nested loop, just iterate through the full numbers' array and insert a zero. Example

p = [1,2,3,4,5,6,7,8,9,10,11,12,13,14, 15]
f = [1,2,4,5,6,7,10,14,15]

for index,i in enumerate(p):
    if i == f[index]:
        pass
    else:
        f.insert(index, 0)

Result

[1, 2, 0, 4, 5, 6, 7, 0, 0, 10, 0, 0, 0, 14, 15]