您的位置:首页 > 编程语言 > Python开发

面试宝典_Python.常规算法.0001.在圆圈和框框分别填入1~8数字各一次?

2016-12-24 14:15 651 查看
面试题目:




解题思路:
1. 总共8个位置,只要2个圈圈之差等于框框即可,注意倒数第3个数还要和第1个数字运算才算结束,所以可以先生成排列组合然后再通过分片偏移来获取符合条件的结果.

具体实现:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date    : 2016-12-24 12:19:01
# @Author  : 李满满 (xmdevops@vip.qq.com)
# @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)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Python 面试宝典
相关文章推荐