码迷,mamicode.com
首页 > 其他好文 > 详细

Code Signal_练习题_isLucky

时间:2018-07-22 18:47:21      阅读:241      评论:0      收藏:0      [点我收藏+]

标签:git   技术分享   src   分享图片   pre   技术   red   关于   false   

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 be
      isLucky(n) = true;
    • For n = 239017, the output should be
      isLucky(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的
View Code

 

Code Signal_练习题_isLucky

标签:git   技术分享   src   分享图片   pre   技术   red   关于   false   

原文地址:https://www.cnblogs.com/YD2018/p/9350946.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!