Problem 3: Number of k (100pts)
Problem
Write a function that takes two non-negative integers,
nandk, and returns the number of occurrences ofkinn.For example,
number_of_k(1234321, 2)returns2, since1234321consists of1, 2, 3, 4, 3, 2, 1, and there are two2's in it.
编写一个函数,接受两个非负整数 n 和 k,并返回 k 在 n 中出现的次数。
例如,number_of_k(1234321, 2) 返回 2,因为 1234321 由 1, 2, 3, 4, 3, 2, 1 组成,其中有两个 2。
def number_of_k(n, k):
"""Return the number of occurrences of k in each digit of a non-negative
integer n.
>>> number_of_k(999, 9)
3
>>> number_of_k(1234321, 2)
2
"""
"*** YOUR CODE HERE ***"
Hints
Hint1: You may want to use a
whileloop to solve this problem. Be careful when to stop!Hint2: For a positive integer
n(e.g.,123),n % 10gives you the last digit ofn(123 % 10gets3), whereasn // 10gives you all except the last digits ofn(123 // 10gets12).Hint3: It is guaranteed that
0 <= k <= 9.
-
您可能需要使用一个
while循环来解决此问题。请注意何时停止! -
对于一个非负整数
n(例如123),n % 10得到n的个位数字(123 % 10得到3),而n // 10得到n除个位数字以外的所有数字(123 // 10得到12)。 -
k的输入总满足0 <= k <= 9。 -
此题可用
str偷鸡 (但好像被制裁了) -
注意
n和k均为0时输出为1
Solutions
使用 while 循环。每次只判断个位数是否与 k 相同,当判断后 n 只剩一位时,所有数位都已经计数,退出循环。
def number_of_k(n, k):
count = 0
# Infinite loop until break
while(True):
# Get the last digit of n using %
last_digit = n % 10
# Check if the last digit is equal to k
if last_digit == k:
count += 1
# Exit the loop when only one digit remains
if(n < 10):
break
# Remove the last digit from n using //
n = n // 10
return count
使用 while 循环,但不使用 break 。需要单独判断最后一位。
def number_of_k(n, k):
count = 0
# When n has more than one digits
while n >= 10:
last_digit = n % 10
# We first check the last digit of n
if last_digit == k:
count += 1
# And then drop the last digit of n
n = n // 10
# When n has only one digit left
if n == k:
count += 1
return count
直接特判 n == 0 and k == 0 时的情况
def number_of_k(n, k):
if (n == 0 and k == 0):
return 1
count = 0
# The loop continues as long as there are digits left in n
while n > 0:
# Get the last digit of n using %
last_digit = n % 10
# Check if the last digit is equal to k
if last_digit == k:
count += 1
# Remove the last digit from n using //
n = n // 10
return count
str 偷鸡(使用 count 函数)
def number_of_k(n, k):
return str(n).count(str(k))