Iteration for Factorials

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Paul McGuire

    #16
    Re: Iteration for Factorials

    On Oct 22, 8:02 am, vimal <cool.vimalsm.. .@gmail.comwrot e:
    On Oct 22, 5:43 pm, Marco Mariani <ma...@sferacar ta.comwrote:
    >
    Py-Fun wrote:
    def itforfact(n):
    while n<100:
    print n
    n+1
    n = input("Please enter a number below 100")
    >
    You function should probably return something. After that, you can see
    what happens with the result you get.
    >
    i am just suggesting u an idea
    but i dont know it satisfies ur needs
    >
    x=10
    def cal_range(10)
    for i in range(10):
    print 2**i
    Maybe a little math refresher would be good for those trying to post
    suggestions.

    "Factorial of N" means "the product of 1 x 2 x 3 x ... x N", and is
    shown symbolically as "N!".

    (Factorial is only defined for nonnegative numbers, and for reasons
    that go beyond this little note, just know that 0! = 1.)

    In Python, a fully expanded factorial for values >= 1 would be:

    2! = 1 * 2
    5! = 1 * 2 * 3 * 4 * 5
    8! = 1 * 2 * 3 * 4 * 5 * 6 * 7 * 8

    Here is an example routine showing iteration, that prints these
    expressions:


    def print_factorial (n):
    print str(n)+"! =",
    print "1",
    t = 2
    while t <= n:
    print "*",t,
    t += 1
    print

    Perhaps this example will give you some ideas on how to approach your
    problem.


    -- Paul

    Comment

    • Tim Golden

      #17
      Re: Iteration for Factorials

      Marco Mariani wrote:
      Tim Golden wrote:
      >
      >> From the cookbook, this time.
      >>It satisfies the requirements nicely ;)
      >>>
      >>http://aspn.activestate.com/ASPN/Coo.../Recipe/496691
      >[... snip the ultimate general-purpose answer to the OP's question ...
      >>
      >I really hope that's a wink up there, Marco.
      >
      The wink is in the second line of my post...
      I did see it :)
      >The poor guy was just trying to get his homework done!
      >
      I don't see how my answer is in any way worse than those based on
      lambda.
      Nor do I. I was just joking with a colleague that the guy
      just wanted a bit of help (which he did get, in fact from
      several sources) and then out came the lambda and the
      decorator. It's only a moment before the metaclass and
      the Twisted solution come along. :)
      (It's like watching a convention of lisp programmers --
      ducks, runs for cover)

      TJG

      Comment

      • mensanator@aol.com

        #18
        Re: Iteration for Factorials

        On Oct 22, 7:50 am, Duncan Booth <duncan.bo...@i nvalid.invalidw rote:
        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.
        >
        This version avoids doing anything fancier than adding 1, so it should be
        simple enough for anyone:
        >
        def factorial(e):
        a = 1
        for b in range(e):
        c = 0
        for j in range(b, -1, -1):
        for d in range(a):
        c += 1
        a = c
        return a
        Not simple enough for my taste:
        >>import gmpy
        >>gmpy.fac(10 )
        mpz(3628800)

        Comment

        • Paul Rudin

          #19
          Re: Iteration for Factorials

          "mensanator@aol .com" <mensanator@aol .comwrites:
          On Oct 22, 7:50 am, Duncan Booth <duncan.bo...@i nvalid.invalidw rote:
          >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.
          >>
          >This version avoids doing anything fancier than adding 1, so it should be
          >simple enough for anyone:
          >>
          >def factorial(e):
          > a = 1
          > for b in range(e):
          > c = 0
          > for j in range(b, -1, -1):
          > for d in range(a):
          > c += 1
          > a = c
          > return a
          >
          Not simple enough for my taste:
          >
          >>>import gmpy
          >>>gmpy.fac(1 0)
          mpz(3628800)
          I haven't followed all this thread, but has anyone yet done:

          import operator
          def fact(x):
          return reduce(operator .mul, xrange(1,x))

          Comment

          • mensanator@aol.com

            #20
            Re: Iteration for Factorials

            On Oct 22, 1:35 pm, Paul Rudin <paul.nos...@ru din.co.ukwrote:
            "mensana...@aol .com" <mensana...@aol .comwrites:
            On Oct 22, 7:50 am, Duncan Booth <duncan.bo...@i nvalid.invalidw rote:
            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.
            >
            This version avoids doing anything fancier than adding 1, so it should be
            simple enough for anyone:
            >
            def factorial(e):
            a = 1
            for b in range(e):
            c = 0
            for j in range(b, -1, -1):
            for d in range(a):
            c += 1
            a = c
            return a
            >
            Not simple enough for my taste:
            >
            >>import gmpy
            >>gmpy.fac(10 )
            mpz(3628800)
            >
            I haven't followed all this thread, but has anyone yet done:
            >
            import operator
            def fact(x):
            return reduce(operator .mul, xrange(1,x))
            I hope not.
            >>import operator
            >>def fact(x):
            return reduce(operator .mul,xrange(1,x ))
            >>fact(3)
            2
            >>fact(2)
            1
            >>fact(1)
            Traceback (most recent call last):
            File "<pyshell#1 0>", line 1, in <module>
            fact(1)
            File "<pyshell#7 >", line 2, in fact
            return reduce(operator .mul,xrange(1,x ))
            TypeError: reduce() of empty sequence with no initial value
            >>fact(0)
            Traceback (most recent call last):
            File "<pyshell#1 1>", line 1, in <module>
            fact(0)
            File "<pyshell#7 >", line 2, in fact
            return reduce(operator .mul,xrange(1,x ))
            TypeError: reduce() of empty sequence with no initial value

            I think you need to make it a bit more complicated.

            Comment

            • tokland@gmail.com

              #21
              Re: Iteration for Factorials

              On 22 oct, 20:35, Paul Rudin <paul.nos...@ru din.co.ukwrote:
              import operator
              def fact(x):
              return reduce(operator .mul, xrange(1,x))
              Maybe:

              import operator
              def fact(x):
              return reduce(operator .mul, xrange(2, x+1), 1)

              fact(0)
              1
              fact(4)
              24

              Comment

              • Paul Rudin

                #22
                Re: Iteration for Factorials

                tokland@gmail.c om writes:
                On 22 oct, 20:35, Paul Rudin <paul.nos...@ru din.co.ukwrote:
                >
                >import operator
                >def fact(x):
                > return reduce(operator .mul, xrange(1,x))
                >
                Maybe:
                >
                import operator
                def fact(x):
                return reduce(operator .mul, xrange(2, x+1), 1)
                Or just:

                reduce(operator .mul, xrange(1, x), 1)



                Comment

                • mensanator@aol.com

                  #23
                  Re: Iteration for Factorials

                  On Oct 22, 3:38 pm, Paul Rudin <paul.nos...@ru din.co.ukwrote:
                  tokl...@gmail.c om writes:
                  On 22 oct, 20:35, Paul Rudin <paul.nos...@ru din.co.ukwrote:
                  >
                  import operator
                  def fact(x):
                  return reduce(operator .mul, xrange(1,x))
                  >
                  Maybe:
                  >
                  import operator
                  def fact(x):
                  return reduce(operator .mul, xrange(2, x+1), 1)
                  >
                  Or just:
                  >
                  reduce(operator .mul, xrange(1, x), 1)
                  Nope, still doesn't work:
                  >>def fact(x):
                  return reduce(operator .mul,xrange(1,x +1),1)
                  >>fact(3)
                  6
                  >>fact(2)
                  2
                  >>fact(1)
                  1
                  >>fact(0)
                  1
                  >>fact(-1)
                  1
                  >>fact(-2)
                  1
                  >>fact(-3)
                  1

                  fact() should raise an exception if x is negative.

                  My variant of your original (same as Tim Chase's except the
                  test for x==1 is not necessary):
                  >>def fact(x):
                  if x==0:
                  return 1
                  else:
                  return reduce(operator .mul,xrange(1,x +1))
                  >>fact(3)
                  6
                  >>fact(2)
                  2
                  >>fact(1)
                  1
                  >>fact(0)
                  1
                  >>fact(-1)
                  Traceback (most recent call last):
                  File "<pyshell#4 0>", line 1, in <module>
                  fact(-1)
                  File "<pyshell#3 5>", line 5, in fact
                  return reduce(operator .mul,xrange(1,x +1))
                  TypeError: reduce() of empty sequence with no initial value

                  Comment

                  • mensanator@aol.com

                    #24
                    Re: Iteration for Factorials

                    On Oct 22, 4:39 pm, "mensana...@aol .com" <mensana...@aol .comwrote:
                    On Oct 22, 3:38 pm, Paul Rudin <paul.nos...@ru din.co.ukwrote:
                    >
                    >
                    >
                    >
                    >
                    tokl...@gmail.c om writes:
                    On 22 oct, 20:35, Paul Rudin <paul.nos...@ru din.co.ukwrote:
                    >
                    >import operator
                    >def fact(x):
                    > return reduce(operator .mul, xrange(1,x))
                    >
                    Maybe:
                    >
                    import operator
                    def fact(x):
                    return reduce(operator .mul, xrange(2, x+1), 1)
                    >
                    Or just:
                    >
                    reduce(operator .mul, xrange(1, x), 1)
                    >
                    Nope, still doesn't work:
                    >
                    >def fact(x):
                    >
                    return reduce(operator .mul,xrange(1,x +1),1)
                    Excuse me, I mistyped your proposed solution. You had
                    xrange(1,x) not xrange(1,x+1). The former only returns
                    correct factorials for x==0 and x==1.

                    Sorry for the confusion.
                    >
                    >fact(3)
                    6
                    >fact(2)
                    2
                    >fact(1)
                    1
                    >fact(0)
                    1
                    >fact(-1)
                    1
                    >fact(-2)
                    1
                    >fact(-3)
                    >
                    1
                    >
                    fact() should raise an exception if x is negative.
                    >
                    My variant of your original (same as Tim Chase's except the
                    test for x==1 is not necessary):
                    >
                    >def fact(x):
                    >
                    if x==0:
                    return 1
                    else:
                    return reduce(operator .mul,xrange(1,x +1))
                    >
                    >
                    >
                    >fact(3)
                    6
                    >fact(2)
                    2
                    >fact(1)
                    1
                    >fact(0)
                    1
                    >fact(-1)
                    >
                    Traceback (most recent call last):
                    File "<pyshell#4 0>", line 1, in <module>
                    fact(-1)
                    File "<pyshell#3 5>", line 5, in fact
                    return reduce(operator .mul,xrange(1,x +1))
                    TypeError: reduce() of empty sequence with no initial value- Hide quoted text -
                    >
                    - Show quoted text -

                    Comment

                    • Tim Chase

                      #25
                      Re: Iteration for Factorials

                      Still, why do you want None instead of raisng an exception
                      (as is the case in other factorial implementations )?
                      A null value is as good/bad as raising an exception in my book.
                      Since you can't do math on a None object, any attempt to do so
                      will raise an exception:
                      >>42 + fact(-1)
                      I generally prefer my functions to return semi-sensible results
                      (in this case, None makes sense to me, as there isn't really a
                      definition of "negative-one factorial"). It also fits in my head
                      alongside my SQL where NULL values/expressions can be returned
                      and evaluated without the whole query falling over.

                      I suppose if you really wanted to throw an exception using this
                      lambda craziness, you could wrap the whole result in "0 +
                      ([body])" which, if the body returned Null, would push up
                      exception daisies (with slightly misleading exception information).

                      -tkc




                      Comment

                      • Hendrik van Rooyen

                        #26
                        Re: Iteration for Factorials

                        "Marco Mariani" <marc....arta.c omwrote:

                        I don't see how my answer is in any way worse than those based on
                        lambda. Maybe I'm just envious because when I was his age I couldn't
                        google for answers. He should at least be able to do that, shouldn't he?
                        But wait. That would mean understanding what a factorial is. That would
                        require a second search, or a textbook, or an understanding of
                        arithmetics before programming with or without recursion. Should we
                        blame the teachers?
                        Yes. And burn their cars to get their attention!

                        Asking someone to write a factorial algorithm before he knows WTF a
                        factorial "is", is either insane, or the ultimate demonstration of deliberate
                        lack of cooperation and coordination between departments.
                        I feel kind of strongly about this ever since, as a student, the physics people
                        expected me to use mathematics that I had not been taught yet...

                        ;-)

                        I shall try to refrain from commenting on the concept of introducing
                        recursion into a first course in CS - I am too much tainted by my ability
                        to mentally "see" the stack growth in a small processor to be qualified
                        to comment.

                        - Hendrik

                        Comment

                        • cokofreedom@gmail.com

                          #27
                          Re: Iteration for Factorials

                          On Oct 23, 8:53 am, "Hendrik van Rooyen" <m...@microcorp .co.zawrote:
                          "Marco Mariani" <marc....arta.c omwrote:
                          >
                          I don't see how my answer is in any way worse than those based on
                          lambda. Maybe I'm just envious because when I was his age I couldn't
                          google for answers. He should at least be able to do that, shouldn't he?
                          But wait. That would mean understanding what a factorial is. That would
                          require a second search, or a textbook, or an understanding of
                          arithmetics before programming with or without recursion. Should we
                          blame the teachers?
                          >
                          Yes. And burn their cars to get their attention!
                          >
                          Asking someone to write a factorial algorithm before he knows WTF a
                          factorial "is", is either insane, or the ultimate demonstration of deliberate
                          lack of cooperation and coordination between departments.
                          I feel kind of strongly about this ever since, as a student, the physics people
                          expected me to use mathematics that I had not been taught yet...
                          >
                          ;-)
                          >
                          I shall try to refrain from commenting on the concept of introducing
                          recursion into a first course in CS - I am too much tainted by my ability
                          to mentally "see" the stack growth in a small processor to be qualified
                          to comment.
                          >
                          - Hendrik
                          Completely agree with this point of view. After being on the receiving
                          end of such problems when first introduced to Haskell and told to look
                          at a database written in it and work my way through it (without having
                          started the course on databases, locks, or any of that jargon) you
                          find yourself almost helpless at times.

                          Hard to google for something you don't know about.

                          Recursive calling is a fun, and yet painful, thing...

                          Comment

                          • Marco Mariani

                            #28
                            Re: Iteration for Factorials

                            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

                            Comment

                            • tokland@gmail.com

                              #29
                              Re: Iteration for Factorials

                              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? if not allowing negative numbers is so
                              important for you, add a if statement and raise a ValueError exception.

                              Comment

                              • cokofreedom@gmail.com

                                #30
                                Re: Iteration for Factorials

                                On Oct 23, 1:58 pm, 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? if not allowing negative numbers is so
                                important for you, add a if statement and raise a ValueError exception.
                                indeed, especially considering that fact(x) is essentially just a
                                lambda statement as Marco Mariani said.

                                Comment

                                Working...