-
Notifications
You must be signed in to change notification settings - Fork 0
/
Jay_num_solution.py
641 lines (531 loc) · 15.1 KB
/
Jay_num_solution.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
from __future__ import division, print_function, absolute_import
""" In this exercise, you will specify an array by providing a
1-dimensional list of numbers and a tuple containing the shape of the array.
For example, the following
>>> data = range(8)
>>> shape = (2, 2, 2)
corresponds to the following ndarray
>>> import numpy as np
>>> x = np.arange(8)
>>> x.shape = (2, 2, 2)
Note that (as in part of homework 1) you will not be allowed to use NumPy
in your implementation. Specifically, you should only use Python builtins,
`product`, and `reduce`. I've already imported product and reduce. You
should not add any additional imports. The purpose of this assignment is
to have you implement everything by hand (with the exception of product
and reduce).
Your task is to implement some of the functionality of NumPy's arrays. To do
this, you will be representing a multidimensional array as a (linear) 1-D list
of numbers. You will store the multidimensional layout of the data array in a
shape tuple. There are two standard ways to fill-in the multidimensional
structure specified by shape from the linear order of the list of
numbers---row-major and column-major order.
You will be using row-major ordering (NumPy's default) for this exercise.
So you will need to understand what that means.
Consider this example:
>>> x
array([[[0, 1],
[2, 3]],
[[4, 5],
[6, 7]]])
>>> x[0, 0, 0]
0
>>> x[0, 0, 1]
1
>>> x[0, 1, 0]
2
>>> x[0, 1, 1]
3
>>> x[1, 0, 0]
4
>>> x[1, 0, 1]
5
>>> x[1, 1, 0]
6
>>> x[1, 1, 1]
7
Look carefully at the pattern. Notice that the axis on the far right
position increments the fastest. Then the axis next to it increments
a little slower.
Let's look at a bigger example.
>>> x = np.arange(64)
>>> x.shape = (2, 4, 4, 2)
>>> x[0, 0, 0, 0]
0
>>> x[0, 0, 0, 1]
1
>>> x[0, 0, 1, 0]
2
>>> x[0, 0, 2, 0]
4
>>> x[0, 0, 3, 0]
6
>>> x[0, 1, 0, 0]
8
>>> x[0, 2, 0, 0]
16
>>> x[0, 3, 0, 0]
24
>>> x[1, 0, 0, 0]
32
Notice that when you cycle on the ith axis each increase is in a fixed amount,
depending on the shape of the array and the position in the index that is
incrementing.
To read more about row-major order see:
https://en.wikipedia.org/wiki/Row-major_order
Below you will find several functions involving working on arrays
represented as a list of numbers and a tuple containing the shape of the
array. As a result, the first two arguments to many of the functions will
normally correspond to this information.
"""
# this might be useful in the `get_increment` function (more information there)
from functools import reduce
# this might be useful in the `extract` function (more information there)
from itertools import product
def size(shape, axis=None):
"""
Return the number of elements along a given axis.
Parameters
----------
shape : tuple
The shape of the input array
axis : int, optional
Axis along which the elements are counted. By default, give
the total number of elements.
Returns
-------
element_count : int
Number of elements along the specified axis.
Examples
--------[]
>>> shape = (2, 3, 2)
>>> size(shape)
12
>>> size(shape, axis=0)
2
>>> size(shape, axis=1)
3
"""
num = 1
if axis == None:
for i in shape:
num = num * i
return num
else:
return shape[axis]
def ndim(shape):
"""
Return the number of dimensions of an array.
Parameters
----------
shape : tuple
The shape of the input array.
Returns
-------
number_of_dimensions : int
The number of dimensions in `a`.
Examples
--------
>>> ndim((2, 2, 2))
3
>>> ndim((2,))
1
"""
return len(shape)
def reshape(data, newshape):
"""
Gives a new shape to an array without changing its data.
Parameters
----------
data : list
Array to be reshaped.
newshape : int or tuple of ints
The new shape should be compatible with the original shape. If
an integer, then the result will be a 1-D array of that length.
Returns
-------
newshape : tuple
This will be the passed in shape if possible, otherwise return None
Examples
--------
>>> reshape(range(8), (2, 2)) is None
True
>>> reshape(range(8), (2, 4))
(2, 4)
>>> reshape(range(8), (8,))
(8,)
"""
data_list = []
for i in data:
data_list .append(i)
if len(data_list) == size(newshape, axis = None):
return newshape
else:
return None
def is_valid_index(shape, index):
"""
Check whether the index is compatible with the shape.
Parameters
----------
shape : tuple
The shape of the input array
index : tuple
The position of an element.
Returns
-------
valid : bool
True is the index is valid for the given shape, False otherwise
Examples
--------
>>> is_valid_index((2,2), (1,3))
False
>>> is_valid_index((2,2), (1,1))
True
"""
for i in range(len(index)):
if shape[i] <= index[i]:
return False
break
return True
def get_increment(shape):
"""
Return the increments corresponding to each axis or dimension in the shape.
Parameters
----------
shape : tuple
The shape of the input array.
Returns
-------
increment_per_axis : list
The number of positions in the linear order that you need to move
to retrieve the element specified by incrementing each axis
in the corresponding index.
Note
----
You will need to understand row-major ordering to make sense of
this function. You may want to reread the module docstring if
you are unsure of what to do. Pay attention to the increment
along the linear array corresponding to incrementing the index
for each axis.
You may also wish to use `reduce`, which has already been imported from
functools above.
Examples
--------
>>> get_increment((2, 4))
[4, 1]
>>> get_increment((2, 2, 2))
[4, 2, 1]
>>> get_increment((2, 4, 3))
[12, 3, 1]
"""
result = []
if len(shape) == 1:
result = []
else:
for i in range(1, len(shape)):
result = result + [reduce(lambda x,y: x*y, shape[i:])]
return result + [1]
def get_position(shape, index):
"""
Return the position in the linear order specified by the given index in
the multidimensional array.
Parameters
----------
shape : tuple
The shape of the input array
index : tuple
The index position in the multidimensional array
Returns
-------
position : int
The position in the linear order specified by the index
Notes
-----
You only have to implement this using row major order:
https://en.wikipedia.org/wiki/Row-major_order
Make sure the index is valid before using it. For example, you could
use the function you wrote above:
assert is_valid_index(shape, index)
Examples
--------
>>> shape = (2,)
>>> get_position(shape, (0,))
0
>>> shape = (2, 2)
>>> get_position(shape, (0, 0))
0
>>> get_position(shape, (0, 1))
1
>>> get_position(shape, (1, 0))
2
>>> get_position(shape, (1, 1))
3
"""
assert is_valid_index(shape, index)
coeff = get_increment(shape)
position = 0
for i in range(len(shape)):
position = position + coeff[i] * index[i]
return position
def get_index(shape, position):
"""
Return the index in the multidimensional array that is corresponds to the
element in the given position in the linear ordered.
Parameters
----------
shape : tuple
The shape of the input array
position : int
The position in the linear ordering
Returns
-------
index : tuple (same number of elements as shape)
The index in the multidimensional array specified by the
position in linear order
Notes
-----
You only have to implement this using row major order:
https://en.wikipedia.org/wiki/Row-major_order
Make sure to check that the position is valid:
assert position < size(shape)
Exercises
---------
>>> shape = (2,)
>>> get_index(shape, 1)
(1,)
>>> shape = (2, 2, 2)
>>> get_index(shape, 4)
(1, 0, 0)
>>> get_index(shape, 2)
(0, 1, 0)
>>> get_index((4, 5, 2, 1, 3), 17)
(0, 2, 1, 0, 2)
"""
assert position < size(shape)
result = ()
if len(shape) == 1:
result = (position,)
else:
increment = get_increment(shape)
for i in increment:
result = result + (position // i, )
if position // i > 0:
position = position % i
return result
def get_item(data, shape, index):
"""
Return the value of the array at the given index.
Parameters
----------
data : list
Input data.
shape : tuple
The shape of the input array
index : tuple
The index of the element to be returned.
Returns
-------
element : number
Number occurring at the position specified by the index.
Examples
--------
>>> data = range(8)
>>> shape = (2, 2, 2)
>>> get_item(data, shape, (0, 0, 0))
0
>>> get_item(data, shape, (0, 0, 1))
1
>>> get_item(data, shape, (0, 1, 0))
2
>>> get_item(data, shape, (0, 1, 1))
3
>>> get_item(data, shape, (1, 0, 0))
4
>>> get_item(data, shape, (1, 0, 1))
5
"""
position = get_position(shape, index)
return data[position]
def nonzero(data, shape):
"""
Return the indices of the elements that are non-zero.
Returns a tuple of arrays, one for each dimension of `data`, containing
the indices of the non-zero elements in that dimension.
Parameters
----------
data : list
Input data.
shape : tuple
The shape of the input array
Returns
-------
tuple_of_arrays : tuple
Indices of elements that are non-zero.
Examples
--------
>>> data = range(8)
>>> shape = (2, 2, 2)
>>> nonzero(data, shape)
((0, 0, 0, 1, 1, 1, 1), (0, 1, 1, 0, 0, 1, 1), (1, 0, 1, 0, 1, 0, 1))
>>> [get_item(data, shape, index) for index in zip(*nonzero(data, shape))]
[1, 2, 3, 4, 5, 6, 7]
>>> d = [n % 2 for n in data]
>>> shape = reshape(d, (2, 4))
>>> nonzero(d, shape)
((0, 0, 1, 1), (1, 3, 1, 3))
>>> [get_item(data, shape, index) for index in zip(*nonzero(d, shape))]
[1, 3, 5, 7]
"""
index = []
result = ()
for i in range(len(data)):
if not data[i] == 0:
index = index + [get_index(shape, i)]
for j in zip(*index):
result = result + (j,)
return result
def extract(data, shape, axis, element):
"""
Extract the subarray at the given element along the given axis.
Parameters
----------
data : list
Input data.
shape : tuple
The shape of the input array
axis : int
Axis along which the subarray is extracted
element : int
Element identifying the subarray to be extracted
Returns
-------
new array: (newdata, newshape)
Notes
-----
Here are some examples using NumPy to help illustrate:
In [1]: import numpy as np
In [2]: y = np.arange(32)
In [3]: y.shape = (2, 4, 4)
In [4]: y
Out[4]:
array([[[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11],
[12, 13, 14, 15]],
[[16, 17, 18, 19],
[20, 21, 22, 23],
[24, 25, 26, 27],
[28, 29, 30, 31]]])
The following would be specified by `axis=0` and `element=1`
In [5]: y[1, :, :]
Out[5]:
array([[16, 17, 18, 19],
[20, 21, 22, 23],
[24, 25, 26, 27],
[28, 29, 30, 31]])
The following would be specified by `axis=1` and `element=1`
In [6]: y[:, 1, :]
Out[6]:
array([[ 4, 5, 6, 7],
[20, 21, 22, 23]])
The following would be specified by `axis=2` and `element=3`
In [7]: y[:, :, 3]
Out[7]:
array([[ 3, 7, 11, 15],
[19, 23, 27, 31]])
Hint
----
Take a look at the docstring for itertools.product. You can use it to
form the Cartesian product of a list of tuples (e.g., if the input shape
was (2, 3, 4) with `axis=1` and `element=1`, you might want to form the
Cartesian product of [range(2), (1,), range(4)]).
Examples
--------
>>> data = range(32)
>>> shape = (2, 4, 4)
>>> d, s = extract(data, shape, 2, 3)
>>> d
[3, 7, 11, 15, 19, 23, 27, 31]
>>> s
(2, 4)
"""
index = []
newdata = []
base = [range(i) for i in shape]
for i in product(*base):
if i[axis] == element:
index.append(i)
for j in index:
newdata = newdata + [get_item(data, shape, j)]
newshape = (int(len(newdata)/shape[-1]), shape[-1])
return (newdata, newshape)
# Reduction operations
def asum(data, shape, axis=None):
"""
Sum of array elements over a given axis.
Parameters
----------
data : list
Input data.
shape : tuple
The shape of the input array
axis : int, optional
Axis along which the sums are computed. The default is to compute
the sum of the flattened array.
Returns
-------
sum_along_axis : tuple (reduced_data, newshape)
Examples
--------
>>> data = range(32)
>>> shape = (2, 4, 4)
>>> asum(data, shape, 1)
([24, 28, 32, 36, 88, 92, 96, 100], (2, 4))
"""
newshape = []
tmp = []
if axis == None:
reduced_data = sum(data)
newshape = ()
else:
for i in range(shape[axis]):
tmp.append(extract(data, shape, axis, i)[0])
reduced_data = [sum(i) for i in zip(*tmp)]
newshape = (int(len(reduced_data)/shape[-1]), shape[-1])
return (reduced_data, newshape)
def mean(data, shape, axis=None):
"""
Compute the arithmetic mean along the specified axis.
Returns the average of the array elements. The average is taken over
the flattened array by default, otherwise over the specified axis.
Parameters
----------
data : list
Input data.
shape : tuple
The shape of the input array
axis : int, optional
Axis along which the means are computed. The default is to compute
the mean of the flattened array.
Returns
-------
mean_along_axis : tuple (reduced_data, newshape)
Examples
--------
>>> data = range(32)
>>> shape = (2, 4, 4)
>>> mean(data, shape)
(15.5, ())
>>> mean(data, shape, 2)
([1.5, 5.5, 9.5, 13.5, 17.5, 21.5, 25.5, 29.5], (2, 4))
"""
if axis == None:
tmp, newshape = asum(data, shape)
reduced_data = tmp / len(data)
else:
tmp, newshape = asum(data, shape, axis)
reduced_data = [x / shape[axis] for x in tmp]
return (reduced_data, newshape)
if __name__ == "__main__":
import doctest
doctest.testmod()