计算生命路径数的Python程序
给定格式为 YYYYMMDD 的日期字符串,我们的任务是计算生命路径编号。 Life Path Number是将日期字符串的每个元素的单个数字重复相加直到单个数字而获得的数字。用于命理预测。
例子:
Input : test_str = “19970314”
Output : 7
Explanation : 1 + 9 + 9 + 7 = 26 , 2 + 6 = 8 [ year ] ; 0 + 3 = 3 [ month ] ; 1 + 4 = 5 [ day ]. 5 + 3 + 8 = 16 ; 1 + 6 = 7.
Input : test_str = “19970104”
Output : 4
Explanation : 1 + 9 + 9 + 7 = 26 , 2 + 6 = 8 [ year ] ; 0 + 1 = 1 [ month ] ; 0 + 4 = 4 [ day ]. 4 + 1 + 8 = 13 ; 1 + 3 = 4.
方法一:使用循环
计算这背后的逻辑是获取每个数字的总和并在每一步执行 %10。如果它变成两位数,这种方式会导致卷发器变为个位数。
Python3
# Python3 code to demonstrate working of
# Life Path Number
# Using loop
# initializing string
test_str = "19970314"
# printing original string
print("The original string is : " + str(test_str))
res = 0
for num in test_str:
res += int(num)
# modulation in case of 2 digit number
if res > 9:
res = res % 10 + res // 10
# printing result
print("Life Path Number : " + str(res))
Python3
# Python3 code to demonstrate working of
# Life Path Number
# Using recursion
# initializing string
test_str = "19970314"
# printing original string
print("The original string is : " + str(test_str))
# recursion function definition
def lpn(num): return num if num < 10 else lpn(num // 10 + num % 10)
# recursive function initial call
res = lpn(int(test_str))
# printing result
print("Life Path Number : " + str(res))
输出:
The original string is : 19970314
Life Path Number : 7
方法二:使用递归
与上述类似,不同之处在于递归函数用于在位数大于 1 的情况下进行重复调制。
蟒蛇3
# Python3 code to demonstrate working of
# Life Path Number
# Using recursion
# initializing string
test_str = "19970314"
# printing original string
print("The original string is : " + str(test_str))
# recursion function definition
def lpn(num): return num if num < 10 else lpn(num // 10 + num % 10)
# recursive function initial call
res = lpn(int(test_str))
# printing result
print("Life Path Number : " + str(res))
输出:
The original string is : 19970314
Life Path Number : 7