Home > Software engineering >  How can I find whether this equation works?
How can I find whether this equation works?

Time:10-14

So I programmed this code to find whether all numbers in a list are multiples of a number k: or not, but it doesn't seem to work. can anyone give some examples for me to draw ideas from?

CodePudding user response:

There two issues with your code.

First you need to use % to get the rest of the division x / k.

Second as you're doing it, you exit the function as soon as you have found a number in your list that is a multiple of k: you don't check remaining items in your list.

Here is a modified version of your code:

k = 4
a: list= [3, 4, 4, 3]
def allMultiplesofK(k, a):
    for x in list(a):
        if x % k != 0:
            return False
    return True  # all items of a are multiples of k
print(allMultiplesofK(k, a))

CodePudding user response:

Use modulo instead of floor division.

Floor division: This will gives you the quotient

Modulus: This will give you the remainder.

k = 4
a = [3, 4, 4, 3]
def allMultiplesofK(k, a):
    for x in list(a):
        if x % k == 0:
            return True
        else:
            return False
print(allMultiplesofK(k, a))
output: False

But this will not give all numbers result i.e it will print last values 3%4 False.

result = [True if i % k == 0 else False for i in a]
print(result)
Output: [False, True, True, False]

CodePudding user response:

Use %7 instead of //7. // will give you whole number quotient and % will give you remainder. Let use say some number 49, 49//7 is 7 and 49%7 is 0. Another example 26, 26//7 is 3 and 26%7 is 5

CodePudding user response:

In your code the return inside the loop will quit the loop as soon as the condition will be satisfied, so, it will will not check all numbers in the list. You can use for example list comprehension and the all function from the standard library, see docs,

def allMultiplesofK(k, a):
    return all(map(lambda p: p % k == 0, a))

    return all([p % k == 0 for p in a]) # with list comprehension

k = 4

a: list= [3, 4, 4, 8]        
print(allMultiplesofK(k, a))
# False

a: list= [12, 4, 4, 8]
print(allMultiplesofK(k, a))
# True

CodePudding user response:

You aren't actually checking every item of the loop.

for x in list(a):
        if x // k == 0:
            return True
        if x // k != 0:
            return False

This is returning from the function after only checking the first item in the list.

Also the way you are checking if one number is divisible by another isn't quite right. You should be using the modulo operator "%". This operator gives you the remainder after the division.

3 % 4 = 3 # since 4 goes into 3, 0 times with 3 remaining.

Therefore your program should become:

k = 4
a: list= [3, 4, 4, 3]
def allMultiplesofK(k, a):
    for x in list(a):
        if x % k != 0:
            return False
    return True
print(allMultiplesofK(k, a))
  • Related