1 заметка с тегом

Function

Python: Divide the number into random digits

Assume that we have an aim: divide a given number into defined number of random digits.The random digits must be equally distributed among all parts. So let’s try to write the code.

from random import randint

def divide_number(number, parts_number, allow_zero = False):
	"""
	Divide a given number into bunch of digits.

	@param int $number Number
	@param int $parts_number Number of parts
	@param bool $allow_zero Let the function use zero in a result array

	@return bool|array
        """
	if (parts_number > number):
		raise ValueError("Number of parts can't be higher than the number");

	parts = []
	number_rest = number

	for i in range(1, parts_number + 1):
		if (i == parts_number):
			parts.append(number_rest)
			break
		else: 
			new_number = randint(0, number_rest) if allow_zero else randint(1, (number_rest - (parts_number - i)) // 2)

		number_rest -= new_number
		parts.append(new_number)

	return parts

Description

int $number — the given number.
int $parts_number — a number of parts.
bool $allow_zero — allow to use zero in result list

The function returns a list of digits or raise exception in case parts_number more than number.

Tests

Dividing 20 into 5 digits

Array
(
    [0] => 1
    [1] => 6
    [2] => 3
    [3] => 2
    [4] => 8
)

Dividing 143 into 7 digits

Array
(
    [0] => 65
    [1] => 12
    [2] => 19
    [3] => 3
    [4] => 22
    [5] => 2
    [6] => 20
)
2017   Function   Python