Home > Software design >  How to input float values in a n-tuple matrix using python?
How to input float values in a n-tuple matrix using python?

Time:07-06

Pardon if my question is too basic since I've just started learning python

rows = int(input("Enter the Number of rows : "))   
column = int(input("Enter the Number of Columns: "))

print("Enter the elements of Matrix:")
matrix_a = [[tuple(input()) for i in range(column)] for i in range(rows)]
print("First Matrix is: ")
for n in matrix_a:
   print(n)

Getting the output as

Enter the Number of rows : 
2
Enter the Number of Columns: 
2
Enter the elements of Matrix:
123
456
987
644
First Matrix is: 
[('1', '2', '3'), ('4', '5', '6')]
[('9', '8', '7'), ('6', '4', '4')]

How can I input float values as elements of this n-tuple matrix.

like [ (0.9, 0.6, 0.5), (0.4, 0.5, 0.1) ]

CodePudding user response:

You can use (,) Python tuple creator to avoid splitting input elements:

rows = int(input("Enter the Number of rows : "))   
column = int(input("Enter the Number of Columns: "))

print("Enter the elements of Matrix:")
matrix_a = [[(input(),) for i in range(column)] for i in range(rows)]
print("First Matrix is: ")
for n in matrix_a:
   print(n)

Output:

Enter the Number of rows : 1
Enter the Number of Columns: 1
Enter the elements of Matrix:
999
First Matrix is: 
[('999',)]

Also, you can use a generator if you want a tuple of float elements:

rows = int(input("Enter the Number of rows : "))   
column = int(input("Enter the Number of Columns: "))

print("Enter the elements of Matrix:")
matrix_a = [[tuple(float(a) for a in input()) for i in range(column)] for i in range(rows)]
print("First Matrix is: ")
for n in matrix_a:
   print(n)

Enter the Number of rows : 1 Enter the Number of Columns: 1 Enter the elements of Matrix: 555 First Matrix is: [(5.0, 5.0, 5.0)]

CodePudding user response:

If you want to be able to input float values, you need to define a delimiter, e.g. a space between the input values. This also enables you to enter multi-digit numbers, which is not possible in the original version.

...
matrix_a = [[tuple(map(float, input().split(" ")))
             for i in range(column)] for i in range(rows)]

...

Enter the Number of rows : 2
Enter the Number of Columns: 2
Enter the elements of Matrix:
1.2 3.2 1.4
1 2 3
123
1.3 12 1
First Matrix is: 
[(1.2, 3.2, 1.4), (1.0, 2.0, 3.0)]
[(123.0,), (1.3, 12.0, 1.0)]
  • Related