伯克利CS61A错题笔记1.0

前段时间刷着berkeley的CS61A,在第二次作业中遇到一个题,魔怔了好久,解出来才发现根本不难,笔记纪念一下。

倒序比数,数大即停

原题 —— Count Until Larger

Implement the function count_until_larger. count_until_larger takes in a positive integer num. count_until_larger counts the distance between the rightmost digit of num and the nearest greater digit; to do so, the function counts digits from right to left. Once it encounters a digit larger than the rightmost digit, it returns that count. If no such digit exists, then the function returns -1.

For example, 8117 has a rightmost digit of 7 and returns a count of 3.
9118117 also returns a count of 3: for both, the count stops at 8.
0 should be treated as having no digits and returns a count of -1.

def count_until_larger(num):
    """
    Complete the function count_until_larger that takes in a positive integer num.
    count_until_larger examines the rightmost digit and counts digits from right to
    left until it encounters a digit larger than the rightmost digit, then returns that count.

    >>> count_until_larger(117) # .Case 1
    -1
    >>> count_until_larger(8117) # .Case 2
    3
    >>> count_until_larger(9118117) # .Case 3
    3
    >>> count_until_larger(8777)  # .Case 4
    3
    >>> count_until_larger(22) # .Case 5
    -1
    >>> count_until_larger(0) # .Case 6
    -1
    """
    "*** YOUR CODE HERE ***"

题目大意就是设计一个函数 count_until_larger:输入任意自然数,找到【比最后一位数大、且与最后一位距离最近的】数,返回它与最后一位数的距离。如果输入是0或者找不到此数,则返回-1。

大致的思路:

  1. 倒序取数,循环比较最后一位和往前数字的大小,
  2. 往前数字大于最后一位时:停止,return 循环的次数
  3. 所有数字循环完成,未找到更大数字:return -1

第一版答案,用string非常暴力拆解了数字:

def count_until_larger(num):
    rightmost,listn,count = num%10,[],0
    listn.extend(i for i in str(num//10))
    listn.reverse()
    for number,i in enumerate(listn):
        if int(i)> rightmost:
            return number+1
        else:
            count += 1
    if count != 0:
        return -1
    else:
        return count

第二版优化后的答案,用取余数的方法一步步拆解数字:

def count_until_larger(num):
    rightmost, aheadnum, count = num%10,((num - num%10)%10), 0
    while num > 1:
        if aheadnum > rightmost:
            return count
        else:
            count += 1
            num = num // 10
            aheadnum = num %10
    return -1

第二版其实和标答已经非常相似了,但也还是有值得优化的:

  1. 前一位数可以直接用 num %10 (除10、取余数)表示
  2. 当 num 为个位数时,num //10 = 0 (取整除结果),所以不需要 num > 1

附上标答:

def count_until_larger(num):
    rightmost = num % 10
    count = 0
    while num:
        if num % 10 > rightmost:
            return count
        num = num // 10
        count = count + 1
    return -1

折腾了一中午,鬼知道一开始看这题的时候陷入了什么bug中,解决了也是很爽~

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值