Code Signal_练习题_isLucky

本文介绍了一种算法,用于判断一个票号是否为幸运票号。幸运票号是指票号的前半部分数字之和等于后半部分数字之和的票号。通过两个不同的Python函数实现这一逻辑,并对代码进行了简化。

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

 

转载于:https://www.cnblogs.com/BlameKidd/p/9350946.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值