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

    Join Date
    Oct 2013
    Posts
    3
    Rep Power
    0

    Angry Object oriented HELP?!?!


    I'm having problems trying to get this to sort correctly. The program has to use classes, and I can't use any built in functions except len [] and [:]. It has to work for chr and int. This is what I have so far.

    class SortedList:
    def __init__(self):
    self.L = [1,2,5,7,12]
    def __insert__(self,item):
    for i in self.L:
    if i >= item:
    M = self.L[:i-1] + [item]
    print(M)
    break

    any suggestions?
  2. #2
  3. Contributing User
    Devshed Demi-God (4500 - 4999 posts)

    Join Date
    Aug 2011
    Posts
    4,706
    Rep Power
    480
    This post has three sections. In the first I complain about the dearth of knowledge your instructor displays. Next I shred what little code you wrote. Finally, I improve your program. Then again, luck may strike; I'll instead get bored and watch supercomputers play each other at FICS, the free internet chess server.

    Just what does "may not use any built in functions" mean?

    Let's examine the object 0 in python2. You'll see that it has the
    __cmp__ method. How are you going to avoid comparisons????

    (In python3 cmp is gone, replaced with explicit __lt__, __le__, __eq__, __ne__, __ge__, __gt__ methods. Does not help, you still need some of these methods.)

    >>> dir(0)
    ['__abs__', '__add__', '__and__', '__class__', '__cmp__', '__coerce__', '__delattr__', '__div__', '__divmod__', '__doc__', '__float__', '__floordiv__', '__format__', '__getattribute__', '__getnewargs__', '__hash__', '__hex__', '__index__', '__init__', '__int__', '__invert__', '__long__', '__lshift__', '__mod__', '__mul__', '__neg__', '__new__', '__nonzero__', '__oct__', '__or__', '__pos__', '__pow__', '__radd__', '__rand__', '__rdiv__', '__rdivmod__', '__reduce__', '__reduce_ex__', '__repr__', '__rfloordiv__', '__rlshift__', '__rmod__', '__rmul__', '__ror__', '__rpow__', '__rrshift__', '__rshift__', '__rsub__', '__rtruediv__', '__rxor__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__truediv__', '__trunc__', '__xor__', 'bit_length', 'conjugate', 'denominator', 'imag', 'numerator', 'real']


    OK. You're permitted "methods" but not "functions". So just use the sort method of lists. As in:
    Code:
    '''
        These doctests  pass.
        $ python3 -ic 'import p;L=p.SortedList("bca")'
        >>> # doctest.  Run with command line     python3 -m doctest -v thisfile.py
        >>> L = SortedList('bca')
        >>> L
        ['a', 'b', 'c']
        >>> L.extend('the')
        >>> L
        ['a', 'b', 'c', 'e', 'h', 't']
        >>> L.append('blort')
        >>> L
        ['a', 'b', 'blort', 'c', 'e', 'h', 't']
        >>> 
    '''
    
    
    # uses the super of python 3
    
    class SortedList(list):
    
        def __init__(self,iterable):
            super().__init__(iterable)
            self.sort()
    
        def insert(self,index,item):
            self.append(item)
    
        def append(self,item):
            super().append(item)
            self.sort()
    
        def extend(self, iterable):
            super().extend(iterable)
            self.sort()
    I suppose "That's not what the professor meant!!!" Leaving us to fix your program while pretending your instructor knows something. Ugh.


    How much of list functionality are you supposed to duplicate?
    Code:
    '''
        These doctests fail!  Fix the program.
        $ python3 -ic 'import p;L=p.SortedList("bca")'
        >>> # doctest.  Run with command line     python3 -m doctest -v thisfile.py
        >>> L = SortedList('bca')
        >>> L
        ['a', 'b', 'c']
        >>> L.extend('the')
        >>> L
        ['a', 'b', 'c', 'e', 'h', 't']
        >>> L.append('blort')
        >>> L
        ['a', 'b', 'blort', 'c', 'e', 'h', 't']
        >>> 
    '''
    
    class SortedList:
    
        def __init__(self, initial = None):
            self.L = [1,2,5,7,12] # why???  This isn't going to work with str in python 3 because python 3 won't compare str with numeric types.
                 #$ python3
                 #Python 3.3.1 (default, Sep 25 2013, 19:29:01) 
                 #[GCC 4.7.3] on linux
                 #Type "help", "copyright", "credits" or "license" for more information.
                 #>>> 'a'<43
                 #Traceback (most recent call last):
                 #  File "<stdin>", line 1, in <module>
                 #TypeError: unorderable types: str() < int()
                 #>>> 
    
            self.L = []
            if initial:
                self.extend(initial)
    
        ###def __insert__(self,item):  # From where do you get the concept __insert__ ???  use dir([]) or help([]) in the interp
    reter to learn something.
        def insert(self, item):  # no underscores.
            for i in self.L:  #you're really confused.  Here the variable i references each object of the list in turn.
                if i >= item:  # you correctly use i comparing the objects that are meant to be compared.
                    M = self.L[:i-1] + [item]  #@!!!!!!!  WOW!  Now you use i as if it were an index into the list.
                    ###### By here you knew everything is broken and didn't bother or know that having discarded the tail end of the list is...WRONG
                    print(M)
                    break
    But first a quick interlude. You often want
    for item in iterable:

    And you often think you want
    for index_variable in range(len(LIST)):

    Usually what you need is both the index and object. Python gives this to us with enumerate.
    for (index_variable, item,) in enumerate(LIST):
    Last edited by b49P23TIvg; October 31st, 2013 at 08:57 PM. Reason: insert part 2, shred the tiny code contribution.
    [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
    Oct 2013
    Posts
    3
    Rep Power
    0
    You have to use recursion. You can only use [ ] [:] and +. And it has to work for strings, sorted alphabetically, integers, and real numbers.
  6. #4
  7. Contributing User
    Devshed Demi-God (4500 - 4999 posts)

    Join Date
    Aug 2011
    Posts
    4,706
    Rep Power
    480
    I have to use recursion?? I think not. This is a good method to use:

    bisect.insort_left(a, x, lo=0, hi=len(a))


    bye.
    [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
    Oct 2013
    Posts
    3
    Rep Power
    0
    Haha Yeh, my professor is nuts n it isn't efficient at all, but I have to use recursion thanks anyway

IMN logo majestic logo threadwatch logo seochat tools logo