# 3道经典 Python 题，9 种绝妙解法，你能想出几种？

1.字母转换问题

solve('coDe')=="code"

solve("CODe")=="CODE"

1).屌丝解法：

2).进阶解法

3).高手解法

2.数独问题

board = [

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

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

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

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

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

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

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

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

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

]

1).可以将上边列表看成一个矩阵图形

row_len=[len(set(row)) for row in board]

# 结果为：

[9, 9, 9, 9, 9, 9, 9, 9, 9]

# 说明每一行去重后仍有9个元素，说明没有重复元素

# 最后只需要判断新生成的列表row_len 元素之和是否等于 81，就可以知道每一行是否有重复数字。

2).判断列是否满足条件

board2 = map(list,zip(*board))

# 结果：

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

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

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

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

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

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

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

[6, 7, 1, 9, 4, 3, 8, 2, 3],

[8, 5, 9, 2, 6, 1, 7, 4, 5]]

3).最后判断行和列是否都满足条件

def done_or_not(board):

if sum([len(set(col)) for col in board2]) == 81 and sum([len(set(row)) for row in board]) ==81 :

pass

else:

return 'Try again!'

4).怎么分成9个小块呢

import numpy as np

board_array = np.array(board)

board_array[0:3,0:3] #取第一行到第三行，第1列到第3列的，3x3小区块

#结果：

array([[1, 3, 2],

[4, 9, 8],

[7, 5, 6]])

board_array[0:3,0:3]

board_array[0:3,3:6]

board_array[0:3,6:9]

board_array[3:6,0:3]

board_array[3:6,3:6]

board_array[3:6,6:9]

board_array[6:9,0:3]

board_array[6:9,3:6]

board_array[6:9,6:9]

import numpy as np

def done_or_not(board):

board2 = map(list,zip(*board))

if sum([len(set(row)) for row in board2]) == 81 and sum([len(set(row)) for row in board]) ==81 :

board_array = np.array(board)

x = [0,3,6,9]

for y in range(0,len(x)-1):

for j in range(0,len(x)-1):

z = board_array[x[y]:x[y+1],x[j]:x[j+1]]

if len(set([num for row in z for num in row ])) != 9:

return 'Try again!'

return 'Finished!'

else:

return 'Try again!'

2.看高手的解法

import numpy as np

def done_or_not(aboard): #board[i][j]

board = np.array(aboard)

rows = [board[i,:] for i in range(9)] # 取行

cols = [board[:,j] for j in range(9)] #取列

sqrs = [board[i:i+3,j:j+3].flatten() for i in [0,3,6] for j in [0,3,6]] # 分区

for view in np.vstack((rows,cols,sqrs)):

if len(np.unique(view)) != 9:

return 'Try again!'

return 'Finished!'

3.神一样的解法

3.找出下一个大的数字

1).屌丝解法：

assert next_bigger(50)==-1

assert next_bigger(13)==31

assert next_bigger(217)==271

assert next_bigger(16318)==16381

2).优化算法，进阶解法

3).神一样的解法

• 发表于:
• 原文链接https://kuaibao.qq.com/s/20180905B1VR7W00?refer=cp_1026
• 腾讯「腾讯云开发者社区」是腾讯内容开放平台帐号（企鹅号）传播渠道之一，根据《腾讯内容开放平台服务协议》转载发布内容。
• 如有侵权，请联系 cloudcommunity@tencent.com 删除。

2022-06-30

2022-06-30

2022-06-30

2022-06-30

2022-06-30

2022-06-30

2018-05-07

2022-06-30

2022-06-30

2022-06-30

2022-06-30

2022-06-30