python - 用于数独解题器的从水平行列表中获取部分的一种简短(呃)方法

标签 python iteration sudoku

我目前有代码:

# gets all the horizontal rows from file
rows = [line.strip('\n') for line in open("F:/sudoku practice.txt",'r')]
# gets all the vertical columns from horizontal rows
columns = [(''.join(list(line[i]for line in rows)))for i in range(8)]
import itertools
sections = [[],[],[],[],[],[],[],[],[]]
for line in rows[:3]:
    sections[0].append([(''.join(line[:3]))])
    sections[1].append([(''.join(line[3:6]))])
    sections[2].append([(''.join(line[6:9]))])
for line in rows[3:6]:
    sections[3].append([(''.join(line[:3]))])
    sections[4].append([(''.join(line[3:6]))])
    sections[5].append([(''.join(line[6:9]))])
for line in rows[6:9]:
    sections[6].append([(''.join(line[:3]))])
    sections[7].append([(''.join(line[3:6]))])
    sections[8].append([(''.join(line[6:9]))])
# flattening the list of lists of lists into a list
for i in range(9):
    sections[i] = ''.join(list(itertools.chain.from_iterable(sections[i])))

print(sections)

返回:

[' 2 457689', '456 8 237', '789236 4 ', '  5274396', '362 9 574', '9746538  ', ' 4 761938', '618 4 725', '397528 6 ']

列表中的每个项目代表数独谜题的一部分,这正是我想要的,但我希望有一种更短的方式来获取所有部分,我有一个用于获取行和列的单行如果可能的话想要类似的东西

最佳答案

由于在数独中,您需要大量访问子数组和对角线等,Numpy将为您节省很多精力:

import numpy as np

a = np.random.randint(1, 9, (9,9))

print a

[[2 6 3 2 3 4 2 6 5]
 [5 3 7 4 5 2 3 4 7]
 [4 3 1 8 2 7 4 4 2]
 [4 6 5 5 3 6 2 6 8]
 [3 8 3 5 5 4 5 7 3]
 [4 6 2 3 1 6 1 4 2]
 [7 2 6 7 8 3 6 6 3]
 [8 1 7 7 5 7 5 2 1]
 [7 5 3 3 6 1 3 4 2]]

# middle section
print a[3:6,3:6]

[[5 3 6]
 [5 5 4]
 [3 1 6]]

# lower middle diagonals
print a[6:, 3:6].diagonal()

[7 5 1]

# lower middle upward diagonals
print a[6:, 3:6][::-1].diagonal()

[3 5 3] 

关于python - 用于数独解题器的从水平行列表中获取部分的一种简短(呃)方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31076174/

相关文章:

python - Pandas 的 CSV 加载错误

python - 在 Python 中按照给定的 UID 执行 shell 命令

Javascript:查找相邻数组元素的乘积并返回最大的乘积

javascript - 我的 javascript 暴力递归数独解算器是否内存不足?

java - 数独需要帮助构建可见矩阵

python - Django 测试错误 : relation does not exist

python - 二进制列的 Pandas 值列表

php - 遍历对象数组

arrays - 遍历数组,将字符串转换为数组,推送到 Ruby 中的新数组

C++ - 解决数独游戏