AITC Wiki

Practice1 solution

练习 1 参考答案

Practice1 solution

中文版:练习 1 参考答案

Review of python syntax

  1. Create an empty list and add 10 different numbers 1 to 10 to the list. Find the median value of the 10 numbers and store it in a variable named mid, and calculate the sum of all the numbers, store the value in variable result.
a=[]
for i in range(1,11):
 a.append(i)
 
print("a: ", a)
 
mid=a[int((len(a)-1)/2)]
print("mid: ",mid)
 
result=sum(a)
print("result: ",result)
  1. Define a function that takes a list as input, for all the elements greater than mid, replace it with the value of mid. If the element is smaller than or equal to mid, leave it unchanged. Return the new list.
def mid_replace(a):
 mid=a[int((len(a)-1)/2)]
 return([mid if i < mid else i for i in a])
a=list(range(1,11))
print(mid_replace(a))
  1. Define a function to sort all the numbers in the list in descending order and return the sorted list.
def sort_descending(a):
 return sorted(a, reverse=True)
a=list(range(1,11))
print(sort_descending(a))

Try by yourself

A matrix is a collection of numbers arranged in rows and columns. For example:

or

  1. Try representing matrix A and B using list
A=[1,2,3]
B=[[1,2],[3,4]]

Array

We have

implement the following operations using python:

Matrix addition:

Matrix multiplication:

A=[[1,2],[3,4]]
B=[[5,6],[7,8]]
C=A+B
print(type(A))
print(C)

Using “Numpy” to deal with Matrix (refer 02.00-02.02)

Check whether NumPy is installed and which version is installed.

import numpy
print(np.__version__)
  1. Import NumPy using np as an alias
import numpy as np
  1. Represent matrix A and B using an array in Numpy:
A=np.array([[1,2],[3,4]])
B=np.array([[5,6],[7,8]])
type(A)
  1. Print the number of dimensions, the size of each dimension, and the total size of the A.
print(A.shape)
  1. Creat an empty array X of shape 3x1, and print it
X=np.empty((3,1))
print(X)
  1. Create a 5×8 int type matrix with random values (e.g. 0 to 100) and print the entire fifth row and the entire fourth column of the matrix separately.
a=np.random.randint(100,size=(5,8))
print("a: ")
print(a)
 
print("5th row: ", a[4])
print("5th colomn: ", a[:,4])
  1. Extract all the rows, and every other column from the 3rd colomn to the 6th of array you created above
b=a[:,2:5:2]
print(b)