Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.9k views
in Technique[技术] by (71.8m points)

Digit of Life in Python

I'm trying to create a method that will return a digit of life when receiving input of a date of birth in the following format: YYYYMMDD. The requirements are as follows (see image below):

I have tried the following:

def split(word):
    return [char for char in word]

date = input("Enter your date of birth in YYYYMMDD format: > ")
sum_list = []


def digitOfLife(date):
    sum = 0
    if(len(date) > 8):
        print("Input data too long")
        return
    else:
        date_list = []
        for char in date:
            date_list.append(int(char))
            
        while len(date_list) >= 1:
            print(len(date_list))
            for num in date_list:
                if sum > 9:
                    sum = 0
                sum+=num
                date_list.pop()
    return sum
    
print(digitOfLife(date))
    

However, I am not getting the result that is supposed to be produced with this algorithm. I know it has something to do with my logic which adds the digits of the list after it's been popped, but I'm not sure what it is.

Any insight would be greatly appreciated.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

It looks like you would only need to perform modulo 10 on cumulative additions:

def dol(N): return N if N < 10 else dol(N//10+N%10)

date = "19991229"
dol(int(date)) # 6

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...