#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jul 2012
    Posts
    7
    Rep Power
    0

    Python 2d array of objects help!


    Hey guys,
    Basically I'm currently doing a project at school to create a ticket booking system for school shows etc.
    I'm trying to create a 2d array 3x3 full of these seat objects so then they can be reserved(res) and named. I need to iteration of the array to number each seat.
    Can anyone help, this is a very early Prototype so I can just start thinking of how I'm going to do it.
    Any comments will be appreciated thanks!



    class seat(object):

    * * def __init__(self, seatNo, res, name):
    * * * * self.seatNo = seatNo
    * * * * self.res = res
    * * * * self.name = name


    seatList = []
    count1 = 0

    for count1 in range(1, 3):
    * * seatList.append(seat(count1, False, ""))
    * * for count2 in range(count1,6):
    * * * * seatList.append(seat(count2,False, ""))
  2. #2
  3. Contributing User
    Devshed Demi-God (4500 - 4999 posts)

    Join Date
    Aug 2011
    Posts
    4,963
    Rep Power
    481
    I advocate tests. Write tests, then code to make the tests pass. Write more tests, write a little more code toward the final goal, make those tests pass. Retain the early tests to make sure you haven't broken them. Change the tests if your design changes.

    I've added a __repr__ method to your class that returns the seat number as a str object, then I print the list you've made. The list is not two dimensional, displaying as [1, 1, 2, 3, 4, 5, 2, 2, 3, 4, 5]
    Code:
    class seat(object):
    
        def __init__(self, seatNo, res, name):
            self.seatNo = seatNo
            self.res = res
            self.name = name
    
        def __repr__(self):
            return str(self.seatNo)
    
    seatList = []
    
    for count1 in range(1, 3):
        seatList.append(seat(count1, False, ""))
        for count2 in range(count1,6):
            seatList.append(seat(count2,False, ""))
    
    print(seatList)
    I'd show more about testing if I knew what you actually intend.

    Thank you for caring about syntactical spacing. There's an easier way---highlight your code then press the # icon or the php icon to preserve spaces. See information at the link on my signature.

    Here's code that creates a 2D array:
    Code:
    >>> LIST = []
    >>> for i in range(3):
    ...     SUBLIST = []
    ...     LIST.append(SUBLIST)
    ...     for j in range(3):
    ...         SUBLIST.append('seat %2d%c'%(i,ord('A')+j))
    ... 
    
    >>> print LIST
    [['seat  0A', 'seat  0B', 'seat  0C'], ['seat  1A', 'seat  1B', 'seat  1C'], ['seat  2A', 'seat  2B', 'seat  2C']]
    >>> import pprint
    >>> pprint.pprint(LIST)
    [['seat  0A', 'seat  0B', 'seat  0C'],
     ['seat  1A', 'seat  1B', 'seat  1C'],
     ['seat  2A', 'seat  2B', 'seat  2C']]
    >>>

    Comments on this post

    • harps agrees : Excellent
    [code]Code tags[/code] are essential for python code and Makefiles!
  4. #3
  5. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jul 2012
    Posts
    7
    Rep Power
    0

    Smile


    It's going to be (after a 6 months- 1 year of development) a type of ticked booking system, as you would see online while trying to book cinema tickets.
    So the reason I have used a class is because I want each seat to hold information on whether it is reserverd, it's number and the name of the person reserving it. This is why you can see me attempting to append this into the 2d array I was trying to make

    I'd seen this pprint before, what does it do differently?
    Also what does the %2d%c bit do ?


    Sorry For all the questions i am very new to programming.
    Really tho thanks, can see what youv done and it's helping me get my head around it.
  6. #4
  7. Contributing User
    Devshed Demi-God (4500 - 4999 posts)

    Join Date
    Aug 2011
    Posts
    4,963
    Rep Power
    481
    pprint "pretty prints" its argument
    (or pprint.pformat returns a string) optional arguments select line length and other features.

    The % operator used with a string causes formatted substitutions using the values from the right hand tuple.

    "%d%c"%(i,j)

    means, in turn, %d converts the first item of the tuple to a string and replace the %d with that string, while the %c format means to use the character corresponding to the ASCII value of j. The Python group (Guido Van Rossum) may deprecate the % format operator in favor of the format string method. Or you could study the wikipedia string formatting article---string formatting is a common feature of computer languages dating back to, I should say, FORTRAN or perhaps Babbage's computing engine, driven by the desirability of a human form of internal representation.

    Anyway, my code was to demonstrate a 2D array structure presented as auditorium seating where I live.
    [code]Code tags[/code] are essential for python code and Makefiles!
  8. #5
  9. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jul 2012
    Posts
    7
    Rep Power
    0
    Sorry for the REALLY late reply, terms just started and back into the project.
    Been researching a bit and I'm getting the string formatting I just don't get why ASCII J - 106 is needed for anything ? :S
    The code is to create a a seating plan holding peoples names etc in. Just like how you'd book cinema tickets. However this is for school plays. This is why I though a class would be appropriate to store ther data.
    Hope you get this, the respond youv given so far has really helped.
  10. #6
  11. Contributing User
    Devshed Demi-God (4500 - 4999 posts)

    Join Date
    Aug 2011
    Posts
    4,963
    Rep Power
    481
    I intended the first section of my July 16th, 2012 01:41 PM post to
    1) help you visualize the structure you've actually created.
    2) encourage you to print small samples in many places for you to ensure that you've made what you expect.

    The second section of code was to show you how to construct a 2D array in python. Had you executed the code of the first section you'd recognize that you have not made a 2D array.


    I'm unfamiliar with "online ticket booking systems".

    The auditorium seats probably don't change much. The schedule changes a little bit as well as becomes extended into the future, and certainly the planned attendance varies frequently. I expected a structure---well I'd use dictionaries not arrays since gymnasium seating is grid like but auditorium seating is not---involving dates and seats, the seats storing customer information. Name, paid, reserved, hopeful, gratis, whatever. Then again, some theaters have variable ticket pricing. So the auditorium structure might have seat price and the audience information could be fairly separate.


    At any rate, I'm here as are many other top-notch question responders. I don't have a good idea about the nature of the current problematic issue.
    [code]Code tags[/code] are essential for python code and Makefiles!
  12. #7
  13. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jul 2012
    Posts
    7
    Rep Power
    0
    I have been using your code for the 2d array playing around with changing how large it is etc, the reason I was using a class is because I wanted to make the seats hold data such as names of people and whether they are reserved or not.
    Using your code I can't find a way to make this happen.
    Eventually I'm going to put a data base behind it but right now I can't make the seats created hold any information
  14. #8
  15. Contributing User
    Devshed Demi-God (4500 - 4999 posts)

    Join Date
    Aug 2011
    Posts
    4,963
    Rep Power
    481
    Code:
    '''
        $ python -c 'import p;p.main()'
        1500 vacant seats
        1499 vacant seats
        Current reservations for Clemens Center Powers Theater
        25:Michelle
    '''
    
    class Auditorium(object):
    
        def __init__(self,name,rows,columns):
            self.rows = rows
            self.columns = columns
            self.name = name
            a = self.seatList = []
            n = 0
            for count1 in range(rows):
                b = []
                a.append(b)
                for count2 in range(columns):
                    b.append(Seat(n,False, ''))
                    n += 1
    
        def getSeat(self,r,c=None):
            if None is c:
                (r,c,) = self.convert_seat_number_to_row_and_column(r)
            return self.seatList[r][c]
    
        def __str__(self):
            return '%s holds %d rows with %d seats per row'%(
                self.name,self.rows,self.columns)
    
        def convert_seat_number_to_row_and_column(self,n):
            return divmod(n,self.rows)
    
        def reserve(self,seatNo,name,override=False):
            seat = self.getSeat(seatNo)
            if seat and (not override):
                return False
            seat.reserve(name)
            return True
    
        def seats(self):
            return self.rows*self.columns
    
        def vacancies(self):                #****Duplicate code
            return [s for r in self.seatList for s in r if not s]
    
        def reserved(self): #****Duplicate code: with a 3rd similar function
            return [s for r in self.seatList for s in r if s] #****I'd find a general solution
    
    class Seat(object):
    
        def __init__(self, seatNo, res, name):
            self.seatNo = seatNo
            self.res = res                  # Boolean
            self.name = name
    
        def __repr__(self):
            return str(self.seatNo)
    
        def __str__(self):
            if self:
                return '%d:%s'%(self.seatNo,self.name)
            return repr(self)
    
        def __bool__(self):
            return self.res
    
        __nonzero__ = __bool__ # for python2
    
        def reserve(self,name):
            self.name = name
            self.res = True
    
    def main():
        T0 = Auditorium('Clemens Center Powers Theater',30,50)
        T1 = Auditorium('Clemens Center Mandeville Hall',10,20)
        print('%d vacant seats'%len(T0.vacancies()))
        FRONT_AND_CENTER = T0.columns//2
        T0.reserve(FRONT_AND_CENTER,'Michelle',override=True)
        print('%d vacant seats'%len(T0.vacancies()))
        print('Current reservations for %s'%T0.name)
        print('\n'.join(str(s) for s in T0.reserved()))
    [code]Code tags[/code] are essential for python code and Makefiles!
  16. #9
  17. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jul 2012
    Posts
    7
    Rep Power
    0
    Sorry just edited my comment managed to get it all working fine,
    Even starting to understand it after digesting it bit by bit,
    So thank you so much for spending the time to help me with this, really appreciate it.
    One final question, is ther a way I can now see the seating plan? Like how you did it in the 2d array? I need a simple visual plan I can develop myself Into a UI

    Thanks
  18. #10
  19. Contributing User
    Devshed Demi-God (4500 - 4999 posts)

    Join Date
    Aug 2011
    Posts
    4,963
    Rep Power
    481
    With this string method in my Auditorium class I can print an auditorium object. "@" precedes reserved seat numbers, a hyphen precedes available seats.

    Note, a command line to run this code, assuming it's on the python path as file p.py, is

    $ python -c 'import p;p.main()'

    Code:
    import math # import at top level before using str(aud)
    
    ....
    
        def __str__(self): # insert into Auditorium class
            format = '%%0%dd'%(1+int(math.log10(self.seats())))
            f = [c+format for c in '@-']
            return '\n'.join(' '.join((f[not s]%s.seatNo) for s in r) for r in self.seatList)
    
    ...
    
        print(T0)  # insert demonstration statement at end of main
    [code]Code tags[/code] are essential for python code and Makefiles!
  20. #11
  21. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jul 2012
    Posts
    7
    Rep Power
    0
    All that seems to do is print what seats are available which is great, I do need that but ATM I wanted to be able to see a 2d array filled with seats such as done before :
    Seat 1. Seat 2, seat 3
    Seat 4. Seat 5, seat 6

    How you made it look before was perfect

    Thank you once again
  22. #12
  23. Contributing User
    Devshed Demi-God (4500 - 4999 posts)

    Join Date
    Aug 2011
    Posts
    4,963
    Rep Power
    481
    Well, no, but you have to look closely. One seat is filled in the middle of the front row and an @ sign precedes it. Obviously I used a ridiculously large (but approximately real) auditorium for an an example.

    If you want the output to include the word "seat" then where the Auditorium __str__ method says
    Code:
            return '\n'.join(' '.join((f[not s]%s.seatNo) for s in r) for r in self.seatList)
    replace for quoted space character the string
    Code:
    '  Seat '
    Now it's your turn to think about programming.
    [code]Code tags[/code] are essential for python code and Makefiles!
  24. #13
  25. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jul 2012
    Posts
    7
    Rep Power
    0
    I many I couldn't see a plan , can't see the ----@
    Thanks for all the help will continue to work at it .
  26. #14
  27. Contributing User
    Devshed Demi-God (4500 - 4999 posts)

    Join Date
    Aug 2011
    Posts
    4,963
    Rep Power
    481
    you probably didn't make all the changes I half indicated.
    Code:
    '''
        $ python -c 'import p;p.main()'
        1500 vacant seats
        1499 vacant seats
        Current reservations for Clemens Center Powers Theater
        25:Michelle
    '''
    
    import math
    
    class Auditorium(object):
    
        def __init__(self,name,rows,columns):
            self.rows = rows
            self.columns = columns
            self.name = name
            a = self.seatList = []
            n = 0
            for count1 in range(rows):
                b = []
                a.append(b)
                for count2 in range(columns):
                    b.append(Seat(n,False, ''))
                    n += 1
    
        def getSeat(self,r,c=None):
            if None is c:
                (r,c,) = self.convert_seat_number_to_row_and_column(r)
            return self.seatList[r][c]
    
        def __str__(self):
            return '%s holds %d rows with %d seats per row'%(
                self.name,self.rows,self.columns)
    
        def convert_seat_number_to_row_and_column(self,n):
            return divmod(n,self.rows)
    
        def reserve(self,seatNo,name,override=False):
            seat = self.getSeat(seatNo)
            if seat and (not override):
                return False
            seat.reserve(name)
            return True
    
        def seats(self):
            return self.rows*self.columns
    
        def vacancies(self):                #****Duplicate code
            return [s for r in self.seatList for s in r if not s]
    
        def reserved(self): #****Duplicate code: with a 3rd similar function
            return [s for r in self.seatList for s in r if s] #****I'd find a general solution
    
        def __str__(self):
            format = '%%0%dd'%(1+int(math.log10(self.seats())))
            f = [c+format for c in '@-']
            return '\n'.join('  Seat '.join((f[not s]%s.seatNo) for s in r) for r in self.seatList)
    
    
    class Seat(object):
    
        def __init__(self, seatNo, res, name):
            self.seatNo = seatNo
            self.res = res                  # Boolean
            self.name = name
    
        def __repr__(self):
            return str(self.seatNo)
    
        def __str__(self):
            if self:
                return '%d:%s'%(self.seatNo,self.name)
            return repr(self)
    
        def __bool__(self):
            return self.res
    
        __nonzero__ = __bool__ # for python2
    
        def reserve(self,name):
            self.name = name
            self.res = True
    
    def main():
        T0 = Auditorium('Clemens Center Powers Theater',30,50)
        T1 = Auditorium('Clemens Center Mandeville Hall',10,20)
        print('%d vacant seats'%len(T0.vacancies()))
        FRONT_AND_CENTER = T0.columns//2
        T0.reserve(FRONT_AND_CENTER,'Michelle',override=True)
        print('%d vacant seats'%len(T0.vacancies()))
        print('Current reservations for %s'%T0.name)
        print('\n'.join(str(s) for s in T0.reserved()))
        print(T0)
    [code]Code tags[/code] are essential for python code and Makefiles!

IMN logo majestic logo threadwatch logo seochat tools logo