[Tutor] Sorting numbers

janos.juhasz@VELUX.com janos.juhasz@VELUX.com
Thu Feb 6 03:54:01 2003


What is your opinion about this kind of solution

*****************
import re

class info:
    """ to handle kilobytes and megabyte, or even terras """
    def __init__(self, val):
        val =3D "%s" % val ## convert val to string, if it isn't that
        num =3D re.sub('[\s]', '', "%s" % val) ## remove the non numeri=
c
chars
        num =3D float(num) ## get back the numeric content
        suffix =3D re.sub('[\d.]', '', val) ## remove the numeric chars=

        suffix =3D suffix.upper() ## standardize the suffix
        if re.match('KB', val):
            num =3D num * 1024
        if re.match('MB', val):
            num =3D num * 1024**2
        if re.match('GB', val):
            num =3D num * 1024**3
        if re.match('TB', val):
            num =3D num * 1024**4
        self.val =3D num ## self.val is a number now

    def __str__(self):
        if self.val >=3D 1024**4:
            return "%.3f TB" % (self.val/1024**4)
        if self.val >=3D 1024**3:
            return "%.3f GB" % (self.val/1024**3)
        if self.val >=3D 1024**2:
            return "%.3f MB" % (self.val/1024**2)
        if self.val >=3D 1024:
            return "%.3f KB" % (self.val/1024)
        else:
            return "%.3f B" % self.val


    def __cmp__(self, other):
        self.val.__cmp__(other.val)


*****************

I have no got enough skill to make it work, but it close to working :(
Can someone shape it?

Best regards,
-----------------------
Juh=E1sz J=E1nos
IT department




                                                                       =
                                                            =20
                                 "Jeff Shannon"   To:     tutor@python.=
org                                                         =20
                                 <jeff@ccvcorp.co cc:     Adam Vardy <a=
nvardy@roadrunner.nf.net>                                   =20
                                 m>               bcc:                 =
                                                            =20
                                                  Subject:     Re: [Tut=
or] Sorting numbers                                         =20
                                 Sent by:                              =
                                                            =20
                                 tutor-admin@pyth                      =
                                                            =20
                                 on.org                                =
                                                            =20
                                                                       =
                                                            =20
                                                                       =
                                                            =20
                                 02/05/2003 18:36                      =
                                                            =20
                                                                       =
                                                            =20
                                                                       =
                                                            =20






Adam Vardy wrote:

>Tuesday, February 4, 2003, 4:27:01 PM, you wrote:
>
>>> >>> rawdata
>>>['45K', '100K', '3.4Meg', '17K', '300K', '9.3Meg', '512', '23Meg']
>>> >>> srt =3D {}
>>> >>> for item in rawdata:
>>>...     num, suffix =3D splitsuffix(item)
>>>...     value =3D srt.get(suffix, [])
>>>...     value.append(num)
>>>...     srt[suffix] =3D value
>>>
>>>
>
>Can you explain the last three lines here?
>
>

Sure.  First let's look at the line 'value =3D srt.get(suffix, [])'.  W=
e
have a dictionary called srt, and we want to see if it has anything in
the key that's held in suffix.  I could've said 'value =3D srt[suffix]'=
,
and then value would contain whatever had previously been stored in the=

dictionary with that key, but what happens if nothing had been
previously stored?

 >>> srt =3D {}
 >>> value =3D srt['Meg']
Traceback (most recent call last):
  File "<interactive input>", line 1, in ?
KeyError: Meg
 >>>

We get an exception.  Now, since I'm starting with an empty dictionary,=

I know that I'm going to try looking up nonexistent keys at least a few=

times.  I *could* use a try/except block, and respond to the exception,=

but there's an easier way.  Dictionaries have a convenient get() method=
,
which will look up a key like normal, but if that key is not found then=

it will return a default value.

 >>> value =3D srt.get('Meg', [])
 >>> value
[]
 >>> value =3D srt.get('Meg', [])
 >>> value
['2.4', '9.6']
 >>>

This basically asks the dictionary, "Give me whatever you've got for
'Meg', but if you don't have anything, then give me an empty list inste=
ad."

Now 'value' is a list containing whatever had been previously been
stored in the dictionary with that suffix -- or an empty list if nothin=
g
had been stored previously.  The next line, 'value.append(num)', tacks
the current numeric value onto the end of that list.  Finally, the last=

line 'srt[suffix] =3D value' takes the modified list and stores that li=
st
back in the dictionary, under the same key as before.

The overall effect of these three lines, then, is that the list that th=
e
dictionary has stored under a given suffix has the current value of num=

tacked on the end, with new lists being created as necessary when new
suffixes are found.  As the original list of raw data is iterated
through, it's sorted into a series of lists depending on what the
non-numeric suffix on the string is.  Eventually, all of the items that=

had ended in 'Meg' are stored in srt['Meg'], all of the numbers that ha=
d
ended in 'K' are stored in srt['K'], and so on.

Hope that helps.  If there's anything else you're not clear on, feel
free to ask.

Jeff Shannon
Technician/Programmer
Credit International





_______________________________________________
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor



=