这是使用while
循环的答案。
>>> dividend = 45
>>> divisor = 7
你有dividend
奶牛和divisor
牛仔(不要被这个幼稚的例子冒犯:这是对我大儿子的眨眼……)。一开始,所有的奶牛都在畜栏里。
>>> remainder = dividend
而且你没有把任何牛给任何牛仔。
>>> quotient = 0
现在,做一个欧几里得除法:虽然你可以给每个牛仔一头牛......
>>> while remainder >= divisor:
... remainder -= divisor # remove those `divisor` cows from the corral...
... quotient += 1 # ...and note that you have given one more cow to each cow-boy
结果是:
>>> quotient, remainder
(6, 3)
希望清楚!
编辑关于for
循环
如果您绝对需要使用 a ,则可以使用afor
来模拟a 。while
break
我们假设dividend
and divisor
>= 1。因此,quotient <= divisor
。
>>> remainder = dividend
>>> quotient = 0
>>> for _ in range(dividend):
... if remainder < divisor:
... break
... quotient += 1
... remainder -= divisor
>>> quotient, remainder
(6, 3)
如果break
不允许,那么您可以使用 hack(我不建议这样做:break
只是隐藏在迭代器中):
>>> remainder = dividend
>>> quotient = 0
>>> for _ in iter(lambda: remainder >= divisor, False):
... quotient += 1
... remainder -= divisor
>>> quotient, remainder
(6, 3)
您还可以使用递归函数:
>>> def divm(divid, divis):
... if divid < divis:
... return 0, divid
... else:
... quotient_minus_one, remainder = divm(divid - divis, divis)
... return quotient_minus_one + 1, remainder
>>> divm(dividend, divisor)
(6, 3)