Reputation: 113
I wanted to make a function that easily split a number by its divider and returns the quotient and remainder the following way:
[6,6,6,3] = function(21, 6)
[2,2,2] = function(6,2)
I use a while loop counting until i reach zero:
divider = 6
start = 21
ret = []
while start >= divider:
ret.append(divider)
start -= divider
if start:
ret.append(start)
I was wondering if there was a more easier/pythonic way to do this.
Upvotes: 0
Views: 142
Reputation: 73460
You can just calculate, using e.g. floor division and modulo:
def function(n, d):
return [d] * (n // d) + [n%d] if n%d else []
>>> function(21, 6)
[6, 6, 6, 3]
>>> function(6, 2)
[2, 2, 2]
There is also the built-in divmod
function, that calculates both in one step:
def function(n, d):
div, mod = divmod(n, d)
return div * [d] + bool(mod) * [mod]
Upvotes: 3
Reputation: 1128
Simple:
def function(a, b):
result = []
for x in range(a//b):
result.append(b)
if a % b != 0:
result.append(a % b)
return result
Upvotes: 0