前段时间刷着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。
大致的思路:
- 倒序取数,循环比较最后一位和往前数字的大小,
- 往前数字大于最后一位时:停止,return 循环的次数
- 所有数字循环完成,未找到更大数字: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
第二版其实和标答已经非常相似了,但也还是有值得优化的:
- 前一位数可以直接用 num %10 (除10、取余数)表示
- 当 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中,解决了也是很爽~