gpt4 book ai didi

python - 如何在python中交叉2个二维数组?

转载 作者:行者123 更新时间:2023-11-30 23:24:10 25 4
gpt4 key购买 nike

我正在尝试制作一个程序,该程序将采用两个代表网格的文件并使它们重叠(填字游戏)。

让我更清楚地解释一下:

对于网格中的每个单元格,我试图找到一个既位于水平文件的行又位于垂直文件的列的字符。

文件“水平.txt”:

bac
def
hig

文件“vertical.txt”:

dhc
abf
gei

程序的输出:

abc
def
ghi

对于单元格 [0][0](左上角),水平文件第 0 行和垂直文件第 0 列上的字母都是“a”

基本上,行和列中的单词是字谜词,我想找到一种方法从前两个单词构建最终的表格。

我在Python中尝试过这个来查找常见字母(我的网格是12x12):

#!/usr/bin/env python

import re

def printCrossword(c):
for r in range(12):
print ''.join(c[r])

with open('h.txt') as hFile:
hFileData = hFile.readlines()

with open('v.txt') as vFile:
vFileData = vFile.readlines()

hData = [[0 for x in xrange(12)] for x in xrange(12)]
vData = [[0 for x in xrange(12)] for x in xrange(12)]
fData = [[0 for x in xrange(12)] for x in xrange(12)]

for r in range(12):
for c in range(12):
hData[r][c] = hFileData[r][c]
vData[c][r] = vFileData[r][c]


for r in range(12):
for c in range(12):
common = re.sub('[^' + ''.join(hData[r]) + ']', '', ''.join(vData[r]))
if len(common) == 1:
fData[r][c] = common
else:
fData[r][c] = ' '

printCrossword(hData)
print '------------'
printCrossword(vData)
print '------------'
printCrossword(fData)

以下是前 4 个单元的过程的图形表示:

Crosswords

最佳答案

I'm trying to find a char that's both on the row of the horizontal file and on the column of the vertical file.

除了我不会讨论的输入和输出之外,您需要的是每个可能的行/列对中的字符集的简单交集算法。幸运的是Python has sets built in (并且它们通过重载的 & 运算符支持交集):

# just row- and column-wise traversals of the grid
# I believe these correspond exactly to your hData and vData tables
rows = [ "bac", "def", "hig" ]
cols = [ "dag", "hbe", "cfi" ]

res = [ [ set(r) & set(c) for c in cols ] for r in rows ]
print(res)

这将计算可能出现在输出中相应位置的字符集(通常,可能有多个候选字符):

[[set(['a']), set(['b']), set(['c'])], 
[set(['d']), set(['e']), set(['f'])],
[set(['g']), set(['h']), set(['i'])]]

如果您预先知道不存在歧义(例如,如果所有字符都不同)并且网格是可解的,则可以使用 next功能:

res = [ [ next(iter(set(r) & set(c))) for c in cols ] for r in rows ]

输出:

[['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h', 'i']]

关于python - 如何在python中交叉2个二维数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23596269/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com