Python Forum
Want to print each iteration of factorial program
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Want to print each iteration of factorial program
#9
In the spirit of this being homework, here is code that almost works. Stores in intermediate variable (output) a list of prior values.
The bug for you to fix is that it does not make the final calculation.
def _factorial_sample_(n,output):
    if n == 0 or n == 1:
        output.append(1)
        return n,output
    else:
        x, output = _factorial_sample_(n-1,output)
        new_val = x * output[-1]
        output.append(new_val)
        print(output)
        return n,output
 
 
print(_factorial_sample_(6,[]))
Output:
[1, 1] [1, 1, 2] [1, 1, 2, 6] [1, 1, 2, 6, 24] [1, 1, 2, 6, 24, 120] (6, [1, 1, 2, 6, 24, 120])
Reply


Messages In This Thread
RE: Want to print each iteration of factorial program - by jefsummers - Jan-08-2020, 04:58 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  UnicodeEncodeError caused by print when program runs from Popen SheeppOSU 5 3,220 Jan-13-2022, 08:11 AM
Last Post: SheeppOSU
  Comparing recursion and loops using two scripts (basic factorial) Drone4four 3 2,398 Oct-11-2020, 06:48 PM
Last Post: deanhystad
  Python factorial code timebrahimy 4 89,574 Sep-27-2020, 12:23 AM
Last Post: timebrahimy
  factorial, repeating Aldiyar 4 2,988 Sep-01-2020, 05:22 PM
Last Post: DPaul
  factorial using recursive function spalisetty06 12 4,414 Aug-25-2020, 03:16 PM
Last Post: spalisetty06
  minor mistake in code for factorial spalisetty06 2 2,046 Aug-22-2020, 05:00 PM
Last Post: spalisetty06
  Help with getting sub-program to print text djwilson0495 2 1,997 Aug-16-2020, 05:03 PM
Last Post: deanhystad
  Factorial Code is not working when the given number is very long integer Raj_Kumar 2 2,460 Mar-31-2020, 06:40 PM
Last Post: deanhystad
  Factorial sketch(python 3) KingArthur526 1 2,057 Sep-25-2019, 01:51 PM
Last Post: ichabod801
  Factorial leodavinci1990 8 4,704 Jul-19-2019, 10:59 PM
Last Post: leodavinci1990

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020