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!

1
  • 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)] Commented May 26, 2021 at 9:45

3 Answers 3

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)
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

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]

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.