## 解析一道编程题（1）

### 题目

Q4: 使Python或者C++完成以下问题(30分)

Spiral Memory

You come across an experimental new kind of memory stored on an infinite two dimensional grid. Each square on the grid is allocated in a spiral pattern starting at a location marked 1 and then counting up while spiraling outward. For example, the first few squares are allocated like this:

While this is very space-efficient (no squares are skipped), requested data must be carried back to square 1 (the location of the only access port for this memory system) by programs that can only move up, down, left, or right. They always take the shortest path: the Manhattan Distance between the location of the data and square 1. For example: Data from square 1 is carried 0 steps, since it’s at the access port. Data from square 12 is carried 3 steps, such as: down, left, left. Data from square 23 is carried only 2 steps: up twice. Data from square 1024 must be carried 31 steps. How many steps are required to carry the data from the square identified in your puzzle input all the way to the access port? How to test your answer:

If you pass these 2 test cases, you can get the credits!

## 交通运输系统规划课设平均增长法python小程序

# 交通运输系统规划课程设计平均增长法求预测年出行矩阵python小程序
# 请打开Anaconda的jupyter Notebook，新建空程序，把这页的文字部分以一个整体全部复制进去，shift+enter运行即可
import numpy as np

od_matx = [[27000,5000,2500,4000,4000,4200,4200,1000,1000],  # 原始出行矩阵，如需处理不同出行矩阵，按格式输入即可
[4000,8000,2500,3000,5000,6500,1000,500,1000],
[8000,6000,4500,2800,2000,2800,1500,3000,1200],
[8000,7500,3000,6000,3500,2000,2000,2000,1300],
[10000,8000,5000,4000,8000,4000,1400,500,5000],
[8000,2000,4000,2000,2000,5000,5500,1000,1000],
[6000,2000,1000,1000,5000,5500,8000,500,6000],
[4000,8000,6000,2500,2000,2000,1500,9000,500],
[8000,2000,1000,1000,6000,3000,4000,500,12500]]
od_array = np.array(od_matx)

goal_matx = [[65000,38000,40000,45000,55000,35000,42000,42000,50000],  # 预测各小区生成总量
[100000,55000,35000,35000,45000,42000,35000,25000,40000]]  # 预测各小区吸引总量
goal_arra = np.array(goal_matx)
num = 0
while(True):
num = num + 1  # 计数器
o_sum = od_array.sum(axis=1)
d_sum = od_array.sum(axis=0)
od_sum_matx = np.concatenate([[o_sum],[d_sum]])

rate_matx = goal_matx/od_sum_matx

rate_aver_list = []
for i in rate_matx[0]:
for j in rate_matx[1]:
rate_aver_list.append((i+j)/2)

rate_aver_matx = np.array(rate_aver_list).reshape(np.shape(od_array))

od_array = np.multiply(od_array,rate_aver_matx)
index = np.abs(goal_arra-od_sum_matx)/goal_arra

# np.set_printoptions(precision=1)  # 设置精度

print("迭代第%d次，得出预测年出行矩阵："%num)
print(np.around(od_array))  # 四舍五入
# print(od_array)
# print(index)
print("收敛误差为：",index.max(),"\n")

keep_running = input("Try again? (y/n): ")  # 如需下一次迭代，在输入框中输入y并按回车即可，如不需要迭代了，回复n
if keep_running == 'n':  # 建议迭代个十几次，让收敛误差足够小且预测值趋于稳定
break