Monday, 23 December 2024

Python Coding Challange - Question With Answer(01231224)

 


What will be the output of the following code?

import numpy as np
arr = np.arange(1, 10).reshape(3, 3)
result = arr.sum(axis=0) - arr.sum(axis=1)
print(result)

[0, 0, 0]
[1, -1, 1]
[3, -3, 3]
[2, 2, -2]

Step 1: Create the array with np.arange(1, 10)

The function np.arange(1, 10) creates a 1D NumPy array containing integers from 1 to 9 (inclusive of 1 but exclusive of 10).

np.arange(1, 10) = [1, 2, 3, 4, 5, 6, 7, 8, 9]

Step 2: Reshape the array to 3x3

The method .reshape(3, 3) converts the 1D array into a 2D array with 3 rows and 3 columns:

arr = [[1, 2, 3],
[4, 5, 6], [7, 8, 9]]

Step 3: Compute arr.sum(axis=0)

The parameter axis=0 means sum along columns (vertically).
For each column, we add the elements from the top to the bottom:

  • First column: 1+4+7=121 + 4 + 7 = 12
  • Second column: 2+5+8=152 + 5 + 8 = 15
  • Third column: 3+6+9=183 + 6 + 9 = 18

Result of arr.sum(axis=0):

[12, 15, 18]

Step 4: Compute arr.sum(axis=1)

The parameter axis=1 means sum along rows (horizontally).
For each row, we add the elements from left to right:

  • First row: 1+2+3=61 + 2 + 3 = 6
  • Second row: 4+5+6=154 + 5 + 6 = 15
  • Third row: 7+8+9=247 + 8 + 9 = 24

Result of arr.sum(axis=1):

[6, 15, 24]

Step 5: Perform element-wise subtraction

The subtraction operation is element-wise, meaning corresponding elements of the two arrays are subtracted.

  • 126=612 - 6 = 6
  • 1515=015 - 15 = 0
  • 1824=618 - 24 = -6

Result of arr.sum(axis=0) - arr.sum(axis=1):

[6, 0, -6]

Step 6: Print the result

Finally, the result is printed:

[6, 0, -6]

Key Points:

  1. axis=0 computes the sum along columns (vertically).
  2. axis=1 computes the sum along rows (horizontally).
  3. Subtraction is performed element-wise between the two resulting arrays.

0 Comments:

Post a Comment

Popular Posts

Categories

100 Python Programs for Beginner (53) AI (34) Android (24) AngularJS (1) Assembly Language (2) aws (17) Azure (7) BI (10) book (4) Books (173) C (77) C# (12) C++ (82) Course (67) Coursera (226) Cybersecurity (24) data management (11) Data Science (128) Data Strucures (8) Deep Learning (20) Django (14) Downloads (3) edx (2) Engineering (14) Excel (13) Factorial (1) Finance (6) flask (3) flutter (1) FPL (17) Google (34) Hadoop (3) HTML&CSS (47) IBM (25) IoT (1) IS (25) Java (93) Leet Code (4) Machine Learning (59) Meta (22) MICHIGAN (5) microsoft (4) Nvidia (3) Pandas (4) PHP (20) Projects (29) Python (932) Python Coding Challenge (364) Python Quiz (25) Python Tips (2) Questions (2) R (70) React (6) Scripting (1) security (3) Selenium Webdriver (3) Software (17) SQL (42) UX Research (1) web application (8) Web development (2) web scraping (2)

Followers

Person climbing a staircase. Learn Data Science from Scratch: online program with 21 courses