课后习题案例
1.编写函数,接收字符串参数,返回一个元组,其中第一个元素为大写字母个数,第二个元素为小写字母个数。
def demo(s):
result=[0,0]
for ch in s:
if 'a'<=ch<='z':
result[1]+=1
elif 'A'<=ch<='Z':
result[0]+=1
return tuple(result)
print(demo('aaaabbbbc'))
(1,8)
2.编写函数,接收一个整数t为参数,打印杨辉三角前t行。
def demo(t):
print([1])
print([1,1])
line = [1,1]
for i in range(2,t):
r = []
for j in range(0,len(line)-1):
r.append(line[j]+line[j+1])
line = [1]+r+[1]
print(line)
demo(10)
[1]
[1, 1]
[1, 2, 1]
[1, 3, 3, 1]
[1, 4, 6, 4, 1]
[1, 5, 10, 10, 5, 1]
[1, 6, 15, 20, 15, 6, 1]
[1, 7, 21, 35, 35, 21, 7, 1]
[1, 8, 28, 56, 70, 56, 28, 8, 1]
[1, 9, 36, 84, 126, 126, 84, 36, 9, 1]
- 编写函数,计算形式如a + aa + aaa + aaaa + … + aaa…aaa的表达式的值,其中a为小于10的自然数。
def demo(v, n):
assert type(n)==int and 0<v<10, 'v must be integer between 1 and 9'
result, t = 0, 0
for i in range(n):
t = t*10 + v
result += t
return result
print(demo(3, 4))
3072