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序列"""