-2

Implement SQL like query tool where from STDIN following things have to be read in the given order:-

1. Number of rows of the table (n) and Number of queries (q).
2. Table fields separated by Comma.
3. n line containing table rows of the table
4. q queries where clause.

We have to print output for each query on STDOUT.

Eg:-

Input:

4,2

"Name","Age","Sex","Salary"

1,"Joy",21,"M",2000

2,"Alan",28,"M",500

3,"John",30,"M",1000

4,"Nemo",45,"F",1500

Salary>=1000

Sex="M" and Salary>499 

Output:

2

3

Can you guys tell how should I approach the problem? And What data structure should I be using to store the table and process the queries ?

PS: I am not asking for the ready made solution, I just need step wise help in solving this question.

1 Answers1

0

I'm guessing the excersise is impelenting SQL like for practice (and not real SQL becuase this is the obvious solution).

I'd have a list of dictionaries (a dict for each row) fill it with the data and than use list comprehension to filter the lines

[ line for line in lines if (line['Sex']=='M') and (line['Salary'] > 499)]

Of course you have a lot of parsing to do to create such a python command - but this is the direction

Boaz
  • 4,864
  • 12
  • 50
  • 90
  • Yes, It is just for practise. How should I go about it ? – Mohammad Asif Feb 23 '15 at 20:16
  • I edited the answer for an example of what you need to create. Basically filling the list is iterating line by line, and creating the queries is a lot of splitting and comparing (and you can do something fancy with regex if you want to challenge yourself) – Boaz Feb 23 '15 at 20:22
  • Thanks. But How Do I store the rows in dictionary? and how will I know wether the input for particular column will be int or string or date? Ps: I know I sound stupid, but I dint get much help from google. – Mohammad Asif Feb 23 '15 at 20:25
  • On a real SQL you specify the type when you create the tables (in the scheme) - here is an excersize - you "know" the type (name is string, age is int, etc...) – Boaz Feb 23 '15 at 20:28
  • you can try and "guess" but usually it is not robust (for instance try and convert it to a number) - but again - in this example - you are supposed to know the types – Boaz Feb 23 '15 at 20:48