Homework--A few simple Python questions

Keywords: Python ascii

1. Write a program to generate 10240 random integers between [0,512], and count the number of occurrences of each element.

2. Write programs that require users to input a list and two integers as subscripts. The program can use slices to obtain and output a sublist of elements between two subscripts in the list. For example, when the user inputs [4, 8, 5, 3, 9] and 1, 2, the program outputs [8].

3. Writing a program requires designing a dictionary, such as {Name': 12,'age': 20,'sex':'boy'}, when the user enters the content as a "key" (for example, input Name), and then outputs the corresponding "value" (output 12) of the dictionary "key". If the "key" entered by the user is not in the dictionary (for example, input ID), the output "the key you entered does not exist" and exit the program.

4. Write a program, requiring that the contents of the two lists be converted into dictionaries, and that the elements in one list be keys and the elements in the other list be values.

 

(The following codes are all Python 2 codes, I used Python 3, because for some reasons, I was stunned to change Python 3 to Python 2)

 

First question

 1 #!/usr/bin/python 
 2 # -*- coding: utf-8 -*-
 3 
 4 import random
 5 import sys
 6 import os
 7 
 8 version_error_info = 'Please use Python2'.decode('utf-8').encode('gbk')
 9 if sys.version_info >= (3, 0):
10    raise RuntimeError(version_error_info)
11 
12 n = 10240
13 max_int = 511
14 list = []   # Save the generated integer
15 dic = dict.fromkeys(range(max_int+1),0)   # key As element,value For the number of occurrences
16 
17 def build():
18     for i in range(n):
19         key = random.randint(0,max_int)
20         list.append(key)
21         dic[key] = dic[key]+1
22 
23 def show():
24     # for i in list:
25     #     print(list[i])
26     for key in dic:
27         print key,':',dic[key]
28 
29 def main():
30     build()
31     show()
32     os.system('pause')
33 
34 if __name__ == '__main__':
35     main()

Train of thought:

Import random module and call random.randint() method to generate random number

Use a dictionary to save the number of occurrences of each element, where key is the number of occurrences of each element (i.e. [0,512]), value is the number of occurrences of each element, of course, you can do without a dictionary, directly call the count function of the list in python such as list.count(0) to return the number of occurrences of the number 0 in the list.

Operation results:

 

 

 

Second questions

 1 #!/usr/bin/python
 2 #-*- coding:utf-8 -*-
 3 
 4 import sys
 5 import os
 6 
 7 version_error_info = 'Please use Python2'.decode('utf-8').encode('gbk')
 8 
 9 if sys.version_info >= (3, 0):
10    raise RuntimeError(version_error_info)
11 
12 def build():
13     str = raw_input()
14     global list
15     list = str.split(' ')
16     list = [int(list[i]) for i in range(len(list))]   # Strong input character to integer
17 
18 def show():
19     # for i in range(len(list)):
20     #     print(list[i], end=' ')
21     # print()
22     start,end = map(int, raw_input().split())   # Enter two integers
23     print list[start:end]
24 
25 def main():
26     build()
27     show()
28     os.system('pause')
29     
30 if __name__ == '__main__':
31     main()

Train of thought:

I should have a problem here. I don't need to convert the input characters into integers, but I still need to convert the input two integers.

Operation results:

 

Third questions

 1 #!/usr/bin/python 
 2 # -*- coding: utf-8 -*-
 3 
 4 import sys
 5 import os
 6 
 7 version_error_info = 'Please use Python2'.decode('utf-8').encode('gbk')
 8 
 9 if sys.version_info >= (3, 0):
10    raise RuntimeError(version_error_info)
11 
12 dic = {'Name':12, 'age':20, 'sex':'boy'}
13 
14 def run():
15     while True:
16         key = raw_input()
17         # Python3 Not in has_key()Method, be__contains__()Replace
18         # if dic.has_key(key):
19         if key in dic:
20             print dic[key]
21         else:
22             print 'The key you entered does not exist'.decode('utf-8').encode('gbk')
23             break
24 
25 def main():
26     run()
27     os.system('pause')
28     
29 if __name__ == '__main__':
30     main()

Operation results:

 

Fourth questions

 1 #!/usr/bin/python 
 2 # -*- coding: utf-8 -*-
 3 
 4 import sys
 5 import os
 6 
 7 version_error_info = 'Please use Python2'.decode('utf-8').encode('gbk')
 8 
 9 if sys.version_info >= (3, 0):
10    raise RuntimeError(version_error_info)
11 
12 def build():
13     global list_key    # List, element is key in dictionary
14     global list_value  # List with elements as keys in the dictionary
15     global dic         # A dictionary that combines two lists
16     global n           # Length of smaller lists
17     str = raw_input()
18     list_key = str.split(' ')
19     str = raw_input()
20     list_value = str.split(' ')
21     dic = {}           # Dictionary statement
22     n = len(list_key) if len(list_key)<len(list_value) else len(list_value)
23     for i in range(n):
24         dic[list_key[i]]=list_value[i]
25 
26 def show():
27     # for i in range(n):
28     #     print list_key[i],':',list_value[i]
29     print dic
30 
31 def main():
32     build()
33     show()
34     os.system('pause')
35     
36 if __name__ == '__main__':
37     main()

Running results: (Enter the dictionary corresponding to the third question here)

 

Conclusion:

1. The Method of Generating Random Numbers

Import random module and call various functions in the module

2. Method of suspending a program at the end of its operation

Import os module and call system("pause") function

3. Calling print function in Python 2 to output strings containing Chinese characters results in ascii or scrambling

(In different environments, the solution here corresponds to the environment in my laptop)

After the string, add ". decode('utf-8').encode('gbk')" (convert ascii code to GBK Chinese code)

4. Method of Inputting Two Integers

    a, b = map(int, raw_input().split())

Posted by siko on Wed, 15 May 2019 23:22:00 -0700