iT邦幫忙

第 11 屆 iThome 鐵人賽

DAY 6
0
自我挑戰組

Daily Coding!一日一刷題系列 第 6

Day05|Codewars 刷題日 (4)

咪那桑晚安R
有鑒於今天出門衝台北放閃
時間上有點來不及寫六級的
就先拿一些七級去做代替吧 qwq

7kyu. Growth of a Population

hmm..這次的有點長,
就麻煩大家自行前往觀看了~

總言之就是不停更新 p0 的數值,
與 p 去做比較,
若更新一次就計數一次,
最後回傳總共調整幾次的結果~

def nb_year(p0, percent, aug, p):
    count = 0
    while p0 < p:
        p0 = p0 + p0 * (percent/100) + aug
        count += 1
    return count

7kyu. Printer Errors

此題也是請大家自行前往觀看
感恩qq

簡單講就是找出 n to z 總共有幾個,
最後回傳 數量 以及 全長度~

def printer_error(s):
    err = 0
    for i in s:
        if i in "nopqrstuvwxyz":
            err += 1
    return str(err) + '/' + str(len(s))

7kyu. Ones and Zeros

Given an array of ones and zeroes, convert the equivalent binary value to an integer.

Eg: [0, 0, 0, 1] is treated as 0001 which is the binary representation of 1.

Examples:

Testing: [0, 0, 0, 1] ==> 1
Testing: [0, 0, 1, 0] ==> 2
Testing: [0, 1, 0, 1] ==> 5
Testing: [1, 0, 0, 1] ==> 9
Testing: [0, 0, 1, 0] ==> 2
Testing: [0, 1, 1, 0] ==> 6
Testing: [1, 1, 1, 1] ==> 15
Testing: [1, 0, 1, 1] ==> 11

However, the arrays can have varying lengths, not just limited to 4.

我的想法是:
先將 list 裡面的東西變成字串並清除前方多餘的 0,
並在前方加上 0b 之後丟入 int(str, 2) 直接轉回十進制~

def binary_array_to_number(arr):
    return int(('0b' + (''.join('%s' %i for i in arr).lstrip('0'))),2)

剛剛又忘記 join 這個方法只能在 串列 裡面只存在字串的情況下使用,
如果要在整數串列使用的話,
需要將他用 for 迴圈將每個元素跑到並轉成字串,
這樣即可正常使用囉~

OK 今天就先這樣
昨天運動完果然今天現世報就來了qwq
我連上下樓走樓梯都會痛不欲生qq
希望能快點好RRRR


上一篇
Day04|Codewars 刷題日 (3)
下一篇
Day06|Codewars 刷題日 (5)
系列文
Daily Coding!一日一刷題7
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言