Sunday 19 March 2017

Python Snippets

Integer Division with Ceil:

Description: Without using math module, getting the ceil functionality. The condition when evaluated to True, gets converted into 1 (in terms of integer) and added to result. When it is evaluated to False, gets converted to 0. Click here for reference thread.

def num_buses(n):
    """ (int) -> int

    Precondition: n >= 0

    Return the minimum number of buses required to transport n people.
    Each bus can hold 50 people.

    >>> num_buses(75)
    2
    """
    assert n>0
    return (n//50)+(n%50>0)

Swapping Array Portions:

Description: Rather than using any loop, make use of array slicing.

def swap_k(L, k):
    """ (list, int) -> NoneType

    Precondtion: 0 <= k <= len(L) // 2

    Swap the first k items of L with the last k items of L.

    >>> nums = [1, 2, 3, 4, 5, 6]
    >>> swap_k(nums, 2)
    >>> nums
    [5, 6, 3, 4, 1, 2]
    """
    assert 0 <= k <= len(L) // 2
    start_block = L[:k]
    end_block = L[-k:]
    L[:k] = end_block
    L[-k:] = start_block

Do you like this article?