Home > Net >  How can I take a triangular matrix like this from the user as an input With Python
How can I take a triangular matrix like this from the user as an input With Python

Time:12-26

I want to take a matrix exactly like this from the user where the first row has an empty column and the second row has 1 column and so on.. elements in column = row - 1

Matrix= [
    [],  # A
    [9],  # B
    [2, 9],  # C
    [4, 6, 5],  # D
    [9, 2, 9, 6],  # E
    [10, 10, 10, 10, 10]  # F
]

CodePudding user response:

IIUC, you want to ask for user input for each individual value:

n = int(input("Enter the number of sequences:"))

out = [[] for i in range(n)]

for i in range(1, n):
    print(f'please input the {i} value(s) of row {i}')
    for j in range(i):
        out[i].append(int(input(f'value {j 1}/{i}')))
simulating the input with an iterator
it = iter([9, 2, 9, 4, 6, 5, 9, 2, 9, 6, 10, 10, 10, 10, 10])

n = 6

out = [[] for i in range(n)]

for i in range(1, n):
    print(f'please input the {i} value(s) of row {i}')
    for j in range(i):
        print(f'value {j 1}/{i}')
        out[i].append(next(it))
        
print(out)

output:

please input the 1 value(s) of row 1
value 1/1
please input the 2 value(s) of row 2
value 1/2
value 2/2
please input the 3 value(s) of row 3
value 1/3
value 2/3
value 3/3
please input the 4 value(s) of row 4
value 1/4
value 2/4
value 3/4
value 4/4
please input the 5 value(s) of row 5
value 1/5
value 2/5
value 3/5
value 4/5
value 5/5
[[], [9], [2, 9], [4, 6, 5], [9, 2, 9, 6], [10, 10, 10, 10, 10]]

CodePudding user response:

You could use a couple for loops based on how many rows the user wants to enter:

def get_int_input(prompt: str) -> int:
    num = -1
    while True:
        try:
            num = int(input(prompt))
            break
        except ValueError:
            print('Error: Enter an integer, try again...')
    return num


def main() -> None:
    triangle_matrix = [[]]
    num_rows = get_int_input('How many rows would you like to enter: ')
    for r in range(1, num_rows   1):
        row = []
        for c in range(r):
            row.append(get_int_input(f'Enter value for row={r}, col={c}: '))
        triangle_matrix.append(row)
    print('You entered the following triangle matrix:')
    for row in triangle_matrix:
        print(row)


if __name__ == '__main__':
    main()

Example Usage:

How many rows would you like to enter: 5
Enter value for row=1, col=0: 9
Enter value for row=2, col=0: 2
Enter value for row=2, col=1: 9
Enter value for row=3, col=0: 4
Enter value for row=3, col=1: 6
Enter value for row=3, col=2: 5
Enter value for row=4, col=0: 9
Enter value for row=4, col=1: 2
Enter value for row=4, col=2: 9
Enter value for row=4, col=3: 6
Enter value for row=5, col=0: 10
Enter value for row=5, col=1: 10
Enter value for row=5, col=2: 10
Enter value for row=5, col=3: 10
Enter value for row=5, col=4: a
Error: Enter an integer, try again...
Enter value for row=5, col=4: 10
You entered the following triangle matrix:
[]
[9]
[2, 9]
[4, 6, 5]
[9, 2, 9, 6]
[10, 10, 10, 10, 10]

CodePudding user response:

You might want to have a look at Python's input function and (nested) for loops. The .append(obj) method on lists might also be helpful.

A possible approach:

x = []
for i in range(7):
    x.append([])
    for _ in range(i):
        x[-1].append(input("Type:"))
print(x)

Problem in your code:

  1. There's a problem where you define m. Because you're accessing m by index, you should define it with the correct length from the beginning:

    [[] for _ in range(n)]
    
  2. You don't have to define all variables at the beginning. You can always redefine them later. Clearing row isn't necessary if you just redefine it in every iteration.

n = int(input("Enter the number of sequences:")) 
m = [[] for _ in range(n)]
for i in range(n): 
    row = []
    for j in range(i):         
        s = input(f"Enter the distance (line {i 1}, elem {j 1}): ")         
        row.append(s)     
    m[i] = row
print(m)     

CodePudding user response:

I think just running the input statement inside the loop should do your work.

n=int(input("Enter number of lines "))
c=1
for i in range(1,n 1):
    if(i>2):
        c =1
    print("Enter input for row " str(i))
    for j in range(0,c):
        if(i==1):
            s=0
        else:
            input()
print("End of program")

Result looks like this:

Enter number of lines 
5
Enter input for row 1
Enter input for row 2
1
Enter input for row 3
1
2
Enter input for row 4
1
2
3
Enter input for row 5
1
2
3
4
End of program


** Process exited - Return Code: 0 **
Press Enter to exit terminal

CodePudding user response:

There's a trick you can use with islice (from itertools) by combining it with enumerate in a list comprehension:

fromUser = [9, 2, 9, 4, 6, 5, 9, 2, 9, 6, 10, 10, 10, 10, 10]

from itertools import islice

chunk  = iter(fromUser)
matrix = [[]]   [[n,*islice(chunk,i)] for i,n in enumerate(chunk)]

print(*matrix,sep='\n')
[]
[9]
[2, 9]
[4, 6, 5]
[9, 2, 9, 6]
[10, 10, 10, 10, 10]
  • Related