Software Engineering

How you can Spherical as much as the Subsequent A number of of 5 in Python

How you can Spherical as much as the Subsequent A number of of 5 in Python
Written by admin


The problem

Given an integer as enter, are you able to spherical it to the following (that means, “increased”) a number of of 5?

Examples:

enter:    output:
0    ->   0
2    ->   5
3    ->   5
12   ->   15
21   ->   25
30   ->   30
-2   ->   0
-5   ->   -5
and so forth.

Enter could also be any constructive or damaging integer (together with 0).

You possibly can assume that each one inputs are legitimate integers.

The answer in Python code

Choice 1:

def round_to_next5(n):
    return n + (5 - n) % 5

Choice 2:

def round_to_next5(n):
    whereas npercent5!=0:
        n+=1
    return n

Choice 3:

import math
def round_to_next5(n):
    return math.ceil(n/5.0) * 5

Check circumstances to validate our resolution

inp = 0
out = round_to_next5(inp)
take a look at.assert_equals(out, 0, "Enter: {}".format(inp))

inp = 1
out = round_to_next5(inp)
take a look at.assert_equals(out, 5, "Enter: {}".format(inp))

inp = -1
out = round_to_next5(inp)
take a look at.assert_equals(out, 0, "Enter: {}".format(inp))

inp = 5
out = round_to_next5(inp)
take a look at.assert_equals(out, 5, "Enter: {}".format(inp))

inp = 7
out = round_to_next5(inp)
take a look at.assert_equals(out, 10, "Enter: {}".format(inp))

inp = 20
out = round_to_next5(inp)
take a look at.assert_equals(out, 20, "Enter: {}".format(inp))

inp = 39
out = round_to_next5(inp)
take a look at.assert_equals(out, 40, "Enter: {}".format(inp))

About the author

admin

Leave a Comment