当前位置: 首页 > news >正文

python算法【楼梯数量计算】

题目:
https://share.feijipan.com/s/XROFZ9vF
在这里插入图片描述

from random import seed, randint
import sys
from collections import defaultdictdef display_grid():for i in range(len(grid)):print('   ', ' '.join(str(int(grid[i][j] != 0)) for j in range(len(grid))))try:arg_for_seed, density, dim = (int(x) for x ininput('Enter three positive integers: ').split())if arg_for_seed < 0 or density < 0 or dim < 0:raise ValueError
except ValueError:print('Incorrect input, giving up.')sys.exit()
seed(arg_for_seed)
grid = [[randint(0, density) for _ in range(dim)] for _ in range(dim)]
print('Here is the grid that has been generated:')
display_grid()def stairs_in_grid():result = {}for size in range(2, (dim + 1) // 2 + 1):for row in range(dim - size + 1):for col in range(dim - (size - 1) * 2):if grid[row][col] == -size:continuepossible = Truetemp_row, temp_col = row, colfor temp_col in range(col, col + size):if grid[temp_row][temp_col] == 0:possible = Falsebreakif possible:step = 0while temp_row < dim - (size - 1) and temp_col < dim - (size - 1):another_step = Truefor temp_row in range(temp_row + 1, temp_row + size):if grid[temp_row][temp_col] == 0:another_step = Falsefor temp_col in range(temp_col + 1, temp_col + size):if grid[temp_row][temp_col] == 0:another_step = Falseif another_step is False:breakgrid[temp_row][temp_col - size + 1] = -sizestep += 1if step >= 1:contain = Falseprevious_info = result.get(size, [])for index in range(len(previous_info)):pair = previous_info[index]if pair[0] == step:contain = Trueprevious_info[index][1] = previous_info[index][1] + 1breakif contain is False:previous_info.append([step, 1])result[size] = sorted(previous_info)return result# POSSIBLY DEFINE OTHER FUNCTIONS# A dictionary whose keys are step sizes, and whose values are lists of pairs
# of the form (number_of_steps, number_of_stairs_with_that_number_of_steps_of_that_step_size)
# ordered from smallest to largest number_of_steps.
stairs = stairs_in_grid()
for step_size in sorted(stairs):print(f'\nFor steps of size {step_size}, we have:')for nb_of_steps, nb_of_stairs in stairs[step_size]:stair_or_stairs = 'stair' if nb_of_stairs == 1 else 'stairs'step_or_steps = 'step' if nb_of_steps == 1 else 'steps'print('    ', nb_of_stairs, stair_or_stairs, 'with', nb_of_steps, step_or_steps)

作答

from random import seed, randint
import sys
from collections import defaultdictdef display_grid():for i in range(len(grid)):print('   ', ' '.join(str(int(grid[i][j] != 0)) for j in range(len(grid))))try:# arg_for_seed, density, dim = (int(x) for x in input('Enter three positive integers: ').split())arg_for_seed, density, dim = 0, 3, 9if arg_for_seed < 0 or density < 0 or dim < 0:raise ValueError
except ValueError:print('Incorrect input, giving up.')sys.exit()
seed(arg_for_seed)
grid = [[randint(0, density) for _ in range(dim)] for _ in range(dim)]
print('Here is the grid that has been generated:')
display_grid()# 1
# def is_valid_stair(grid, dim, r, c, step_size):
#     if any(grid[r][c + i] == 0 for i in range(step_size)):
#         return False
#     return True
# def is_valid_stair(grid, dim, r, c, step_size):
#     check = [grid[r][c + i] for i in range(step_size)]
#     print(f"Checking stair top at ({r},{c}), size={step_size}, values={check}")
#     return all(v != 0 for v in check)# def count_steps(grid, dim, start_r, start_c, step_size):
#     steps = 0
#     cur_r, cur_c = start_r, start_c + step_size - 1
#     while cur_r + step_size <= dim and cur_c + step_size <= dim:
#         invalid = False
#         for k in range(1, step_size):
#             if grid[cur_r + k][cur_c] == 0 or grid[cur_r + step_size - 1][cur_c + k] == 0:
#                 invalid = True
#                 break
#         if invalid: 
#             break
#         steps += 1
#         grid[cur_r + step_size - 1][cur_c] = -step_size  
#         cur_r += 1
#         cur_c += 1
#     return steps# def stairs_in_grid():
#     results = defaultdict(list)
#     for s in range(2, (dim + 1) // 2 + 1):
#         for r in range(dim - s + 1):
#             for c in range(dim - (s - 1) * 2):
#                 if grid[r][c] == -s: 
#                     continue
#                 if not is_valid_stair(grid, dim, r, c, s):
#                     continue
#                 steps = count_steps(grid, dim, r, c, s)
#                 if steps > 0:
#                     for i, (st, cnt) in enumerate(results[s]):
#                         if st == steps:
#                             results[s][i] = (st, cnt + 1)
#                             break
#                     else:
#                         results[s].append((steps, 1))
#         results[s] = sorted(results[s])
#     results = {k: v for k, v in results.items() if v}
#     return results# 2
def stairs_in_grid():result = {}# 2-5for size in range(2, (dim + 1) // 2 + 1):used = [[False for _ in range(dim)] for _ in range(dim)]# 0-7for row in range(dim - size + 1):# 0-7for col in range(dim - (size - 1) * 2):if used[row][col] or grid[row][col] == 0:continuepossible = Truefor cc in range(col, col + size):if grid[row][cc] == 0:possible = Falsebreakif not possible:continueelse:step = 0cur_row, cur_col = row, col + size - 1while cur_row < dim - size + 1 and cur_col < dim - size + 1:another_step = True# downfor cur_row in range(cur_row, cur_row + size):if grid[cur_row][cur_col] == 0:another_step = Falsebreak# rightfor cur_col in range(cur_col, cur_col + size):if grid[cur_row][cur_col] == 0:another_step = Falsebreakif another_step is False:breakused[cur_row][cur_col - size + 1] = Truestep += 1if step >= 1:contain = Falseprevious_info = result.get(size, [])for index in range(len(previous_info)):pair = previous_info[index]if pair[0] == step:contain = Truepair[1] += 1breakif contain is False:previous_info.append([step, 1])result[size] = sorted(previous_info)return resultstairs = stairs_in_grid()
for step_size in sorted(stairs):print(f'\nFor steps of size {step_size}, we have:')for nb_of_steps, nb_of_stairs in stairs[step_size]:stair_or_stairs = 'stair' if nb_of_stairs == 1 else 'stairs'step_or_steps = 'step' if nb_of_steps == 1 else 'steps'print('    ', nb_of_stairs, stair_or_stairs, 'with', nb_of_steps, step_or_steps)"""
A10 = A9+A8 A9 = A8 + A7A8 = A7+A6序列"""
http://www.dtcms.com/a/315363.html

相关文章:

  • Hadoop HDFS 3.3.4 讲解~
  • linux的用户操作(详细介绍)
  • 牛客笔试题错题整理(1)
  • Field and wave electromagnetics 复习
  • 【编程实践】点云曲率计算与可视化
  • Pimpl惯用法
  • 【秋招笔试】2025.08.03虾皮秋招笔试-第二题
  • [GYCTF2020]FlaskApp
  • 0804 进程
  • 【笔记】重学单片机(51)(下)
  • 数据结构——并查集及C++实现
  • Javascript面试题及详细答案150道(046-060)
  • 5天从0到1!用阿里Qwen3-Coder开发故障调度指挥室系统,运维也能搞定开发
  • 嵌入式 C 语言入门:函数指针基础笔记 —— 从计算器优化到指针本质
  • 文本转语音(TTS)脚本
  • 【项目实践】在系统接入天气api,根据当前天气提醒,做好plan
  • C语言的控制语句
  • 16day-人工智学习-机器学习-特征工程
  • 【世纪龙科技】虚拟技术助力职教汽车自动变速器拆装虚拟实训软件
  • RFID技术在汽车倍速链中的应用:驱动智能制造的隐形引擎
  • Windows/Linux入侵排查
  • CPP学习之多态
  • Python高频元素分析技术:高效找出序列中出现次数最多的元素
  • 【Unity3D实例-功能-镜头】第三人称视觉
  • FeiQ飞秋安装教程:FeiQ.1060559168 详细安装步骤(附注意事项)​
  • 【QT】常⽤控件详解(三)常用按钮控件PushButton RadioButton CheckButton Tool Button
  • 茗鹤工业低代码可视化技术开发平台
  • 网络相关命令
  • 全国计算机二级C语言二级考试通关笔记
  • 风光储并网协同运行simulink仿真模型实现