Python打卡Day22
Question 90
Question
Please write a program which count and print the numbers of each character in a string input by console.
Example: If the following string is given as input to the program:
1abcdefgabc
Then, the output of the program should be:
1a,2
2c,2
3b,2
4e,1
5d,1
6g,1
7f,1
Hints
Use dict to store key/value pairs. Use dict.get() method to lookup a key with default value.
Main author's Solution: Python 2
1dic = {}
2s=raw_input()
3for s in s:
4 dic[s] = dic.get(s,0)+1
5print '\n'.join(['%s,%s' % (k, v) for k, v in dic.items()])
My Solution: Python 3
1import string
2
3s = input()
4for letter in string.ascii_lowercase:
5 cnt = s.count(letter)
6 if cnt > 0:
7 print("{},{}".format(letter,cnt))
OR
1s = input()
2for letter in range(ord('a'),ord('z')+1): # ord() gets the ascii value of a char
3 letter = chr(letter) # chr() gets the char of an ascii value
4 cnt = s.count(letter)
5 if cnt > 0:
6 print("{},{}".format(letter,cnt))
Question 91
Question
Please write a program which accepts a string from console and print it in reverse order.
Example: If the following string is given as input to the program:*
1rise to vote sir
Then, the output of the program should be:
1ris etov ot esir
Hints
Use list[::-1] to iterate a list in a reverse order.
Main author's Solution: Python 2
1s=raw_input()
2s = s[::-1]
3print s
My Solution: Python 3
1s = input()
2s = ''.join(reversed(s))
3print(s)
Question 92
Question
Please write a program which accepts a string from console and print the characters that have even indexes.
Example: If the following string is given as input to the program:
1H1e2l3l4o5w6o7r8l9d
Then, the output of the program should be:
1Helloworld
Hints
Use list[::2] to iterate a list by step 2.
Main author's Solution: Python 2
1s=raw_input()
2s = s[::2]
3print s
My Solution: Python 3
1s = "H1e2l3l4o5w6o7r8l9d"
2s = [ s[i] for i in range(len(s)) if i%2 ==0 ]
3print(''.join(s))
OR
1s = "H1e2l3l4o5w6o7r8l9d"
2ns =''
3for i in range(len(s)):
4 if i % 2 == 0:
5 ns+=s[i]
6print(ns)
Question 93
Question
Please write a program which prints all permutations of [1,2,3]
Hints
Use itertools.permutations() to get permutations of list.
Solution:
1
2import itertools
3print list(itertools.permutations([1,2,3]))
Question 94
Question
Write a program to solve a classic ancient Chinese puzzle: We count 35 heads and 94 legs among the chickens and rabbits in a farm. How many rabbits and how many chickens do we have?
Hints
Use for loop to iterate all possible solutions.
Solution:
1def solve(numheads,numlegs):
2 ns='No solutions!'
3 for i in range(numheads+1):
4 j=numheads-i
5 if 2*i+4*j==numlegs:
6 return i,j
7 return ns,ns
8
9numheads=35
10numlegs=94
11solutions=solve(numheads,numlegs)
12print solutions