天天看點

Self Describing Numbers自描述數字問題(Python版)Description:Input sample:Output sample:解釋:求解方案:

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