0

I am trying to write a code for below pseudocode

for all element in list do
    match and condition
    if all match
       return True

for example, List A=[1,2,3,4,5],B=10

What I want is like

def match():
    for i in range(len(A)):
      if B%A[0]==0 and B%A[1]==0 and B%A[2]==0 and B%A[3]==0 and B%A[4]==0: #Generate all these 
        #and condition one by one
        #automatically in this function
          return True

How can I do?

NOTE:I am asking about write code match and condition with a loop, not write a remainder

AlexWithYou
  • 399
  • 1
  • 4
  • 14
  • Check out the python `all` function. Here is a good introduction https://stackoverflow.com/questions/19389490/how-do-pythons-any-and-all-functions-work. – Mitch Jun 01 '20 at 01:45

2 Answers2

1

Try this one:

result = all( [(B%a==0) for a in A] )
lenik
  • 23,228
  • 4
  • 34
  • 43
  • You can remove the `[ ]`, `result = all(B % x == 0 for x in A)`. You can save some memory since this wont generate a list – Mitch Jun 01 '20 at 01:42
  • @MitchelPaulin I intentionally wrote it that way to make it easier to understand for OP – lenik Jun 01 '20 at 01:43
  • Does adding `[]` make it easier to understand? – Mitch Jun 01 '20 at 01:44
  • @MitchelPaulin I hope it does. The original problem was not related to using extra memory or using the minimum amount of characters, more like to understanding or basic structures and possible operations. – lenik Jun 01 '20 at 01:45
1

You can use a pythonic one liner

result = all(B % x == 0 for x in A)

Or maybe in a slightly more familiar syntax

res = True
for x in A:
    if B % x != 0:
        res = False
        break
Mitch
  • 3,342
  • 2
  • 21
  • 31