Home > Enterprise >  Can you please help me to solve the below python question
Can you please help me to solve the below python question

Time:01-29

Evenly Divisible: Create a function that gets three arguments x,y,z as input and return the number of values in the range between x and y(both x and y are included) and evenly divisible by z.

Sample case:- Sample Input 1 20 2 Sample Output 10

Explanation: From the limit 1 to 20 the values 2,4,6,810,1214,16,18,20 are evenly divisible by 2,so the total number is evenly divisible by 10.

CodePudding user response:

I don't understand what your question is trying to say, but here is a function to find all numbers between x and y that are divisible by z.

def divisible_in_range(x, y, z):
    if x > y:
        x, y = y, x
    for i in range(x, y   1):
        if i % z == 0:
            print(i)

# Call it with 3 values

This prints all the numbers, like so (inputs 1, 20, 10)

2
4
6
8
10
12
14
16
18
20

If this isn't what you expected, include more detail about what your function should do in the question.

I would recommend trying out some code before posting a question, as all this code requires is knowing what a function is and knowing the syntax for a for loop.

EDIT Looking at your comment, you could do this:

def divisible_in_range(x, y, z):
    if x > y:
        x, y = y, x
    count = 0
    for i in range(x, y   1):
        if i % z == 0:
            print(i)
            count  = 1
    return count

And call it like this:

print(f"The number of numbers between 1 and 20 divisible by 2 is: {divisible_in_range(1, 20, 2)}")

Output:

2
4
6
8
10
12
14
16
18
20
The number of numbers between 1 and 20 divisible by 2 is: 10

CodePudding user response:

If you understand it, you might use list comprehension as well.

def evendiv(x,y,z):
    return(len([i for i in range(x, y 1) if i%z==0]))

print(evendiv(2,26,4))
  •  Tags:  
  • Related