楼梯有n阶,每次只能走1阶或两阶,编程实现
#逆向递归 num = 10 def stairs_top_to_bottom(count): rand = np.random.choice([1,2]) if count ==num - 1 or count ==num: print(num - count,'last',end = ' ') else: stairs_top_to_bottom(count + rand) print(rand,end = ' ') stairs_top_to_bottom(0) print( ) #常规做法 def stairs_up(n): count = 0 List = [] while count < n: rand = np.random.choice([1, 2]) if count == num - 1: List.append(1) count += 1 else: count += rand List.append(rand) print(List) print(' '.join(map(str,List))) #必须变成字符串才能拼接 stairs_up(10)1 last 1 2 1 2 2 1
1 last 1 2 1 2 2 1
[1, 2, 1, 2, 2, 1, 1]
1 2 1 2 2 1 1