Problem 7: Double Ones (100pts)
Problem
Write a function that takes in a number and determines if the digits contain two adjacent 1s. (Reviewing this problem in Lab 01 might be helpful here!)
编写一个函数,接受一个数字作为参数,并判断其数字中是否包含两个相邻的 1。(回顾 Lab 01 中的 这个问题 可能会有所帮助!)
def double_ones(n):
"""Return true if n has two ones in a row.
>>> double_ones(1)
False
>>> double_ones(11)
True
>>> double_ones(2112)
True
>>> double_ones(110011)
True
>>> double_ones(12345)
False
>>> double_ones(10101010)
False
"""
"*** YOUR CODE HERE ***"
Hints
-
可以使用
str逃课() -
大致思路:取最后两位看看是不是11,如果不是,去掉最后一位再判断
-
while循环和递推都很好写
Solutions
使用 while 循环。当 n 只剩一位时退出循环。
def double_ones(n):
# Loop while the number n still has at least two digits remaining (n >= 10).
while n >= 10:
# Check the last two digits: n % 100 will give the last two digits.
# If the last two digits are 11, we've found our pattern.
if n % 100 == 11:
return True
# Remove the last digit by performing integer division by 10.
n = n // 10
# A single-digit number can never have "11".
return False
递归:
def double_ones(n):
# If the number is less than 10 (single digit), it cannot have '11'.
if n < 10:
return False
# If the last two digits (n % 100) are 11, the condition is met.
if n % 100 == 11:
return True
# Remove the last digit (n // 10) and recursively call the function.
return double_ones(n // 10)
str 逃课:
def double_ones(n):
return '11' in str(n)