Iteration for Factorials

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Py-Fun

    Iteration for Factorials

    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.

  • Diez B. Roggisch

    #2
    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.
    Show us your attempts, and we might suggest a fix. Because otherwise this
    sounds suspiciously like homework.

    Diez

    Comment

    • Py-Fun

      #3
      Re: Iteration for Factorials

      On 22 Oct, 13:28, "Diez B. Roggisch" <de...@nospam.w eb.dewrote:
      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.
      >
      Show us your attempts, and we might suggest a fix. Because otherwise this
      sounds suspiciously like homework.
      >
      Diez
      Here is my futile attempt. Be careful with this though, I just ran
      something similar and it was never ending...

      def itforfact(n):
      while n<100:
      print n
      n+1
      n = input("Please enter a number below 100")

      itforfact(n)

      Comment

      • Marco Mariani

        #4
        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.
        As opposed to what, a complicated one?

        Comment

        • Marco Mariani

          #5
          Re: Iteration for Factorials

          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.

          Comment

          • Duncan Booth

            #6
            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.
            >
            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


            Comment

            • Py-Fun

              #7
              Re: Iteration for Factorials

              On 22 Oct, 13:43, 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.
              Marco, Thanks for the tip. This now works:

              def itforfact(n):
              while n<100:
              print n
              n = n+1
              n = input("Please enter a number below 100")

              itforfact(n)

              Is it a "factorial" though?

              Comment

              • cokofreedom@gmail.com

                #8
                Re: Iteration for Factorials

                On Oct 22, 2: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.
                lambda n: n<=0 or reduce(lambda a,b: long(a)*long(b) ,xrange(1,n+1))


                Comment

                • Amit Khemka

                  #9
                  Re: Iteration for Factorials

                  On 10/22/07, Py-Fun <lorna.burns@gm ail.comwrote:
                  On 22 Oct, 13:28, "Diez B. Roggisch" <de...@nospam.w eb.dewrote:
                  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.
                  Show us your attempts, and we might suggest a fix. Because otherwise this
                  sounds suspiciously like homework.

                  Diez
                  >
                  Here is my futile attempt. Be careful with this though, I just ran
                  something similar and it was never ending...
                  >
                  def itforfact(n):
                  while n<100:
                  print n
                  n+1
                  n = input("Please enter a number below 100")
                  >
                  itforfact(n)
                  Let me give you a pseudo code (which though can be found in most of
                  the textbooks and some 'simple' googling). Try to understand the code
                  and then write an equivalent python function.

                  function iFactorial(n: integer): integer;
                  var i, temp: integer;
                  begin
                  temp = 1;
                  for i = 1 to n do
                  temp = temp * i
                  end
                  return temp

                  About your code.
                  1. why doesn't it surprise you if the code that you posted goes in
                  infinite loop ?!
                  2. why do you use condition: n < 100
                  3. How do you think that your function will calculate the factorial ?
                  4. Instead of "input" use "raw_input" , and then "cast" the input as integer .

                  Cheers,
                  amit.
                  --
                  --
                  Amit Khemka

                  Comment

                  • vimal

                    #10
                    Re: Iteration for Factorials

                    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


                    Comment

                    • Ant

                      #11
                      Re: Iteration for Factorials

                      On Oct 22, 1:26 pm, 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.
                      The following simple adder functions should give you an idea of how
                      recursion can be recast as iteration:

                      def acc(i):
                      '''i should be a positive integer'''
                      if i 0:
                      return i + acc(i - 1)
                      return 0

                      print "acc", acc(9)

                      def itt(i):
                      '''i should be a positive integer'''
                      out = 0

                      while i 0:
                      out += i
                      i = i - 1

                      return out

                      print "itt", itt(9)
                      ...
                      Is it a "factorial" though?
                      Er, no. And neither is mine. You may want to google for the definition
                      of factorial! Here's a hint:

                      reduce(operator .mul, range(1, i + 1))

                      --
                      Anthony Roy


                      Comment

                      • Marco Mariani

                        #12
                        Re: Iteration for Factorials

                        From the cookbook, this time.
                        It satisfies the requirements nicely ;)






                        def tail_recursion( g):
                        '''
                        Version of tail_recursion decorator using no stack-frame
                        inspection.
                        '''
                        loc_vars ={"in_loop":Fal se,"cnt":0}

                        def result(*args, **kwd):
                        loc_vars["cnt"]+=1
                        if not loc_vars["in_loop"]:
                        loc_vars["in_loop"] = True
                        while 1:
                        tc = g(*args,**kwd)
                        try:
                        qual, args, kwd = tc
                        if qual == 'continue':
                        continue
                        except (TypeError, ValueError):
                        loc_vars["in_loop"] = False
                        return tc
                        else:
                        if loc_vars["cnt"]%2==0:
                        return ('continue',arg s, kwd)
                        else:
                        return g(*args,**kwd)
                        return result


                        @tail_recursion
                        def factorial(n, acc=1):
                        "calculate a factorial"
                        if n == 0:
                        return acc
                        res = factorial(n-1, n*acc)
                        return res

                        Comment

                        • Tim Golden

                          #13
                          Re: Iteration for Factorials

                          Marco Mariani wrote:
                          From the cookbook, this time.
                          It satisfies the requirements nicely ;)
                          >
                          >

                          >
                          [... snip the ultimate general-purpose answer to the OP's question ...

                          I really hope that's a wink up there, Marco. The poor guy
                          was just trying to get his homework done!

                          :>

                          TJG

                          Comment

                          • Marco Mariani

                            #14
                            Re: Iteration for Factorials

                            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... more for the "do the least
                            amount of work to meet the requirements" people that for the OP
                            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. 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?

                            Comment

                            • Peter Goodman

                              #15
                              Re: Iteration for Factorials

                              On Oct 22, 8:26 am, 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.
                              def fac_btt(num):
                              total = 1
                              if num 1:
                              for i in range(1, num+1):
                              total *= i
                              return total

                              Comment

                              Working...