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

    Join Date
    Jan 2013
    Posts
    76
    Rep Power
    2

    Fast way vs slow way


    Hey, I found a simple piece of code on the web, rewrote it in my own "style" and have abit of trouble with figuring out which version is best in practical use. Both have its advantages/disadvantages.
    It would be great to get input on this, and maybe some of your implementations of it?

    Ps. I found 9 writing mistakes in my code when i wrote it, is this too much? does anyone have any tips on how to improve this?

    the Web's version:
    Code:
    input = 'John,Doe,1984,4,1,male'
    
    tokens = input.split(',')
    firstName = tokens[0]
    lastName = tokens[1]
    birthdate = (int(tokens[2]), int(tokens[3]), int(tokens[4]))
    isMale = (tokens[5] == 'male')
    
    print('Hi ' + firstName + ' ' + lastName)
    My version:
    Code:
    def dCreateInfo(sInput):
        #Creates a temporary list of the credentials
        lsTokens = sInput.split(',')
    
        #Creates the dictionary of a person
        dInfo = {"sFirstName":lsTokens[0],
         "sLastName":lsTokens[1]}
    
        #Adds a bIsMale boolean to the dictionary
        if lsTokens[5].lower() == "male":
            dInfo.update({"bIsMale":True})
        else:
            dInfo.update({bIsMale:False})
            
        #Adds tiBirthDate tuple to the dictionary
        tiBirthDate = int(lsTokens[2]), int(lsTokens[3]), int(lsTokens[4])
        dInfo.update({"tiBirthDate":tiBirthDate})
        
        #Returns the created dictionary
        return(dInfo)
    
    #Creates a dictionary with info based on the string sInput
    sInput = 'John,Doe,1984,4,1,Male'
    dInfo = dCreateInfo(sInput) 
    
    #Prints the message and returns the dictionary
    print('Hi ' + dInfo["sFirstName"] + " " + dInfo["sLastName"])
  2. #2
  3. Contributing User
    Devshed Demi-God (4500 - 4999 posts)

    Join Date
    Aug 2011
    Posts
    4,711
    Rep Power
    480

    correct versus not correct.


    Code:
    # Tested to the extent of Hi John Doe
    # My untested programs are rarely correct.
    
    def dCreateInfo(sInput):
        #Create a temporary list of the credentials
        lsTokens = sInput.split(',')
    
        tiBirthDate = tuple(map(int, lsTokens[2:5]))
    
        #Create and return the dictionary of a person
        return dict(
            sFirstName = lsTokens[0],
            sLastName = lsTokens[1],
            bIsMale = lsTokens[5].lower() == "male", # Boolean
            tiBirthDate = tiBirthDate, # tuple---can't change a birthday!  No rebirth for me.
            )
    
    
    #Creates a dictionary with info based on the string sInput
    sInput = 'John,Doe,1984,4,1,Male'
    dInfo = dCreateInfo(sInput) 
    
    #Prints the message and returns the dictionary
    print('Hi ' + dInfo["sFirstName"] + " " + dInfo["sLastName"])
    Your program does not work because of dInfo.update({bIsMale:False})

    Note that I've been saying all along that we abhor duplicate code, and my version eliminated that duplicate code
    bIsMale = lsTokens[5].lower() == "male", # Boolean

    You tested with a "Male" but not with a "female". Complete testing takes some work!


    Reviewing the various versions visually, I compared my version of your dictionary version to the original version. Clearly the version I prefer is the original version over your revised version.
    Last edited by b49P23TIvg; September 25th, 2013 at 09:49 AM. Reason: Insert title.
    [code]Code tags[/code] are essential for python code and Makefiles!
  4. #3
  5. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jan 2013
    Posts
    76
    Rep Power
    2
    oh, my bad. should have tested it better but didnt have the time because of work.

    your version looks alot better and i like the use of the map function, ive never used it so its not integrated in my brain yet

    I also noticed that i forgot doclines completly, and ofc there would be some unit tests along with this to test the output. You would use doclines in the function in such a function, right?
  6. #4
  7. Contributing User
    Devshed Demi-God (4500 - 4999 posts)

    Join Date
    Aug 2011
    Posts
    4,711
    Rep Power
    480
    Code:
    # python 3 code.  I don't know if annotations are part of the python 2.7 release.
    def dCreateInfo(sInput:str)->dict:
        '''
            To your shell, command   python -m doctest thisfile.py
    	as doing so will run this important doctest.
    
            >>> list(map(dCreateInfo, 'John,Doe,1984,4,1,Male Suzy,Q,1884,8,9,fleemail'.split())) == [{'sFirstName':'John','sLastName':'Doe','bIsMale':True,'tiBirthDate':(1984,4,1)},dict(sFirstName='Suzy',sLastName='Q',bIsMale=False,tiBirthDate=(1884,8,9))]
    	True
        '''
        #Create a temporary list of the credentials
        lsTokens = sInput.split(',')
    
        tiBirthDate = tuple(map(int, lsTokens[2:5]))
    
        #Create and return the dictionary of a person
        return dict(
            sFirstName = lsTokens[0],
            sLastName = lsTokens[1],
            bIsMale = lsTokens[5].lower() == "male", # Boolean
            tiBirthDate = tiBirthDate, # tuple---can't change a birthday!  No rebirth for me.
            )
    [code]Code tags[/code] are essential for python code and Makefiles!
  8. #5
  9. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jan 2013
    Posts
    76
    Rep Power
    2
    waow, you just gave me two more things to investigate further annotations and your way of unit testing. I've actually written a module myself that searches for key characters in doclines and makes unit tests out of them :P
  10. #6
  11. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jan 2013
    Posts
    76
    Rep Power
    2
    Finished I reckon.
    prefer using list comprehension because it's something I'm a bit more familiar with. This should work in both python 2 and 3. I hope it makes an ok example program, it atleast does for me

    Code:
    #!/usr/bin/env python
    # coding=utf-8
    from __future__ import print_function  # For compability with python2
    
    
    def fdCreatePerson(sInput):
        '''Returns a dictionary based on the sInput string provided.'''
    
        #Creates a temporary list of the credentials
        lsTokens = sInput.split(',')
    
        #Returns a dictionary based on the sInput string provided
        return({"sFirstName": lsTokens[0],
                "sLastName": lsTokens[1],
                "tiBirthdate": tuple(int(i) for i in lsTokens[2:5]),
                "bMale": True if lsTokens[5].lower() == "male" else False})
    
    #Creates a dictionary with info based on the string sInput
    dPerson = fdCreatePerson('John,Doe,1984,4,1,Male')
    
    #Prints the message and returns the dictionary
    print('Hi', dPerson["sFirstName"], dPerson["sLastName"])
    
    
    ################################################################################
    #######################The file unittests.py####################################
    ################################################################################
    import unittest
    #import person.py #imports the file we want to test
    
    
    class unittests(unittest.TestCase):
        '''This class will contain all unit tests.'''
        def test_fdCreateAPerson(self):
            #Tests that the function returns a properly formatted dictionary
            dExpectedAnswer = {'sFirstName': 'Leon', 'tiBirthdate': (1984, 10, 4),
                               'sLastName': 'Naley', 'bMale': True}
            dTest = fdCreatePerson('Leon,Naley,1984,10,4,male')
            self.assertEqual(dExpectedAnswer, dTest)
    
            #Tests that the function can handle a big M in male
            dTest = fdCreatePerson('Leon,Naley,1984,10,4,Male')
            self.assertEqual(dExpectedAnswer, dTest)
    
            #Tests that the function can handle a female
            dExpectedAnswer = {'sFirstName': 'Leona', 'tiBirthdate': (1984, 10, 4),
                               'sLastName': 'Naley', 'bMale': False}
            dTest = fdCreatePerson('Leona,Naley,1984,10,4,Female')
            self.assertEqual(dExpectedAnswer, dTest)
    
    unittest.main()

IMN logo majestic logo threadwatch logo seochat tools logo