import numpy as np
import pandas as pd
# n 矩阵n*n 斐波那契蛇
def makeSnake(n):
snakeArr = np.zeros((n,n))
# 制作一个point和方向控制变量 direction
xPos = yPos =0
direction =1 # 1右2下3左4上
# 获取fibonacci数列
fib =fibonacci(n*n)
# 循环填充数据
for num in fib:
snakeArr[xPos][yPos]= num
# 寻找下一个点
if direction ==1:if yPos+1< n and snakeArr[xPos][yPos+1]==0:
yPos +=1else:
direction =2
xPos +=1
elif direction ==2:if xPos+1< n and snakeArr[xPos+1][yPos]==0:
xPos +=1else:
direction =3
yPos -=1
elif direction ==3:if xPos-1>=0 and snakeArr[xPos][yPos-1]==0:
yPos -=1else:
direction =4
xPos -=1else:if xPos-1>=0 and snakeArr[xPos-1][yPos]==0:
xPos -=1else:
direction =1
yPos +=1print(snakeArr)
# num 整个数列的长度
def fibonacci(num):
fiArr =[1,1]
one = two =1
res =0for rn in range(num-2):
res = one + two
fiArr.append(res)
one,two = two,res
fiArr.reverse()return fiArr
if __name__ =='__main__':
# print(fibonacci(10))makeSnake(4)
结果
你好中国
用python解答
import numpy as np
import pandas as pd
# 找寻单词的每个字母在矩阵中的位置并返回字母坐标 argwhere
def findChrPosition(maritx,word):
chrPos =[]for wd in word:
xyArr = np.where(maritx == wd)
chrPos.append(list(zip(xyArr[0], xyArr[1])))return chrPos
# 检查两点是否有关联性
def checkPointRelation(point1,point2):if(point1[0]== point2[0] and abs(point1[1]-point2[1])==1) or (point1[1]==point2[1] and abs(point1[0]-point2[0])==1):return True
else:return False
# 数组维数 word你要找的单词
def findWord(n,word):
initArr = np.array(list(map(lambda x:chr(x),np.random.randint(65,91,size=n*n)))).reshape((n,n))print(initArr)
wordPos =findChrPosition(initArr,word) # [c[(0,1),(0,2),(4,8),(5,7)],h[(1,1),(4,9),(6,7),(8,10),(12,16)],i[(),()]]
paths =[[]for i in range(len(word)-1)] # [[[(0,1),(1,1)],[(4,8),(4,9)],[(5,7),(6,7)]]]for r in range(len(word)-1):if r ==0:for p1 in wordPos[0]:for p2 in wordPos[1]:ifcheckPointRelation(p1,p2):
paths[r].append([p1,p2])else:
# print(paths)for o1 in paths[r-1]: # [(0,1),(1,1)]for p3 in wordPos[r+1]:ifcheckPointRelation(o1[-1],p3):
# o1.append(p3)
# print(o1)
paths[r].append(o1+[p3])print(paths[-1])if __name__ =='__main__':findWord(200,'CHINA')