Iteration for Factorials

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Lou Pecora

    #46
    Re: Iteration for Factorials

    In article <1193261568.712 027.234520@e9g2 000prf.googlegr oups.com>,
    "mensanator@aol .com" <mensanator@aol .comwrote:
    def factorial(i):
    fact=1.0
    for n in xrange(i):
    fact=n*fact
    return fact
    >
    Simple minded indeed.
    >
    >factorial(3)
    0.0
    >
    Whoops, should have xrange(i)+1 there. Or, better, xrange(2,n+1). Save a
    multiplication. Just trying to show the OP the scheme for iteration
    here.

    --
    -- Lou Pecora

    Comment

    • Marco Mariani

      #47
      Re: Iteration for Factorials

      marek.rocki@wp. pl wrote:
      class fact_0(object):
      value = 1
      [...
      def __new__(self, n_):
      class spanish_inquisi tion(object):
      __metaclass__ = fact_meta
      n = n_
      return spanish_inquisi tion()

      You wrote lots of boilerplate to hide the fact you're cheating, didn't you?

      The OP explicitly asked for an iterative procedure.

      btw... writing a test unit to check the tested code is not calling
      itself.. could be interesting

      Comment

      • Nicko

        #48
        Re: Iteration for Factorials

        On Oct 25, 2:36 am, Paul Rubin <http://phr...@NOSPAM.i nvalidwrote:
        Lou Pecora <pec...@anvil.n rl.navy.milwrit es:
        There might even be an array method that can be adapted to get the
        product. Is there a product method? (analogous to a sum method)
        >
        The "reduce" function which is being removed from python in 3.0.
        >
        import operator
        def factorial(n):
        return reduce(operator .mul, xrange(1,n+1))
        Since reduce is being removed, and Guido is known not to like its use
        anyway, I propose the following code for Py2.5 and later:

        import math
        def fact(n):
        return math.exp(sum((m ath.log(i) for i in range(1,n+1)))) if n
        >= 0 else None
        If you don't like the rounding errors you could try:

        def fact(n):
        d = {"p":1L}
        def f(i): d["p"] *= i
        map(f, range(1,n+1))
        return d["p"]

        It is left as an exercise to the reader as to why this code will not
        work on Py3K

        Nicko


        Comment

        • Steven Bethard

          #49
          Re: Iteration for Factorials

          Nicko wrote:
          If you don't like the rounding errors you could try:
          >
          def fact(n):
          d = {"p":1L}
          def f(i): d["p"] *= i
          map(f, range(1,n+1))
          return d["p"]
          >
          It is left as an exercise to the reader as to why this code will not
          work on Py3K
          Serves you right for abusing map(). ;-)

          STeVe

          Comment

          • Anurag

            #50
            Re: Iteration for Factorials

            What about this no map, reduce, mutiplication or even addition
            Its truly interative and You will need to interate till infinity if
            you want correct answer ;)

            def factorial(N):
            """
            Increase I ...and go on increasing...
            """
            import random

            myNumer = range(N)
            count = 0
            I = 10000 #10**(N+1)
            for i in range(I):
            bucket = range(N)
            number = []
            for i in range(N):
            k = bucket[ random.randrang e(0,len(bucket) )]
            bucket.remove(k )
            number.append(k )

            if number == myNumer:
            count+=1

            return int(I*1.0/count+.5)

            Comment

            • Nick Craig-Wood

              #51
              Re: Iteration for Factorials

              Anurag <anuraguniyal@g mail.comwrote:
              What about this no map, reduce, mutiplication or even addition
              Its truly interative and You will need to interate till infinity if
              you want correct answer ;)
              >
              def factorial(N):
              """
              Increase I ...and go on increasing...
              """
              import random
              >
              myNumer = range(N)
              count = 0
              I = 10000 #10**(N+1)
              for i in range(I):
              bucket = range(N)
              number = []
              for i in range(N):
              k = bucket[ random.randrang e(0,len(bucket) )]
              bucket.remove(k )
              number.append(k )
              >
              if number == myNumer:
              count+=1
              >
              return int(I*1.0/count+.5)
              ;-)

              Note you can write your middle loop as

              for i in range(I):
              number = myNumer[:]
              random.shuffle( number)
              if number == myNumer:
              count+=1


              --
              Nick Craig-Wood <nick@craig-wood.com-- http://www.craig-wood.com/nick

              Comment

              • Marco Mariani

                #52
                Re: Iteration for Factorials

                Nick Craig-Wood wrote:
                Note you can write your middle loop as
                >
                for i in range(I):
                number = myNumer[:]
                random.shuffle( number)
                if number == myNumer:
                count+=1
                Nice. Try 'em all, then count 'em.

                Another wtfery would be a SQLAlchemy solution, generating dynamic
                queries, using only OUTER JOINs and COUNT(). Could be a way to justify
                hardware upgrades.


                Comment

                • Boris Borcic

                  #53
                  Re: Iteration for Factorials

                  Py-Fun wrote:
                  I'm stuck trying to write a function that generates a factorial of a
                  number using iteration and not recursion. Any simple ideas would be
                  appreciated.
                  >
                  fact = lambda n : len(map([1].__imul__,range (1,n+1))[0])

                  hth :)

                  BB

                  Comment

                  • auzaar@gmail.com

                    #54
                    Re: Iteration for Factorials

                    On Oct 30, 3:30 pm, Nick Craig-Wood <n...@craig-wood.comwrote:
                    Anurag <anuraguni...@g mail.comwrote:
                    What about this no map, reduce, mutiplication or even addition
                    Its truly interative and You will need to interate till infinity if
                    you want correct answer ;)
                    >
                    deffactorial(N) :
                    """
                    Increase I ...and go on increasing...
                    """
                    import random
                    >
                    myNumer = range(N)
                    count = 0
                    I = 10000 #10**(N+1)
                    for i in range(I):
                    bucket = range(N)
                    number = []
                    for i in range(N):
                    k = bucket[ random.randrang e(0,len(bucket) )]
                    bucket.remove(k )
                    number.append(k )
                    >
                    if number == myNumer:
                    count+=1
                    >
                    return int(I*1.0/count+.5)
                    >
                    ;-)
                    >
                    Note you can write your middle loop as
                    >
                    for i in range(I):
                    number = myNumer[:]
                    random.shuffle( number)
                    if number == myNumer:
                    count+=1
                    >
                    --
                    Nick Craig-Wood <n...@craig-wood.com--http://www.craig-wood.com/nick- Hide quoted text -
                    >
                    - Show quoted text -
                    good :) i thinkif go on improving this we will have worlds' best
                    useless factorial function.

                    actually number = myNumer[:] can be moved out of the loop.

                    Comment

                    • J. Clifford Dyer

                      #55
                      Re: Iteration for Factorials

                      On Tue, Oct 30, 2007 at 01:09:38PM +0100, Boris Borcic wrote regarding Re: Iteration for Factorials:
                      >
                      Py-Fun wrote:
                      I'm stuck trying to write a function that generates a factorial of a
                      number using iteration and not recursion. Any simple ideas would be
                      appreciated.
                      >
                      fact = lambda n : len(map([1].__imul__,range (1,n+1))[0])
                      >
                      hth :)
                      >
                      Nice one. I was trying to grok it, and started out by breaking it down:
                      >>[1].__imul__(2)
                      [1, 1]
                      >>map([1].__imul__,range (1,3))
                      [[1, 1], [1, 1]]

                      So far so good, but I tried to break it down a little more:
                      >>[1].__imul__(1), [1].__imul__(2), [1].__imul__(3)
                      ([1], [1, 1], [1, 1, 1])

                      Hmm. Wasn't what I was expecting.

                      Then it hit me:
                      >>L = [1]
                      >>L.__imul__(1) , L.__imul__(2), L.__imul__(3)
                      ([1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1])

                      Pretty sneaky, sis.

                      Cheers,
                      Cliff

                      P.S. Regards to those who lack a grounding in American pop-culture, or who are to young to remember the origins of "Pretty sneaky, sis."

                      Comment

                      • J. Clifford Dyer

                        #56
                        Re: Iteration for Factorials

                        On Tue, Oct 30, 2007 at 01:09:38PM +0100, Boris Borcic wrote regarding Re: Iteration for Factorials:
                        >
                        Py-Fun wrote:
                        I'm stuck trying to write a function that generates a factorial of a
                        number using iteration and not recursion. Any simple ideas would be
                        appreciated.
                        >
                        fact = lambda n : len(map([1].__imul__,range (1,n+1))[0])
                        >
                        OK. Now I've been sucked in. How about this:

                        def fact(x):
                        def f(x):
                        if int(x) != x:
                        raise ValueError
                        elif x 1:
                        return f(x-1) ** x
                        elif x == 1:
                        return 10
                        else:
                        raise ValueError
                        return len(str(f(x))) -1

                        The great part about this recursive solution is that you don't have to worry about the stack limit because performance degrades so quickly on the conversion to string! fact(8) takes a little less than a second, fact(9) takes about a minute, and fact(10) takes more time than I had patience to wait for!

                        Cheers,
                        Cliff

                        Comment

                        • mensanator@aol.com

                          #57
                          Re: Iteration for Factorials

                          On Oct 30, 10:25 am, "J. Clifford Dyer" <j...@sdf.lones tar.orgwrote:
                          On Tue, Oct 30, 2007 at 01:09:38PM +0100, Boris Borcic wrote regarding Re: Iteration for Factorials:
                          >
                          >
                          >
                          Py-Fun wrote:
                          I'm stuck trying to write a function that generates a factorial of a
                          number using iteration and not recursion. Any simple ideas would be
                          appreciated.
                          >
                          fact = lambda n : len(map([1].__imul__,range (1,n+1))[0])
                          >
                          OK. Now I've been sucked in. How about this:
                          >
                          def fact(x):
                          def f(x):
                          if int(x) != x:
                          raise ValueError
                          elif x 1:
                          return f(x-1) ** x
                          elif x == 1:
                          return 10
                          else:
                          raise ValueError
                          return len(str(f(x))) -1
                          >
                          The great part about this recursive solution is that you don't have to worry about the stack limit because performance degrades so quickly on the conversion to string! fact(8) takes a little less than a second, fact(9) takes about a minute, and fact(10) takes more time than I had patience to wait for!
                          And the not-so-great part is that it raises an exception
                          on fact(0) which makes it utterly useless for calculating
                          combinations of m things taken n at a time: m!/n!*(m-n)!

                          Why is it that no one seems able to get this right?
                          >
                          Cheers,
                          Cliff

                          Comment

                          • J. Clifford Dyer

                            #58
                            Re: Iteration for Factorials

                            On Tue, Oct 30, 2007 at 11:37:57AM -0700, mensanator@aol. com wrote regarding Re: Iteration for Factorials:
                            >
                            On Oct 30, 10:25 am, "J. Clifford Dyer" <j...@sdf.lones tar.orgwrote:
                            On Tue, Oct 30, 2007 at 01:09:38PM +0100, Boris Borcic wrote regarding Re: Iteration for Factorials:


                            Py-Fun wrote:
                            I'm stuck trying to write a function that generates a factorial of a
                            number using iteration and not recursion. Any simple ideas would be
                            appreciated.
                            fact = lambda n : len(map([1].__imul__,range (1,n+1))[0])
                            OK. Now I've been sucked in. How about this:

                            def fact(x):
                            def f(x):
                            if int(x) != x:
                            raise ValueError
                            elif x 1:
                            return f(x-1) ** x
                            elif x == 1:
                            return 10
                            else:
                            raise ValueError
                            return len(str(f(x))) -1

                            The great part about this recursive solution is that you don't have to worry about the stack limit because performance degrades so quickly on the conversion to string! fact(8) takes a little less than a second, fact(9) takes about a minute, and fact(10) takes more time than I had patience to wait for!
                            >
                            And the not-so-great part is that it raises an exception
                            on fact(0) which makes it utterly useless for calculating
                            combinations of m things taken n at a time: m!/n!*(m-n)!
                            >
                            Why is it that no one seems able to get this right?
                            >
                            I can't speak for everyone, but my excuses are as follows:

                            * I haven't studied math or done math-heavy work in 8 years.
                            * I'm not at my home computer, and most of the thread (wherein, I now recall, that particular rule was specified) is downloaded to my home computer, so I was working from my feeble memory.
                            * I didn't care enough to google for it.

                            That said, s/elif x == 1:/elif x in (0,1):/ should solve the problem

                            Comment

                            • mensanator@aol.com

                              #59
                              Re: Iteration for Factorials

                              On Oct 30, 1:52 pm, "J. Clifford Dyer" <j...@sdf.lones tar.orgwrote:
                              On Tue, Oct 30, 2007 at 11:37:57AM -0700, mensana...@aol. com wrote regarding Re: Iteration for Factorials:
                              >
                              >
                              >
                              >
                              >
                              >
                              >
                              On Oct 30, 10:25 am, "J. Clifford Dyer" <j...@sdf.lones tar.orgwrote:
                              On Tue, Oct 30, 2007 at 01:09:38PM +0100, Boris Borcic wrote regarding Re: Iteration for Factorials:
                              >
                              Py-Fun wrote:
                              I'm stuck trying to write a function that generates a factorial of a
                              number using iteration and not recursion. Any simple ideas would be
                              appreciated.
                              >
                              fact = lambda n : len(map([1].__imul__,range (1,n+1))[0])
                              >
                              OK. Now I've been sucked in. How about this:
                              >
                              def fact(x):
                              def f(x):
                              if int(x) != x:
                              raise ValueError
                              elif x 1:
                              return f(x-1) ** x
                              elif x == 1:
                              return 10
                              else:
                              raise ValueError
                              return len(str(f(x))) -1
                              >
                              The great part about this recursive solution is that you don't have to worry about the stack limit because performance degrades so quickly on the conversion to string! fact(8) takes a little less than a second, fact(9) takes about a minute, and fact(10) takes more time than I had patience to wait for!
                              >
                              And the not-so-great part is that it raises an exception
                              on fact(0) which makes it utterly useless for calculating
                              combinations of m things taken n at a time: m!/n!*(m-n)!
                              >
                              Why is it that no one seems able to get this right?
                              >
                              I can't speak for everyone, but my excuses are as follows:
                              >
                              * I haven't studied math or done math-heavy work in 8 years.
                              Fair enough. I primarily do math-heavy work, and am familiar
                              with such matters. But that's just me.
                              * I'm not at my home computer, and most of the thread (wherein,
                              I now recall, that particular rule was specified) is downloaded
                              to my home computer, so I was working from my feeble memory.
                              Well, I've only had to point it out a dozen times already in
                              this thread. Nice to see that all that effort has been for nought.
                              * I didn't care enough to google for it.
                              Quoting from Monty Python:
                              "It's just as easy to get these things right, you know."
                              >
                              That said, s/elif x == 1:/elif x in (0,1):/ should solve the problem
                              Sure, it's always easily solvable. I just hope someone learns the
                              lesson on how to test properly, to make sure things work the way
                              they should and to fail the way they should so that one can actually
                              trust the algorithms they write.

                              Comment

                              • Gabriel Genellina

                                #60
                                Re: Iteration for Factorials

                                En Tue, 30 Oct 2007 15:37:57 -0300, mensanator@aol. com
                                <mensanator@aol .comescribió:
                                On Oct 30, 10:25 am, "J. Clifford Dyer" <j...@sdf.lones tar.orgwrote:
                                >The great part about this recursive solution is that you don't have to
                                >worry about the stack limit because performance degrades so quickly on
                                >the conversion to string! fact(8) takes a little less than a second,
                                >fact(9) takes about a minute, and fact(10) takes more time than I had
                                >patience to wait for!
                                >
                                And the not-so-great part is that it raises an exception
                                on fact(0) which makes it utterly useless for calculating
                                combinations of m things taken n at a time: m!/n!*(m-n)!
                                >
                                Why is it that no one seems able to get this right?
                                Uhmmm... don't be so serious, most of those recipes are a joke :)
                                Who cares about fact(0) when fact(10) can't be computed...? At least,
                                that's how I see it, Nimo dixit.

                                --
                                Gabriel Genellina

                                Comment

                                Working...