26. What is the output of the following script?
print(sum(range(5),-1))
from numpy import *
print(sum(range(5),-1))
print(sum(range(5),-1))
from numpy import *
print(sum(range(5),-1))
import numpy as np
print(np.sum(range(5),-1))
python의 sum은 sum(sequence[,start]) python의 내장함수
-1+1+2+3+4=9
numpy.sum(a, axis=None),axis 축으로 더한다.
27. Consider an integer vector Z, which of these expressions are legal?
Z**Z
2 << Z >> 2
Z <- Z
1j*Z
Z/1/1
Z<Z>Z
import numpy as np
Z = np.random.randint(1,4,(5,5))
print(Z**Z)
print(2 << Z >> 2)
print(Z <- Z)
print(1j*Z)
print(Z/1/1)
print(Z<Z>Z) #오류가 난다.
[[27 1 1 1 4] [ 1 1 1 1 27] [ 4 1 4 4 1] [ 1 4 4 27 1] [ 4 27 1 1 1]] [[4 1 1 1 2] [1 1 1 1 4] [2 1 2 2 1] [1 2 2 4 1] [2 4 1 1 1]] [[False False False False False] [False False False False False] [False False False False False] [False False False False False] [False False False False False]] [[0.+3.j 0.+1.j 0.+1.j 0.+1.j 0.+2.j] [0.+1.j 0.+1.j 0.+1.j 0.+1.j 0.+3.j] [0.+2.j 0.+1.j 0.+2.j 0.+2.j 0.+1.j] [0.+1.j 0.+2.j 0.+2.j 0.+3.j 0.+1.j] [0.+2.j 0.+3.j 0.+1.j 0.+1.j 0.+1.j]] [[3. 1. 1. 1. 2.] [1. 1. 1. 1. 3.] [2. 1. 2. 2. 1.] [1. 2. 2. 3. 1.] [2. 3. 1. 1. 1.]]
--------------------------------------------------------------------------- ValueError Traceback (most recent call last) <ipython-input-5-b8e9b3bf440b> in <module> 6 print(1j*Z) 7 print(Z/1/1) ----> 8 print(Z<Z>Z) #오류가 난다. ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
28. What are the result of the following expressions?
np.array(0) / np.array(0)
np.array(0) // np.array(0)
np.array([np.nan]).astype(int).astype(float)
print(np.array(0) / np.array(0))
print(np.array(0) // np.array(0))
print(np.array([np.nan]).astype(int).astype(float))
nan 0 [-2.14748365e+09]
29. How to round away from zero a float array ?
#hint: np.uniform, np.copysign, np.ceil, np.abs, np.where
data = np.random.random(5)*100
data1 = np.round(data+0.5)
data2 = np.copysign(np.ceil(np.abs(data)),data)
print(data)
print(data1)
print(data2)
[78.43772873 89.73307257 96.14244721 19.5070952 27.94266262]
[79. 90. 97. 20. 28.]
[79. 90. 97. 20. 28.]
30. How to find common values between two arrays?
#hint: np.intersect1d
data1 = np.random.randint(1,5,10)
data2 = np.random.randint(3,10,10)
print(np.intersect1d(data1,data2))
31. How to ignore all numpy warnings (not recommended)?
#hint: np.seterr, np.errstate
data = np.seterr(all= "ignore")
data1 = np.ones(1) / 0
_ = np.seterr(**data)
with np.errstate(divide='ignore'):
data = np.ones(1) / 0
numpy.org/doc/stable/reference/generated/numpy.errstate.html
32. Is the following expressions true?
print(np.sqrt(-1) == np.emath.sqrt(-1))
print(np.sqrt(-1) )
print(np.emath.sqrt(-1))
33. How to get the dates of yesterday, today and tomorrow?
yesterday = np.datetime64('today','D') - np.timedelta64(1,'D')
print(yesterday)
today = np.datetime64('today','D')
print(today)
tomorrow = np.datetime64('today','D') + np.timedelta64(1,'D')
print(tomorrow)
34. How to get all the dates corresponding to the month of July 2016?
#np.arange(dtype=datetime64['D'])
data = np.arange('2016-07','2016-08', dtype='datetime64[D]')
print(data)
35. How to compute ((A+B)*(-A/2)) in place (without copy)?
#hint: np.add(out=), np.negative(out=), np.multiply(out=), np.divide(out=)
A = np.ones(3)*1
B = np.ones(3)*2
np.add(A,B, out = B)
np.negative(A, out=A)
np.divide(A,2,out = A)
np.multiply(A,B,out = A)
array([-1.5, -1.5, -1.5])
36. Extract the integer part of a random array using 5 different methods
#hint: %, np.floor, astype, np.trunc
data = np.random.uniform(0,10,10)
print (data - data%1)
print (np.floor(data))
print (np.ceil(data)-1)
print (data.astype(int))
print (np.trunc(data))
37. Create a 5x5 matrix with row values ranging from 0 to 4
#hint: np.arange
data = np.zeros((5,5))
print(data)
data += np.arange(5)
print(data)
38. Consider a generator function that generates 10 integers and use it to build an array
#hint: np.fromiter
def generate():
for x in range(10):
yield x
data = np.fromiter(generate(), dtype = float, count = -1)
print(data)
[0. 1. 2. 3. 4. 5. 6. 7. 8. 9.]
39. Create a vector of size 10 with values ranging from 0 to 1, both excluded
#hint: np.linspace
print(np.linspace(0,1,11))
print(np.linspace(0,1,11,endpoint=False))
print(np.linspace(0,1,11,endpoint=False)[1:])
40. Create a random vector of size 10 and sort it
#hint: sort
data = np.random.random(10)
data.sort()
print(data)
41. How to sum a small array faster than np.sum?
#hint: np.add.reduce
import datetime
t0 = datetime.datetime.now()
data = np.arange(10)
for i in range(999):
np.sum(data)
t1 = datetime.datetime.now()
print(t1-t0)
t0 = datetime.datetime.now()
data = np.arange(10)
for i in range(999):
np.add.reduce(data)
t1 = datetime.datetime.now()
print(t1-t0)
42. Consider two random array A and B, check if they are equal
#hint: np.allclose, np.array_equal
A = np.random.randint(0,2,5)
B = np.random.randint(0,2,5)
print(A)
print(B)
data = np.allclose(A,B)
print(data)
data = np.array_equal(A,B)
print(data)
43. Make an array immutable (read-only)
#hint: flags.writeable
data = np.zeros(10)
data.flags.writeable= False
data[0]=1
44. Consider a random 10x2 matrix representing cartesian coordinates, convert them to polar coordinates
#hint: np.sqrt, np.arctan2
Z = np.random.random((10,2))
print(Z)
X,Y = Z[:,0], Z[:,1]
print(X)
print(Y)
R = np.sqrt(X**2 + Y**2)
T = np.arctan2(Y,X)
print(R)
print(T)
45. Create random vector of size 10 and replace the maximum value by 0
#hint: argmax
data = np.random.random(10)
print(data)
print(data.argmax())
print(data[data.argmax()])
data[data.argmax()] = 0
print(data)
46. Create a structured array with x and y coordinates covering the [0,1]x[0,1] area
#hint: np.meshgrid
Z = np.zeros((5,5))
print(Z)
Z = np.zeros((5,5), [('x',float),('y',float)])
print(Z)
Z['x'], Z['y'] = np.meshgrid(np.linspace(0,1,5),
np.linspace(0,1,5))
print(Z)
47. Given two arrays, X and Y, construct the Cauchy matrix C (Cij =1/(xi - yj))
#hint: np.subtract.outer
X = np.arange(8)
print(X)
Y = X+0.5
print(Y)
C = 1.0 / np.subtract.outer(X, Y)
print(np.linalg.det(C))
48. Print the minimum and maximum representable value for each numpy scalar type
#hint: np.iinfo, np.finfo, eps
for dtype in [np.int8, np.int32, np.int64]:
print(np.iinfo(dtype).min)
print(np.iinfo(dtype).max)
for dtype in [np.float32, np.float64]:
print(np.finfo(dtype).min)
print(np.finfo(dtype).max)
print(np.finfo(dtype).eps)
49. How to print all the values of an array?
np.set_printoptions(threshold=np.nan)
ValueError: threshold must be non-NAN, try sys.maxsize for untruncated representation
#hint: np.set_printoptions
#np.set_printoptions(threshold=np.nan)
data = np.zeros((10,10))
print(data)
50. How to find the closest value (to a given scalar) in a vector?
#hint: argmin
data = np.arange(100)
print(data)
v = np.random.uniform(0,100)
print(v)
index = (np.abs(data - v)).argmin()
print(data[index])
'문제 > Numpy 100제' 카테고리의 다른 글
numpy exercise-4 (0) | 2021.02.03 |
---|---|
100 numpy exercises-3 (0) | 2021.01.29 |
100 numpy exercises-1 (0) | 2021.01.27 |