Think before you speak, read before you think.

找出特殊的九位数-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()

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *