How to input values of the matrix from keyboard in python
Chris Rebert
clp2 at rebertia.com
Wed Aug 11 17:13:04 EDT 2010
On Wed, Aug 11, 2010 at 12:06 PM, Chris Rebert <clp2 at rebertia.com> wrote:
> On Wed, Aug 11, 2010 at 11:43 AM, Pramod <pramo4d at gmail.com> wrote:
>> Hi
>>
>> I want to know the how we input values into the matrix (N*N size)
>> from keyboard in python,
>>
>> Here I wrote Matrix programe in C++
>>
>> This asks values from key board and print on the console N*N matrix ;
>>
>> Thanks in advance ....
>>
>>
>> #include<iostream>
>> using namespace std;
>> int main()
>> {
>> double **a;
>> int i,j,n;
>> cout<<"Enter size of the matrix\n";
>> cin>>n;
>> for(i=0;i<n;i++){
>> for(j=0;j<n;j++)
>> a[i][j] = random();
>> //or
>> //cin>>a[i][j];
>> cout<<endl;
>> }
>> for(i=0;i<n;i++){
>> for(j=0;j<n;j++)
>> cout<<a[i][j]<<"\t";
>> cout<<endl;
>> }
>> delete [] a;
>> }
>
> from random import random
> from sys import exit
>
> while True:
> try:
> N = int(raw_input("Enter size of the matrix: "))
> except ValueError:
> print "Invalid input. Try again."
> except EOFError:
> exit(1)
> else:
> break
>
> a = [[random() for j in xrange(N)] for i in xrange(N)]
> stringified = "\n".join("\t".join(row) for row in a)
> print stringified
Should have prefaced that with an "untested" disclaimer.
Make that:
stringified = "\n".join("\t".join(str(cell) for cell in row) for row in a)
- Chris
More information about the Python-list
mailing list