面試寶典_Python.常規算法.0001.在圓圈和框框分別填入1~8數字各一次?

面試題目:

wKioL1heDiqAAWRIAAC6xlnKOHo915.jpg

解題思路:

1. 總共8個位置,只要2個圈圈之差等於框框即可,注意倒數第3個數還要和第1個數字運算纔算結束,所以可以先生成排列組合然後再通過分片偏移來獲取符合條件的結果.


具體實現:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date    : 2016-12-24 12:19:01
# @Author  : 李滿滿 ([email protected])
# @Link    : http://xmdevops.blog.51cto.com/
# @Version : $Id$

from __future__ import absolute_import
# 說明: 導入公共模塊
import pprint
import itertools
# 說明: 導入其它模塊


def calculation(max_num):
    result = []
    combinations = itertools.permutations(
        xrange(1, max_num + 1),
        max_num
    )
    for item in combinations:
        flag = True
        for index in range(0, max_num, 2):
            x = item[index]
            y = item[index + 1]
            z = item[0] if index == max_num - 2 else item[index + 2]
            if abs(z - x) != y:
                flag = False
                break
        if flag:
            result.append(item)

    return result


if __name__ == '__main__':
    result = calculation(8)
    pprint.pprint(result)


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章