Click here to Skip to main content
14,920,001 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Problem:
Take two integers, a and b, from user input, where a<b and a+19=b.
Generate a 4x5 2-d numpy array of integers ranging from a to b, inclusive. Print the array.
Create a new 4x5 array by reversing the columns of the array created in Part 2. Print the new array.
Create a new 4x5 array by switching the second and the fourth row of the array created in Part 3. Print the new array.
(Note: in order to pass the test cases, the output from your code should match exactly the desired output.)

 

User Input:
1
20
Desired Output:
Output for 2:
[[ 1  2  3  4  5]
 [ 6  7  8  9 10]
 [11 12 13 14 15]
 [16 17 18 19 20]]
 
Output for 3:
[[ 5  4  3  2  1]
 [10  9  8  7  6]
 [15 14 13 12 11]
 [20 19 18 17 16]]
 
Output for 4:
[[ 5  4  3  2  1]
 [20 19 18 17 16]
 [15 14 13 12 11]
 [10  9  8  7  6]]


What I have tried:

Python
import numpy as np
# 1. get a and b from user
a = int(input())
b = int(input())

# 2. generate desired output:
A = np.arange(a,b+1).reshape((4,5))

print('Output for 2:')
print(A)

print('\nOutput for 3:')
revarray = A[:,::-1]
print(revarray)

print('\nOutput for 4:')
A[[1,3]] = revarray[[3,1]]
print(A)
Posted
Updated 10-Dec-20 23:57pm
v2

1 solution

Firstly in step 1 read the instructions carefully
your code should get only a from user input and calculate b according the rules given -
Quote:
where a<b and a+19=b
. Note that the condition a<b is meaningless because of the condition a+19=b - Have you copied that down correctly? It would also be nice to give the user a prompt so they know what to enter. So I used
Python
# 1. get a and b from user
print('\nEnter an integer value:')
a = int(input())
b = a + 19
Then swapping the rows over is quite trivial
1. Store one of the rows in a temporary variable
2. Assign the other row values to the original row
3. Assign the original row to the temporary variable

The key is your attempt is referring to single elements of the array [1,3] and [3,1] instead of the entire row revarray[1] and revarray[3]. Example
Python
print('\nOutput for 4:')
temp = revarray[1]
revarray[1] = revarray[3]
revarray[3] = temp
print(revarray)
   

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900