I’m writing a program that the user must input a binary matrix. how can i do that.
What is the best way to say the user how to input that matrix?
I’m writing a program that the user must input a binary matrix. how can
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
There are many different possibilities. For example:
First, you could use a spreadsheet-like GUI (or similar
cursesUI), console-style text input, or all kinds of other things.Assuming you’ve decided on going with console input, the most obvious solution is probably space-separated columns, newline-separated rows. But that may not be the best solution for your use case.
If you users might want to copy and paste the output of one run into the input of the next, you probably want to either allow or require the brackets and commas as you’re going to print them out. Or, if they might copy from a CSV file, allow or require commas. And so on.
If the matrices have to be square, you don’t need the newlines. On the other hand, having them makes the input look nicer, and allows you to give much better error handling (“row 3 has 8 values instead of 7” vs. “you entered 50 values instead of 49”).
Since the values are binary, you don’t need the spaces either. This has similar tradeoffs.
You could also use two characters closer together on the keyboard than
1and0, or more visually distinct (e.g.,Xand.), or more relevant to your problem space.And so on. The point is, there is no one “best way”; there are dozens of tradeoffs to be made, and maybe even innovative design decisions that will lead to even more tradeoffs.
Once you pick one, they’re almost all easy to implement. For example, let’s do space-separated columns, newline separated rows, with a blank line meaning the end:
You can obviously merge some of those lines together, or turn the whole thing into a list comprehension or a generator, but I left it like this so you can add whatever error handling you find appropriate. (You may notice there’s no error handling at all—if you enter the wrong number of columns on some line you’ll get a jagged matrix; if you accidentally type
qinstead of1it’ll raise an exception; etc.)