checkio (Counting tiles)

Nicola needs some help building a circular landing zone using the ice square tiles for their new Ice Base. Before he converts the area to a construction place, Nikola needs to figure out how many square tiles he will need.

Each square tile has size of 1x1 meters. You need to calculate how many whole and partial tiles are needed for a circle with a radius of N meters. The center of the circle will be at the intersection of four tiles. For example: a circle with a radius of 2 metres requires 4 whole tiles and 12 partial tiles.

Input: The radius of a circle as a float

Output: The quantities whole and partial tiles as a list, [solid, partial] as numbers.

Example:
?
1
2
3
4
checkio(2)==[4,12]
checkio(3)==[16,20]
checkio(2.1)==[4,20]
checkio(2.5)==[12,20]

先想到枚举每个格子的坐标,判断它在不在圆内,这样是O(r^2)。和大湿讨论后,想到改进,只需求出x=1,x=2,x=3...与圆的交点,然后根据这些交点的y坐标,就可以轻易轻松判断结果了。注意只需要算1/4圆的,最后答案乘以4,复杂度O(r)
from math import sqrt,ceil

def checkio(radius):
    tiles = partial = 0
    left_height = radius
    length = int(ceil(radius))
    square_radius = radius**2
    for x in range(1, length):
        height = sqrt(square_radius - x**2)
        tiles += int(height)
        partial += int(ceil(left_height)) - int(height)
        left_height = height
    partial += int(ceil(left_height))
    return [tiles*4, partial*4]



#These "asserts" using only for self-checking and not necessary for auto-testing
if __name__ == '__main__':
    assert checkio(2) == [4, 12], "N=2"
    assert checkio(3) == [16, 20], "N=3"
    assert checkio(2.1) == [4, 20], "N=2.1"
    assert checkio(2.5) == [12, 20], "N=2.5"


你可能感兴趣的:(checkio (Counting tiles))