Ticket numbers usually consist of an even number of digits. A ticket number is considered lucky if the sum of the first half of the digits is equal to the sum of the second half.
Given a ticket number n
, determine if it‘s lucky or not.
Example
- For
n = 1230
, the output should beisLucky(n) = true
; - For
n = 239017
, the output should beisLucky(n) = false
.
我的解答:
1 def isLucky(n): 2 n = str(n) 3 li = [] 4 for i in n: 5 li.append(i) 6 f = int(len(li)/2) 7 sum_l = 0 8 sum_r = 0 9 for x in li[:f]: 10 sum_l += int(x) 11 for y in li[f:]: 12 sum_r += int(y) 13 print(sum_l,sum_r) 14 return sum_l == sum_r 15 16 最后一句本来想这样写的: 17 if sum_l == sum_r: 18 return True 19 else: 20 return False 21 做了几道题发现其他人都一句话完事,于是也学到了...
膜拜大佬:
def isLucky(n): s = str(n) pivot = len(s)//2 left, right = s[:pivot], s[pivot:] return sum(map(int, left)) == sum(map(int, right)) 刚学了map,也知道怎么回事,就是想不起来用..还是得多练练关于map的
原文地址:https://www.cnblogs.com/YD2018/p/9350946.html
时间: 2024-10-13 19:23:00