Python打卡Day24
Question 100
Question
You are given words. Some words may repeat. For each word, output its number of occurrences. The output order should correspond with the input order of appearance of the word. See the sample input/output for clarification.
If the following string is given as input to the program:
14 2bcdef 3abcdefg 4bcde 5bcdefThen, the output of the program should be:
13 22 1 1
Hints
Make a list to get the input order and a dictionary to count the word frequency
My Solution: Python 3
1n = int(input())
2
3word_list = []
4word_dict = {}
5
6for i in range(n):
7 word = input()
8 if word not in word_dict:
9 word_list.append(word)
10 word_dict[word] = word_dict.get(word, 0) + 1
11
12print(len(word_list))
13for word in word_list:
14 print(word_dict[word], end=' ')
Question 101
Question
You are given a string.Your task is to count the frequency of letters of the string and print the letters in descending order of frequency.
If the following string is given as input to the program:
1aabbbccdeThen, the output of the program should be:
1b 3 2a 2 3c 2 4d 1 5e 1
Hints
Count frequency with dictionary and sort by Value from dictionary Items
My Solution: Python 3
1word = input()
2dct = {}
3for i in word:
4 dct[i] = dct.get(i,0) + 1
5
6dct = sorted(dct.items(),key=lambda x: (-x[1],x[0]))
7for i in dct:
8 print(i[0],i[1])
1'''Solution by: yuan1z'''
2
3X = input()
4my_set = set(X)
5arr = []
6for item in my_set:
7 arr.append([item,X.count(item)])
8tmp = sorted(arr,key = lambda x: (-x[1],x[0]))
9
10for i in tmp:
11 print(i[0]+' '+str(i[1]))
1'''Solution by: StartZer0'''
2
3s = list(input())
4
5dict_count_ = {k:s.count(k) for k in s}
6list_of_tuples = [(k,v) for k,v in dict_count_.items()]
7list_of_tuples.sort(key = lambda x: x[1], reverse = True)
8
9for item in list_of_tuples:
10 print(item[0], item[1])
Question 102
Question
Write a Python program that accepts a string and calculate the number of digits and letters.
Input
1Hello321Bye360
Output
1Digit - 6 2Letter - 8
Hints
Use isdigit() and isalpha() function
Solution:
1word = input()
2digit,letter = 0,0
3for char in word:
4 digit+=char.isdigit()
5 letter+=char.isalpha()
6
7print('Digit -',digit)
8print('Letter -',letter)
Question 103
Question
Given a number N.Find Sum of 1 to N Using Recursion
Input
15
Output
115
Hints
Make a recursive function to get the sum
Solution:
1def rec(n):
2 if n == 0:
3 return n
4 return rec(n-1) + n
5
6
7n = int(input())
8sum = rec(n)
9print(sum)