Floor division: // ( 2345//10 = 234//10 = 23//10 = 2)数字分拆运算 1//10 = 0
Module (remainder): % (123%10 = 3; 12%10 = 2) 取末位数 1%10 = 1
Q4: Sum Digits:
""" sum all the digits of n. >>> sum_digits(123) # 1+2+3 = 6
1. recursion:
def sum_digits(n):
if n<10:
return n
else:
other, last = n//10, n%10
return sum_digits(other) + last
2. iteration
def sum_digits(n):
sum=0
while n>0:
n, last = n//10, n%10
sum += last
return sum
Q6 Falling Factorial
""" falling(6,3) # 6*5*4 =120; falling(4,0) = 1, falling(4, 3)= 4*3*2=24"""
def falling(n,k)
fac=1
while k>0:
fac, k = n*fac, k-1
n -= 1
retrun fac
Q7 Double Eights
"" return true if n has two eights in a row. double_eights(88) = True, double_eights(123)=False"""
def double_eights(n):
flag=0
while n>0:
n, last = n//10, n%10
if last ==8 and flag == 1:
return True
elif last == 8:
flag = 1
else:
flag = 0
return False
n | 123 |
other | 12 |
last | 3 |
RV | RV + last 3 |
n | 12 |
other | 1 |
last | 2 |
RV | RV+ last 1+2=3 |
n | 1 |
RV | 1 |