题目九十
请编写一个程序,在控制台输入的字符串中计数和打印每个字符的数字。
示例:如果给出以下字符串作为程序的输入:
abcdefgabc
输出为:
a,2
c,2
b,2
e,1
d,1
g,1
f,1
提示:
使用Dict存储键/值对。使用auto.get()方法查找具有默认值的键。
代码实现
方法一:
使用字典键值对
s = input("请输入字符:")
dic1 = {}
for i in s:
num = s.count(i)
dic1[i] = num
for i in dic1:
print("{},{}".format(i,dic1[i]))
方法二:
import string
s = input("请输入字符:")
for letter in string.ascii_lowercase:
cnt = s.count(letter)
if cnt > 0:
print("{},{}".format(letter, cnt))
运行结果
请输入字符:abcdefgabc
a,2
b,2
c,2
d,1
e,1
f,1
g,1
题目九十一
请编写一个从控制台接收字符串的程序,并按相反顺序打印。
示例:如果给出以下字符串作为程序的输入:
rise to vote sir
输出为:
ris etov ot esir
提示:
使用List[::-1]以相反的顺序迭代列表。
代码实现
方法一:
使用列表切片输出
lst = input("请输入字符:")
print(lst[:: -1])
方法二:
s = input("请输入字符:")
s = "".join(reversed(s))
print(s)
运行结果
请输入字符:rise to vote sir
ris etov ot esir
题目九十二
请编写一个从控制台接收字符串的程序,并打印具有均匀索引的字符。
示例:如果给出以下字符串作为程序的输入:
H1e2l3l4o5w6o7r8l9d
输出为:
Helloworld
提示:
使用list[::2]按步骤2迭代列表。
代码实现
方法一:
slst1 = "H1e2l3l4o5w6o7r8l9d"
s =[slst1[i] for i in range(len(slst1)) if i % 2 ==0]
print("".join(s))
方法二:
slst1 = "H1e2l3l4o5w6o7r8l9d"
lst = list(slst1)
print("".join(lst[0:len(lst):2]))
运行结果
Helloworld
题目九十三
请编写一个程序,打印[1,2,3]的所有排列。
提示:
使用itertools.permutations()获取列表的排列。
代码实现
方法一:
import itertools
print(list(itertools.permutations([1, 2, 3])))
运行结果
[(1, 2, 3), (1, 3, 2), (2, 1, 3), (2, 3, 1), (3, 1, 2), (3, 2, 1)]
题目九十四
写一个程序解决一个古老的中国经典谜题:
我们数35个头和94条腿鸡和兔子在一个农场。我们有多少只兔子和多少只鸡?
提示:
使用循环
代码实现
def solution(num_heads, num_legs):
ns = '无解'
for r_heads in range(num_heads+1):
c_heads = num_heads - r_heads
if r_heads*4 + c_heads*2 ==num_legs:
return r_heads,c_heads
return ns,ns
num_heads = 35
num_legs = 94
solve = solution(num_heads, num_legs)
print("兔子的数量:",solve[0],"鸡的数量:",solve[1])
运行结果
兔子的数量: 12 鸡的数量: 23