Iteration for Factorials

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Roberto Bonvallet

    #31
    Re: Iteration for Factorials

    On Oct 22, 11:45 am, Ant <ant...@gmail.c omwrote:
    Er, no. And neither is mine. You may want to google for the definition
    of factorial!
    Don't google for the definition... google for the answer!

    import urllib
    import re
    urllib.URLopene r.version = "Mozilla/4.0"

    def fact(x):
    r = re.compile(r"%d ! = (\d+)" % x)
    for line in urllib.urlopen( "http://www.google.cl/search?q=%d%%21 "
    % x):
    m = r.search(line)
    if m:
    return int(m.group(1))

    --
    Roberto Bonvallet

    Comment

    • Hendrik van Rooyen

      #32
      Re: Iteration for Factorials

      "Dennis Lee Bieber" <wlfraed@ix.net com.comwrote:
      Heh... the one saving grace of taking a CS major in a period where
      the primary languages taught were FORTRAN (IV), COBOL (74), and
      something close to K&K BASIC. Heck, even the assembler class followed
      the FORTRAN parameter handling scheme (argument addresses copied to
      static locals and used via one level of indirection) -- It would take me
      some time, today, to figure out how to even create a "stack" (even the
      return address was passed via a reserved register and saved locally):
      >
      call,2 sub-address
      data arg1-address
      data arg2-address
      do-something
      .
      .
      .
      sub-address: store,2 my-return
      load,9 *my-return,1 ;indexed access
      store,9 param1
      load,9 *my-return,2
      store,9 param2
      do-stuff
      load,2 my-return
      addimmediate,2 2 ;number of args to
      adjust return
      return,2
      >
      (format:
      label command,registe r argument
      *argument ;indirection
      argument,x ;indexed )
      --
      Yuk. Reminds me of one of the Hitachi processors that
      has a single depth hardware "link register" that tells a
      subroutine where it was called from.

      I was thinking of a stack that grows when you call or push,
      and shrinks when you return or pop.

      When there are only 128 or so bytes, and an address is two bytes,
      recursive calling soon runs into trouble. Especially so if you also
      use the stack to pass params...

      - Hendrik


      Comment

      • Jon Ribbens

        #33
        Re: Iteration for Factorials

        On 2007-10-23, Hendrik van Rooyen <mail@microcorp .co.zawrote:
        Yuk. Reminds me of one of the Hitachi processors that
        has a single depth hardware "link register" that tells a
        subroutine where it was called from.
        That's how ARM processors work, and they're everywhere these days.

        Comment

        • Marco Mariani

          #34
          Re: Iteration for Factorials

          Roberto Bonvallet wrote:
          import urllib
          import re
          urllib.URLopene r.version = "Mozilla/4.0"
          >
          def fact(x):
          r = re.compile(r"%d ! = (\d+)" % x)
          for line in urllib.urlopen( "http://www.google.cl/search?q=%d%%21 " % x):
          m = r.search(line)
          if m:
          return int(m.group(1))

          You solution reminds me the web-based WTF calculator.

          This is the fifth article in a twelve-part series that discusses the twelve finalists and their calculator submissions for the OMGWTF Programming Contest. The entries are being presented in the order submitted, and the winner will be announced on June 18, 2007. All Real Applications these days have a few things in common: a Client/Server Model, a Web 2.0 Interface, and good amount of outsourcing. Entry #100123 - Dave C.'s WTF Web Calc - managed to accomplish that with an impressively minimalistic approach.

          Comment

          • mensanator@aol.com

            #35
            Re: Iteration for Factorials

            On Oct 23, 6:58 am, tokl...@gmail.c om wrote:
            On 22 oct, 23:39, "mensana...@aol .com" <mensana...@aol .comwrote:
            >
            Nope, still doesn't work:
            >
            def fact(x):
            return reduce(operator .mul,xrange(1,x +1),1)
            >
            fact() should raise an exception if x is negative.
            >
            So, where is the problem?
            The fact that it returns 1 for negative x?

            And didn't you see my followup message? About how the
            example, as posted, doesn't even produce correct answers
            for legal values of x?
            if not allowing negative numbers is so
            important for you,
            Mathematical consistency is only important to _me_?
            add a if statement and raise a ValueError exception.
            Not necessary when done correctly. Didn't you see my example?


            Comment

            • mensanator@aol.com

              #36
              Re: Iteration for Factorials

              On Oct 23, 5:55 am, Marco Mariani <ma...@sferacar ta.comwrote:
              Tim Chase wrote:
              >>fact = lambda i: i 1 and reduce(mul, xrange(1, i+1)) or not
              i and 1 or None
              >
              Stunts like this would get a person fired around here if they
              were found in production code :)
              >
              eheh, indeed.
              >
              def fact(n):
              try:
              return eval('*'.join(s tr(x) for x in range(1,n+1)))
              except:
              return 1
              Needs work.

              IDLE 1.2
              >>def fact(n):
              try:
              return eval('*'.join(s tr(x) for x in range(1,n+1)))
              except:
              return 1
              >>fact(3)
              6
              >>fact(2)
              2
              >>fact(1)
              1
              >>fact(0)
              1
              >>fact(-1)
              1
              >>fact(-2)
              1

              Comment

              • Marco Mariani

                #37
                Re: Iteration for Factorials

                mensanator@aol. com wrote:
                Needs work.
                Uh... ok.. this one gives an exception ;-)


                def fact(n):
                try:
                return eval('*'.join(s tr(x) for x in range(1,n+1)))
                except:
                return n>=0 or ValueError



                print fact(-1)
                <type 'exceptions.Val ueError'>

                Comment

                • Hendrik van Rooyen

                  #38
                  Re: Iteration for Factorials

                  "Jon Ribbens" <jon+use...quiv ocal.co.ukwrote :

                  On 2007-10-23, Hendrik van Rooyen <mail@microcorp .co.zawrote:
                  Yuk. Reminds me of one of the Hitachi processors that
                  has a single depth hardware "link register" that tells a
                  subroutine where it was called from.
                  >
                  That's how ARM processors work, and they're everywhere these days.
                  Yes, worse luck. The market has chosen...

                  - Hendrik

                  Comment

                  • Nick Craig-Wood

                    #39
                    Re: Iteration for Factorials

                    Py-Fun <lorna.burns@gm ail.comwrote:
                    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.
                    Here is the math geek answer ;-)

                    import math

                    def factorial(i):
                    n = i + 1
                    return math.exp(-n)*(n**(n-0.5))*math.sqrt (2*math.pi)*(1. + 1./12/n + 1./288/n**2 - 139./51840/n**3)

                    Works for non integer factorials also...

                    See here for background

                    The asymptotic series for the gamma function is given by (1) (OEIS A001163 and A001164). The coefficient a_n of z^(-n) can given explicitly by a_n=sum_(k=1)^(2n)(-1)^k(d_3(2n+2k,k))/(2^(n+k)(n+k)!), (2) where d_3(n,k) is the number of permutations of n with k permutation cycles all of which are >=3 (Comtet 1974, p. 267). Another formula for the a_ns is given by the recurrence relation b_n=1/(n+1)(b_(n-1)-sum_(k=2)^(n-1)kb_kb_(n+1-k)), (3) with b_0=b_1=1, then ...


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

                    Comment

                    • Lou Pecora

                      #40
                      Re: Iteration for Factorials

                      In article <slrnfhvalj.67s .nick@irishsea. home.craig-wood.com>,
                      Nick Craig-Wood <nick@craig-wood.comwrote:
                      Py-Fun <lorna.burns@gm ail.comwrote:
                      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.
                      >
                      Here is the math geek answer ;-)
                      >
                      import math
                      >
                      def factorial(i):
                      n = i + 1
                      return math.exp(-n)*(n**(n-0.5))*math.sqrt (2*math.pi)*(1. + 1./12/n +
                      1./288/n**2 - 139./51840/n**3)
                      >
                      Works for non integer factorials also...
                      >
                      See here for background
                      >
                      http://mathworld.wolfram.com/StirlingsSeries.html

                      Well, that's Sterling's formula. You do have to worry about
                      convergence/accuracy.

                      How about (for intergers - simple-minded version):

                      def factorial(i):
                      fact=1.0
                      for n in xrange(i):
                      fact=n*fact
                      return fact

                      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)

                      Then you could use,

                      arr=arange(i)+1
                      fact=arr.produc t() # or something like that

                      --
                      -- Lou Pecora

                      Comment

                      • mensanator@aol.com

                        #41
                        Re: Iteration for Factorials

                        On Oct 24, 4:05 pm, Lou Pecora <pec...@anvil.n rl.navy.milwrot e:
                        In article <slrnfhvalj.67s .n...@irishsea. home.craig-wood.com>,
                        Nick Craig-Wood <n...@craig-wood.comwrote:
                        >
                        >
                        >
                        >
                        >
                        Py-Fun <lorna.bu...@gm ail.comwrote:
                        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.
                        >
                        Here is the math geek answer ;-)
                        >
                        import math
                        >
                        def factorial(i):
                        n = i + 1
                        return math.exp(-n)*(n**(n-0.5))*math.sqrt (2*math.pi)*(1. + 1./12/n +
                        1./288/n**2 - 139./51840/n**3)
                        >
                        Works for non integer factorials also...
                        >
                        See here for background
                        >>
                        Well, that's Sterling's formula. You do have to worry about
                        convergence/accuracy.
                        >
                        How about (for intergers - simple-minded version):
                        >
                        def factorial(i):
                        fact=1.0
                        for n in xrange(i):
                        fact=n*fact
                        return fact
                        Simple minded indeed.
                        >>factorial(3 )
                        0.0
                        >
                        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)
                        >
                        Then you could use,
                        >
                        arr=arange(i)+1
                        fact=arr.produc t() # or something like that
                        >
                        --
                        -- Lou Pecora- Hide quoted text -
                        >
                        - Show quoted text -

                        Comment

                        • marek.rocki@wp.pl

                          #42
                          Re: Iteration for Factorials

                          Tim Golden napisa (a):
                          It's only a moment before the metaclass and
                          the Twisted solution come along. :)
                          I couldn't resist. It's not as elegant as I hoped, but hey, at least
                          it memoizes the intermediate classes :-)


                          class fact_0(object):
                          value = 1

                          class fact_meta(objec t):
                          def __new__(cls, name, bases, attrs):
                          n = attrs['n']
                          class_name = 'fact_%i' % n
                          try:
                          return globals()[class_name]
                          except KeyError:
                          new_class = type(class_name , bases, {})
                          new_class.value = n * fact(n - 1).value
                          new_class.__str __ = lambda self: str(self.value)
                          globals()[class_name] = new_class
                          return new_class

                          class fact(object):
                          def __new__(self, n_):
                          class spanish_inquisi tion(object):
                          __metaclass__ = fact_meta
                          n = n_
                          return spanish_inquisi tion()

                          print fact(5)
                          print fact(3)
                          print fact(1)

                          Comment

                          • mensanator@aol.com

                            #43
                            Re: Iteration for Factorials

                            On Oct 24, 5:19 pm, marek.ro...@wp. pl wrote:
                            Tim Golden napisa (a):
                            >
                            It's only a moment before the metaclass and
                            the Twisted solution come along. :)
                            >
                            I couldn't resist. It's not as elegant as I hoped, but hey, at least
                            it memoizes the intermediate classes :-)
                            >
                            class fact_0(object):
                            value = 1
                            >
                            class fact_meta(objec t):
                            def __new__(cls, name, bases, attrs):
                            n = attrs['n']
                            class_name = 'fact_%i' % n
                            try:
                            return globals()[class_name]
                            except KeyError:
                            new_class = type(class_name , bases, {})
                            new_class.value = n * fact(n - 1).value
                            new_class.__str __ = lambda self: str(self.value)
                            globals()[class_name] = new_class
                            return new_class
                            >
                            class fact(object):
                            def __new__(self, n_):
                            class spanish_inquisi tion(object):
                            __metaclass__ = fact_meta
                            n = n_
                            return spanish_inquisi tion()
                            >
                            print fact(5)
                            print fact(3)
                            print fact(1)
                            Dare I add fact(0)?

                            120
                            6
                            1
                            <__main__.fact_ 0 object at 0x011729F0>

                            Hmm..not sure what that means, but I bet I can't calculate
                            combinations.

                            What about fact(-1)?

                            120
                            6
                            1
                            <__main__.fact_ 0 object at 0x011729F0>

                            Traceback (most recent call last):
                            File "C:/Program Files/PyGTK/Python/user/yet_another_fac torial.py",
                            line 31, in <module>
                            print fact(-1)
                            File "C:/Program Files/PyGTK/Python/user/yet_another_fac torial.py",
                            line 21, in __new__
                            class spanish_inquisi tion(object):
                            File "C:/Program Files/PyGTK/Python/user/yet_another_fac torial.py",
                            line 13, in __new__
                            new_class.value = n * fact(n - 1).value
                            File "C:/Program Files/PyGTK/Python/user/yet_another_fac torial.py",
                            line 21, in __new__
                            class spanish_inquisi tion(object):
                            File "C:/Program Files/PyGTK/Python/user/yet_another_fac torial.py",
                            line 13, in __new__
                            new_class.value = n * fact(n - 1).value
                            File "C:/Program Files/PyGTK/Python/user/yet_another_fac torial.py",
                            line 21, in __new__
                            class spanish_inquisi tion(object):
                            File "C:/Program Files/PyGTK/Python/user/yet_another_fac torial.py",
                            line 13, in __new__
                            new_class.value = n * fact(n - 1).value
                            File "C:/Program Files/PyGTK/Python/user/yet_another_fac torial.py",
                            line 21, in __new__
                            class spanish_inquisi tion(object):
                            File "C:/Program Files/PyGTK/Python/user/yet_another_fac torial.py",
                            line 13, in __new__
                            new_class.value = n * fact(n - 1).value
                            File "C:/Program Files/PyGTK/Python/user/yet_another_fac torial.py",
                            line 21, in __new__
                            class spanish_inquisi tion(object):
                            File "C:/Program Files/PyGTK/Python/user/yet_another_fac torial.py",
                            line 13, in __new__
                            new_class.value = n * fact(n - 1).value
                            File "C:/Program Files/PyGTK/Python/user/yet_another_fac torial.py",
                            line 21, in __new__
                            class spanish_inquisi tion(object):
                            File "C:/Program Files/PyGTK/Python/user/yet_another_fac torial.py",
                            line 13, i

                            Wow! An infinite loop in the Traceback. Not quite the exception
                            I was looking for.

                            Comment

                            • Paul Rubin

                              #44
                              Re: Iteration for Factorials

                              Lou Pecora <pecora@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))

                              Comment

                              • Paul Rubin

                                #45
                                Re: Iteration for Factorials

                                marek.rocki@wp. pl writes:
                                It's only a moment before the metaclass and
                                the Twisted solution come along. :)
                                >
                                I couldn't resist. It's not as elegant as I hoped, but hey, at least
                                it memoizes the intermediate classes :-)
                                It gets even weirder in Haskell.


                                Comment

                                Working...