内容🔗:
Lab 1 Solutions | CS 61A Summer 2023
一.print and None
1.string literal string value:
2.
- Careful python rule:
- print() returns None (the value of print expression)
🌰 >>>print(None, None) >>> None None :因为print功能就是会打印形参绑定的value -> 绑定了N one,None,所以会display, 但它的返回值是None(即Print表达式的值)所以不打印。
二.Ture and False![](https://i-blog.csdnimg.cn/blog_migrate/106d3f7d116112c15f7c204a8a2f030f.png)
the empty string
>>> True and 13 >>> 13:
在Python中,and
是一个逻辑运算符,用于将两个表达式连接起来,并在两个表达式都为真(True)时返回真,否则返回假(False)。
当你在Python中键入 True and 13
,Python会首先评估第一个表达式 True
,由于它是真值,所以继续评估第二个表达式 13
。在Python中,非零的整数被视为真值,因此 13
也是真值。
由于两个表达式都为真值,所以整个 and
表达式返回最后一个被评估的值,即 13
。这就是为什么 True and 13
会显示 13
的原因。
or从左往右找到了一个真值就返回它,不会继续往右计算了 ,and同理(找到一个假值)
三.coding
Q4: Falling Factorial(阶乘
逆向思维
Let's write a function falling
, which is a "falling" factorial that takes two arguments, n
and k
, and returns the product of k
consecutive numbers, starting from n
and working downwards. When k
is 0, the function should return 1.
Q4: Falling Factorial
Let's write a function falling, which is a "falling" factorial that takes two arguments, n and k, and returns the product of k consecutive numbers, starting from n and working downwards. When k is 0, the function should return 1.
def falling(n, k):
"""Compute the falling factorial of n to depth k.
>>> falling(6, 3) # 6 * 5 * 4
120
>>> falling(4, 3) # 4 * 3 * 2
24
>>> falling(4, 1) # 4
4
>>> falling(4, 0)
1
"""
total, stop = 1, n-k
while n > stop:
total, n = total*n, n-1
return total
Q5: Sum Digits
Write a function that takes in a nonnegative integer and sums its digits. (Using floor division and modulo might be helpful here!)
3//10 = 0, 5//10 = 0, 3%10 = 3,%10是最后一个数字 -> 2345%10=5
def sum_digits(y):
"""Sum all the digits of y.
>>> sum_digits(10) # 1 + 0 = 1
1
>>> sum_digits(4224) # 4 + 2 + 2 + 4 = 12
12
>>> sum_digits(1234567890)
45
>>> a = sum_digits(123) # make sure that you are using return rather than print
>>> a
6
"""
total = 0
while y > 0:
total, y = total + y % 10, y // 10
return total
Q8: Double Eights
Write a function that takes in a number and determines if the digits contain two adjacent 8s.
def double_eights(n):
"""Return true if n has two eights in a row.
>>> double_eights(8)
False
>>> double_eights(88)
True
>>> double_eights(2882)
True
>>> double_eights(880088)
True
>>> double_eights(12345)
False
>>> double_eights(80808080)
False
"""
prev_eight = False
while n > 0:
last_digit = n % 10
if last_digit == 8 and prev_eight:
return True
elif last_digit == 8:
prev_eight = True
else:
prev_eight = False
n = n // 10
return False
自己的:
while n >= 10:
right = n % 10
n //= 10
if right == 8:
left = n % 10
if left == 8:
return True
return False