一、题目
手机的九宫格图案解锁总共能绘出多少种图案?
二、思路:
1、至少经过四个点;不能重复经过同一个点;【对数字进行4个数的全排列】
2、路径上的中间点不能跳过(如从1到3一定会经过2);【设置字典,然后判断这些情况在不在全排列中】
三、代码:
# -*- coding: utf-8 -*- from itertools import chain, permutations impossible = {'13':'2', '46': '5', '79': '8', '17': '4', '28': '5', '39': '6', '19': '5', '37': '5', '31': '2', '64': '5', '97': '8', '71': '4', '82': '5', '93': '6', '91': '5', '73': '5'} def counts(): ###permutations产生全排列,chain是产生迭代器列表 iterlst = chain(*(permutations('123456789', i) for i in range(4, 10))) count = 0 for i in iterlst: stri = ''.join(i) for k, v in impossible.items(): if k in stri and v not in stri[:stri.find(k)]: break #for循环搭配else:当迭代的对象迭代完并为空时,位于else的子句将执行,而如果在for循环中含有break时则直接终止循环,并不会执行else子句。 else: count += 1 return count print(counts())#389112
参考:
https://www.zhihu.com/question/24905007/answer/29414497