100+Python挑战性编程练习系列 -- day 4
Question 14
写一个程序,接受一个句子,并计算大写字母和小写字母的数量。
假设向程序提供以下输入: Hello world!
然后,输出应为: UPPER CASE 1 LOWER CASE 9
方法1
word = input() upper, lower = 0, 0 for i in word: if 'a' <= i and i <= 'z': lower += 1 if 'A' <= i and i <= 'Z': upper += 1 print("UPPER CASE {0}\nLOWER CASE {1}".format(upper, lower)) 方法2
word = input() upper, lower = 0, 0 for i in word: lower += i.islower() upper += i.isupper() print("UPPER CASE {0}\nLOWER CASE {1}".format(upper, lower)) 方法3
word = input() upper = sum(1 for i in word if i.isupper()) # sum function cumulatively sum up 1's if the condition is True lower = sum(1 for i in word if i.islower()) print("UPPER CASE {0}\nLOWER CASE {1}".format(upper, lower)) Question 15
写一个程序,计算a+aa+aaa+aaaa的值,其中给定一个数字作为a的值。
假设向程序提供以下输入: 9
然后,输出应为: 11106
方法1
a = input() total, tmp = 0, str() # initialing an integer and empty string for i in range(4): tmp += a # concatenating 'a' to 'tmp' total += int(tmp) # converting string type to integer type print(total) 方法2
a = input() total = int(a) + int(2*a) + int(3*a) + int(4*a) # N*a=Na, for example a="23", 2*a="2323",3*a="232323" print(total) 方法3
a = input() print(sum(int(i*a) for i in range(1,5)))