CS61A lab1

本文介绍了Python中的一些数学运算,如地板除、模运算,以及如何使用递归和迭代方式计算数字的各位之和。此外,还展示了落射阶乘的计算方法,并提供了一个检查连续数字8的函数。这些概念在编程中经常被用到,对于理解基本的算法和数据处理至关重要。
摘要由CSDN通过智能技术生成

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

P-G frame(recursion)
n123
other12
last3
RV

RV + last

n12
other1
last2
RVRV+ last 1+2=3

1

RV1
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值