iT邦幫忙

2022 iThome 鐵人賽

DAY 21
0
自我挑戰組

Udemy課程上完你也可以開始Codewars 30天系列 第 21

[Day21] Codewars >>> Luck check (Python)

  • 分享至 

  • xImage
  •  

題目(5kyu):

In some countries of former Soviet Union there was a belief about lucky tickets. A >transport ticket of any sort was believed to posess luck if sum of digits on the left >half of its number was equal to the sum of digits on the right half. Here are examples >of such numbers:

003111 # 3 = 1 + 1 + 1
813372 # 8 + 1 + 3 = 3 + 7 + 2
17935 # 1 + 7 = 3 + 5 // if the length is odd, you should ignore the >middle number when adding the halves.
56328116 # 5 + 6 + 3 + 2 = 8 + 1 + 1 + 6
Such tickets were either eaten after being used or collected for bragging rights.

Your task is to write a funtion luck_check(str), which returns true/True if argument is >string decimal representation of a lucky ticket number, or false/False for all other >numbers. It should throw errors for empty strings or strings which don't represent a >decimal number.

解題思路

題目理解:設計一函式代入一皆為數字的字串string,若該字串左右半邊數字和相等則返還True,不等則返還False。其中若字串長度為奇數,則正中間的該數字皆不計入左右半邊和內。

def luck_check(string):
    """判斷字串左右半邊數字和是否相等"""
    #將string以個別數字形式轉換成list
    num_string = [int(i) for i in string]
    #使用int()會自動無條件捨去
    middle_index = int(len(string)/2)
    #若字串個數為奇數,則不計中間數
    if len(string)%2 == 1:
        #對前半段與後半段數字的總和做比較,留意後半段索引+1以此來不計入中間數字
        if sum(num_string[:middle_index]) == sum(num_string[middle_index+1:]):
            return True
    else:
        #若為偶數則無中間數字問題可直接使用middle_index做區隔
        if sum(num_string[:middle_index]) == sum(num_string[middle_index:]):
            return True
    return False           

上一篇
[Day20] Codewars >>> Integers: Recreation One (Python)
下一篇
[Day22] Codewars >>> Rot13 (Python)
系列文
Udemy課程上完你也可以開始Codewars 30天30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言