ITS·黑客

Python小实验——数独游戏

2017-04-17  本文已影响0人  木凛

1)简化迭代模型-->填充数字

引入itertools.product()函数能够把之前需要两层以上迭代才能完成的工作用一层迭代就完成

>>> print list(product([1,2,3],[3,4]))

[(1, 3), (1, 4), (2, 3), (2, 4), (3, 3), (3, 4)]

>>>

>>> print list(product([1,2,3],repeat = 2))

[(1, 1), (1, 2), (1, 3), (2, 1), (2, 2), (2, 3), (3, 1), (3, 2), (3, 3)]

2)拷贝,copy函数-->打印数独列表

在介绍我们的打印函数之前,先介绍一下我们即将要完成的函数中要用到的 copy.deepcopy() 函数。

>>> a = list(range(5))

>>> print a

[0, 1, 2, 3, 4]

>>> b = a

>>> a[3] = 7

>>>

>>> print b

[0, 1, 2, 7, 4]

Python 中的对象之间赋值时是按引用传递的,如果需要拷贝对象,需要使用标准库中的copy模块。

>>> a = list(range(5))

>>> print a

[0, 1, 2, 3, 4]

>>> import copy

>>> b = copy.deepcopy(a)

>>> a[3] = 7

>>> print b

[0, 1, 2, 3, 4]

这次的赋值不再单单传递了一个 变量a 的引用,而是实实在在的为 变量b 分配了内存空间。

3)方便单位调用-->打印数独列表

这里用到了print.format()函数,举例说明:

>>> print '{} and {}'.format('spam', 'eggs')

spam and eggs

但是在代码中我们运用了更加高级的技巧

print("||  {}  |  {}  |  {}  ||  {}  |  {}  |  {}  ||  {}  |  {}  |  {}  ||"

.format(*(cell or ' ' for cell in line)))

每一个 "{}" 都对应了一个 cell 变量。而format()函数中的 * 号,则是将所有的 cell 的不同值放入一个元组 tuple 之中,方便format函数调用。

上一篇 下一篇

猜你喜欢

热点阅读