找出特殊的九位数-python

1~9的9个数字, 每个数字只能出现一次, 要求这样的9位数:其第一位能被1整除, 前两位能被2整除, 前三位能被3整除…依次类推,前9位能被9整除。所有的9位数中,只有一个数字满足这些条件,请你输出这个9位数。

思路:
根据描述写出函数,判断重复,缩小范围

#!/usr/bin/env python
#-*- coding:utf-8 -*-


def no_repeat(my_num):
    uniq_str=''.join(set(str(my_num)))
    if len(str(my_num)) == len(uniq_str):
        return True

def possible(prefix):
    possible_list = []
    number_len = len(str(prefix)) + 1
    for i in range(10*prefix + 1, 10*(prefix+1)):
        if (i % number_len == 0) and no_repeat(i) and (number_len<9):
            possible(i)
        elif (i % number_len == 0) and no_repeat(i) and number_len == 9:
            print i

def main():
    for i in range(1,10):
        possible(i)

if __name__ == "__main__":
    main()

python list 去重

比较容易记忆的是用内置的set

l1 = ['b','c','d','b','c','a','a']
l2 = list(set(l1))
print l2

还有一种据说速度更快的,没测试过两者的速度差别

l1 = ['b','c','d','b','c','a','a']
l2 = {}.fromkeys(l1).keys()
print l2

这两种都有个缺点,祛除重复元素后排序变了:

['a', 'c', 'b', 'd']

如果想要保持他们原来的排序:

用list类的sort方法

l1 = ['b','c','d','b','c','a','a']
l2 = list(set(l1))
l2.sort(key=l1.index)
print l2

也可以这样写

l1 = ['b','c','d','b','c','a','a']
l2 = sorted(set(l1),key=l1.index)
print l2

也可以用遍历

l1 = ['b','c','d','b','c','a','a']
l2 = []
for i in l1:
    if not i in l2:
        l2.append(i)
print l2
上面的代码也可以这样写
l1 = ['b','c','d','b','c','a','a']
l2 = []
[l2.append(i) for i in l1 if not i in l2]
print l2

这样就可以保证排序不变了:

['b', 'c', 'd', 'a']

参考:

http://blog.csdn.net/zhengnz/article/details/6265282