SoFunction
Updated on 2024-11-14

Python Walking Stairs Problem Solution Example

This article example describes the Python walk up the stairs problem solving method. Shared for your reference, as follows:

# -*- coding:utf-8 -*-
#!python3
'''
Downstairs Problem. There are h steps to walk from upstairs to downstairs, and there are two ways to walk each step:
Walking 1 step and walking 2 steps, ask how many walkable options there are. Programming with recursive and iterative ideas
'''
'''
Analysis: The problem can be considered in reverse, in terms of whether the last time you took 1 step or 2 steps.
'''
def take_stairs_recursive(n):
  if n == 1:
    return 1
  elif n == 2:
    return 2
  else:
    return take_stairs_recursive(n-1)+take_stairs_recursive(n-2)
'''
It's actually the Fibonacci sequence
'''
def take_stairs(n):
  if n == 1:
    return 1
  if n == 2:
    return 2
  a,b = 1,2
  result = 0
  for i in range(3,n+1):
    result = a + b
    a = b
    b = result
  return result
print(take_stairs_recursive(10))
print(take_stairs(10))

Run results:

89
89

Readers interested in more Python related content can check out this site's topic: theSummary of Python mathematical operations techniques》、《Python Data Structures and Algorithms Tutorial》、《Summary of Python function usage tips》、《Summary of Python string manipulation techniques》、《Python introductory and advanced classic tutorialsand theSummary of Python file and directory manipulation techniques

I hope the description of this article will help you in Python programming.