Self Describing Numbers自描述数字问题(Python版)

Description:

A number is a self-describing number when (assuming digit positions are labeled 0 to N-1), the digit in each position is equal to the number of times that that digit appears in the number.

Input sample:

The first argument is the pathname to a file which contains test data, one test case per line. Each line contains a positive integer. Each line is in the format: N i.e. a positive integer eg.

2020
22
1210

Output sample:

If the number is a self-describing number, print out a 1. If not, print out a 0 eg.

1
0
1

解释:

自描述数字是指第i位上的数字等于i在整个数字中出现的次数,如2020,第0位上的数字为2,2020中共有2个0;第1位上的数字是0,2020中共有0个1;第2位上的数字是2,2020中共有2个2;第3位上的数字是0,2020中共有0个3;所以2020是自描述数字

求解方案:

import sys

if __name__ == "__main__":
        argv = sys.argv
        inf = open(argv[1],'r')
        while True:
                line = inf.readline()[:-1]
                if len(line) == 0:
                        break
                flag = True
                for i in range(0,len(line)):
                        if int(line[i]) != line.count(str(i)):
                                flag = False
                                break
                if flag:
                        print 1
                else:
                        print 0


你可能感兴趣的:(代码,算法,python,python)