python-3.x - 最小步数可被 1 或 2 整除,但可被给定数整除
问题描述
我正在开发一个 python 程序,我想找到到达顶层所需的最小步数,这样步数应该可以被给定的数字整除m
这是我从这里获取的程序:
# A program to count the number of ways to reach n'th stair
# Recurssive program to find n'th fibonacci number
def fib(n):
if n <= 1:
return n
return fib(n-1) + fib(n-2)
# returns no. of ways to reach s'th stair
def countWays(s):
return fib(s + 1)
# Driver program
s = 10
print("Number of ways = ", countWays(s) )
在这里,我得到了方法的总数,但我想用那些可以被给定数字整除的方法来过滤它们,说m
,怎么做?
Example:
1) s = 10 and m = 2, output should be 6, as the steps are {2,2,2,2,1,1}
2) s = 3 and m = 5 output should be -1 as the possible steps are {1,1,1}, {2,1}, {1,2}
--> here none of them (means 3 steps, 2 steps, 2 steps) are divible by 5.
解决方案
s = 10
m = 2
if s % m == 0:
print(s)
outputs: 10
使用 % 是一个模运算。这提供了除法后的“余数”。因此,如果您的项目没有余数,则它可以被所选数字整除。
# A program to count the number of ways to reach n'th stair
# Recursive function used by countWays
def countWaysUtil(n,m):
res = [0 for x in range(n)] # Creates list res witth all elements 0
res[0],res[1] = 1,1
for i in range(2,n):
j = 1
while j<=m and j<=i:
res[i] = res[i] + res[i-j]
j = j + 1
return res[n-1]
# Returns number of ways to reach s'th stair
def countWays(s,m):
return countWaysUtil(s+1, m)
# Driver Program
s,m = 4,2
print "Number of ways =",countWays(s,m)
# Contributed by Harshit Agrawal
推荐阅读
- javascript - React/Ant Design 修复后退按钮
- java - 如何在 2 活动中使用相同的 ImageView
- javascript - 如何将范围的值传递给我的变量调用?
- python - subprocess.Popen() 返回值中的 stderr 来自哪里?
- osgi - 使用 Equinox 启动器在 OSGi 中使用多个配置文件
- powershell - 如何使用 powershell 获取线程等待原因?
- html - 一旦从 dom 中删除另一个 SVG 元素,SVG 路径就会消失
- python - 使用 python.exe 执行时,导入包在 venv 中不起作用
- javascript - JavaScript E.Listener
- asp.net-core - 使用 Cloud Foundry 部署具有多个项目的 Asp.Net Core 应用程序时出错