Python Programming
 
Forums: » Register « |  User CP |  Games |  Calendar |  Members |  FAQs |  Sitemap |  Support | 
User Name:
Password:
Remember me

The Shed is going Social! Join us on FaceBook and Twitter and chime in on the conversation.

Go Back   Dev Shed ForumsProgramming LanguagesPython Programming

Reply
Add This Thread To:
  Del.icio.us   Digg   Google   Spurl   Blink   Furl   Simpy   Y! MyWeb 
Thread Tools Search this Thread Rate Thread Display Modes
 
Unread Dev Shed Forums Sponsor:
  #1  
Old January 1st, 2013, 07:38 PM
MickeyCoder MickeyCoder is offline
Registered User
Dev Shed Newbie (0 - 499 posts)
 
Join Date: Jan 2013
Posts: 2 MickeyCoder User rank is Just a Lowly Private (1 - 20 Reputation Level) 
Time spent in forums: 21 m 4 sec
Reputation Power: 0
Working program but review required to make it better

Hi All,

I just started learning Python using online resources and am just a couple of days old in it. I have quite a good experience in Java though (10+ years) and Python caught my fancy during the Christmas holidays as had nothing better to do

I wrote a quick and dirty code to compute factorial of a number using Python and I need an expert's opinion about it with respect to the structure and semantics - is there something that can be more optimized in it, something that was done incorrectly etc. Am interested to learn the language right the first time, and will immensely appreciate any feedback.

The idea of code is simple - being a recursive algorithm, I've tried to cache all previously computed values of factorial in a file which is cached when an object of FactCache is created. Factorial then uses the cache to reduce recursion.

Code follows:

Code:
import os
import pickle
"""
Caches and pickles factorial of a number.
Upon instantiation, sarches for the file 'fact.cache'
in the current directory or in the path passed during
construction. If not found then creates the file there.
If found then unpickles it and creates the dictionary
with pre-calculated factorial values.
"""
class FactCache:
    c = {}
    def __init__(self,path="./fact.cache"):
        self.path=path
        try:
            if(os.path.isfile(self.path)):
                print("Cache file found. Reading it now...")
                with open(self.path,'rb') as readCache:
                    self.c = pickle.load(readCache)
            else:
                print("File not found. Creating it now...")
                with open(self.path,'wb') as writeCache:
                    pickle.dump(self.c,writeCache)
        except IOError as err:
            print("Oops! Factorial cache not loaded!",str(err))
            pass
        finally:
            print(self.c)

    """
    Stores the value (f) of the factorial for a number (n) in the file.
    """
    def add(self,n,f):
        self.c[n]=f
        with open(self.path,'wb') as writeCache:
            pickle.dump(self.c,writeCache)    

    """
    Returns the value of the factorial for a number (n) from the dictionary.
    """
    def get(self,n):
        if n in self.c:
            return self.c[n]
        else:
            return -1

"""
Computes factorial of a given number and
reuses all previous results to reduce recursion.
"""
def factorial(n,c):
    f = c.get(n)
    if(f == -1):
        if(n==0):
            return 1
        else:
            v = n*factorial(n-1,c)
            c.add(n,v)
            return v
    else:
        print("Value served from cache for ",n)
        return f


Output follows:
>>> factorial(26,c)
Value served from cache for 25
403291461126605635584000000

Reply With Quote
  #2  
Old January 1st, 2013, 08:57 PM
b49P23TIvg's Avatar
b49P23TIvg b49P23TIvg is offline
Contributing User
Dev Shed Loyal (3000 - 3499 posts)
 
Join Date: Aug 2011
Posts: 3,458 b49P23TIvg User rank is Major (30000 - 40000 Reputation Level)b49P23TIvg User rank is Major (30000 - 40000 Reputation Level)b49P23TIvg User rank is Major (30000 - 40000 Reputation Level)b49P23TIvg User rank is Major (30000 - 40000 Reputation Level)b49P23TIvg User rank is Major (30000 - 40000 Reputation Level)b49P23TIvg User rank is Major (30000 - 40000 Reputation Level)b49P23TIvg User rank is Major (30000 - 40000 Reputation Level)b49P23TIvg User rank is Major (30000 - 40000 Reputation Level)b49P23TIvg User rank is Major (30000 - 40000 Reputation Level)b49P23TIvg User rank is Major (30000 - 40000 Reputation Level) 
Time spent in forums: 1 Month 2 Weeks 4 Days 6 h 26 m 43 sec
Reputation Power: 403
Wonderful.

Next write a decorator to hide the cache argument.
__________________
[code]Code tags[/code] are essential for python code!

Reply With Quote
  #3  
Old January 2nd, 2013, 06:04 AM
SuperOscar SuperOscar is offline
Contributing User
Dev Shed Newbie (0 - 499 posts)
 
Join Date: Jul 2007
Location: Joensuu, Finland
Posts: 412 SuperOscar User rank is Second Lieutenant (5000 - 10000 Reputation Level)SuperOscar User rank is Second Lieutenant (5000 - 10000 Reputation Level)SuperOscar User rank is Second Lieutenant (5000 - 10000 Reputation Level)SuperOscar User rank is Second Lieutenant (5000 - 10000 Reputation Level)SuperOscar User rank is Second Lieutenant (5000 - 10000 Reputation Level)SuperOscar User rank is Second Lieutenant (5000 - 10000 Reputation Level)SuperOscar User rank is Second Lieutenant (5000 - 10000 Reputation Level) 
Time spent in forums: 1 Week 7 h 13 m 32 sec
Reputation Power: 65
Quote:
Originally Posted by MickeyCoder
Am interested to learn the language right the first time, and will immensely appreciate any feedback.


Docstrings should go below the thing they document, not (as in Ruby) above. Also, PEP 257 recommends that the first line is followed by a blank line. I.e.:

Code:
def spam(eggs):
    '''Add spam to my eggs.

    A more detailed explanation follows here.
    '''
__________________
My armada: openSUSE 12.3 (home desktop, laptop, work desktop), Ubuntu 12.04 LTS (mini laptop), Debian GNU/Linux 7.0 (server), Mythbuntu 12.04 LTS (HTPC), Bodhi Linux 2.0 & Windows 7 Ultimate (test desktop), FreeBSD 9.1 (test server)

Reply With Quote
  #4  
Old January 2nd, 2013, 12:29 PM
Dietrich's Avatar
Dietrich Dietrich is offline
Contributing User
Dev Shed Newbie (0 - 499 posts)
 
Join Date: Feb 2005
Posts: 498 Dietrich User rank is Second Lieutenant (5000 - 10000 Reputation Level)Dietrich User rank is Second Lieutenant (5000 - 10000 Reputation Level)Dietrich User rank is Second Lieutenant (5000 - 10000 Reputation Level)Dietrich User rank is Second Lieutenant (5000 - 10000 Reputation Level)Dietrich User rank is Second Lieutenant (5000 - 10000 Reputation Level)Dietrich User rank is Second Lieutenant (5000 - 10000 Reputation Level)Dietrich User rank is Second Lieutenant (5000 - 10000 Reputation Level) 
Time spent in forums: 4 Days 3 h 4 m 11 sec
Reputation Power: 63
You can also access a properly located documentation string this way:
Code:
''' DocumentationString1.py
documentation strings must be added right below the function definition,
triple quotes are recommended as a standard
can be accessed via function_name.__doc__
'''

def get_distance(x1, y1, x2, y2):
    """
    get_distance(x1, y1, x2, y2)
    returns distance between two points using the pythagorean theorem
    the function parameters are the coordinates of the two points
    """
    dx = x2 - x1
    dy = y2 - y1
    return (dx**2 + dy**2)**0.5

#
# since the indentation rules relax between triple quotes
# you can also use this to avoid adding spaces in front of 
# the doc string
#

def get_distance2(x1, y1, x2, y2):
    """
get_distance(x1, y1, x2, y2)
returns distance between two points using the pythagorean theorem
the function parameters are the coordinates of the two points
    """
    dx = x2 - x1
    dy = y2 - y1
    return (dx**2 + dy**2)**0.5

print( "The function's documentation string:" )
# shows text between the triple quotes
print(get_distance.__doc__)
print("\nWithout leading spaces:")
print(get_distance2.__doc__)

''' my result >>>
The function's documentation string:

    get_distance(x1, y1, x2, y2)
    returns distance between two points using the pythagorean theorem
    the function parameters are the coordinates of the two points
    

Without leading spaces:

get_distance(x1, y1, x2, y2)
returns distance between two points using the pythagorean theorem
the function parameters are the coordinates of the two points
'''
__________________
Real Programmers always confuse Christmas and Halloween because Oct31 == Dec25

Reply With Quote
  #5  
Old January 2nd, 2013, 04:12 PM
MickeyCoder MickeyCoder is offline
Registered User
Dev Shed Newbie (0 - 499 posts)
 
Join Date: Jan 2013
Posts: 2 MickeyCoder User rank is Just a Lowly Private (1 - 20 Reputation Level) 
Time spent in forums: 21 m 4 sec
Reputation Power: 0
Thanks!

Thank you all for your feedback. @b49P23TIvg: The decorators are very interesting and thanks for pointing me in that direction!

Reply With Quote
  #6  
Old January 2nd, 2013, 04:58 PM
Dietrich's Avatar
Dietrich Dietrich is offline
Contributing User
Dev Shed Newbie (0 - 499 posts)
 
Join Date: Feb 2005
Posts: 498 Dietrich User rank is Second Lieutenant (5000 - 10000 Reputation Level)Dietrich User rank is Second Lieutenant (5000 - 10000 Reputation Level)Dietrich User rank is Second Lieutenant (5000 - 10000 Reputation Level)Dietrich User rank is Second Lieutenant (5000 - 10000 Reputation Level)Dietrich User rank is Second Lieutenant (5000 - 10000 Reputation Level)Dietrich User rank is Second Lieutenant (5000 - 10000 Reputation Level)Dietrich User rank is Second Lieutenant (5000 - 10000 Reputation Level) 
Time spent in forums: 4 Days 3 h 4 m 11 sec
Reputation Power: 63
A decorator would be a little overkill since it would only be useful for that particular function.

Reply With Quote
Reply

Viewing: Dev Shed ForumsProgramming LanguagesPython Programming > Working program but review required to make it better

Developer Shed Advertisers and Affiliates



Thread Tools  Search this Thread 
Search this Thread:

Advanced Search
Display Modes  Rate This Thread 
Rate This Thread:


Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

vB code is On
Smilies are On
[IMG] code is On
HTML code is Off
View Your Warnings | New Posts | Latest News | Latest Threads | Shoutbox
Forum Jump

Forums: » Register « |  User CP |  Games |  Calendar |  Members |  FAQs |  Sitemap |  Support | 
  
 


Powered by: vBulletin Version 3.0.5
Copyright ©2000 - 2013, Jelsoft Enterprises Ltd.

© 2003-2013 by Developer Shed. All rights reserved. DS Cluster - Follow our Sitemap