如何确定 Python 中给定总数的最少整数求和数?
How do I determine the fewest number of summed integers for a given total in Python?
可能有一个算法,但我不确定它是什么。
对于一个整数X,求和为X的整数的最少个数,并且整数之和小于或等于Y且可以在和中重复。
例如:
X=95
Y=1
This is 1 (95 times)
X=39
Y=5
This is 5 (7 times) and 4 (1 time)
X=53
Y=11
This is 11 (4 times), 9 (1 time)
我看到这是一种递归除法,同时减少分母直到达到零,但可能有更优雅的方法。
更新:
两件事:
- 我没有意识到为此所需的划分不会超过 1 级。我假设可能有 numerator/denominator 的组合,其中在第二次出现除法后会有余数,但至少在我的用例中,没有。
- 不,没有什么Python特定的,这就是我正在使用的。
您可以使用divmod()
求出商和余数:
X = 95
Y = 1
quotient, remainder = divmod(X, Y)
if remainder == 0:
print(f"This is {Y} ({quotient} times)")
else:
print(f"This is {Y} ({quotient} times) and {remainder} (1 time)")
这会打印:
This is 1 (95 times)
X=int(input("What is X"))
Y=int(input("What is Y"))
divisor = X // Y # integer divide
remainder = X % Y
if remainder:
print(f"This is {Y} ({divisor} times), {remainder}")
else:
print(f"This is {Y} ({divisor} times)")
你问的是将一个数除以另一个数,并提供余数。
使用 //
运算符将两个数相除,返回一个整数。 %
运算符将提供两个数相除时的余数。
def div(x, y):
return x//y, x%y
x = 95
y = 15
count, remainder = div(x, y)
text = 'This is {} ({} times)'.format(x, count)
if remainder > 0:
text += ' and {} ({} times)'.format(remainder, 1)
print(text)
可能有一个算法,但我不确定它是什么。
对于一个整数X,求和为X的整数的最少个数,并且整数之和小于或等于Y且可以在和中重复。
例如:
X=95
Y=1
This is 1 (95 times)
X=39
Y=5
This is 5 (7 times) and 4 (1 time)
X=53
Y=11
This is 11 (4 times), 9 (1 time)
我看到这是一种递归除法,同时减少分母直到达到零,但可能有更优雅的方法。
更新:
两件事:
- 我没有意识到为此所需的划分不会超过 1 级。我假设可能有 numerator/denominator 的组合,其中在第二次出现除法后会有余数,但至少在我的用例中,没有。
- 不,没有什么Python特定的,这就是我正在使用的。
您可以使用divmod()
求出商和余数:
X = 95
Y = 1
quotient, remainder = divmod(X, Y)
if remainder == 0:
print(f"This is {Y} ({quotient} times)")
else:
print(f"This is {Y} ({quotient} times) and {remainder} (1 time)")
这会打印:
This is 1 (95 times)
X=int(input("What is X"))
Y=int(input("What is Y"))
divisor = X // Y # integer divide
remainder = X % Y
if remainder:
print(f"This is {Y} ({divisor} times), {remainder}")
else:
print(f"This is {Y} ({divisor} times)")
你问的是将一个数除以另一个数,并提供余数。
使用 //
运算符将两个数相除,返回一个整数。 %
运算符将提供两个数相除时的余数。
def div(x, y):
return x//y, x%y
x = 95
y = 15
count, remainder = div(x, y)
text = 'This is {} ({} times)'.format(x, count)
if remainder > 0:
text += ' and {} ({} times)'.format(remainder, 1)
print(text)