473,837 Members | 1,735 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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.

Oct 22 '07
59 5830
Ant
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
Oct 22 '07 #11
From the cookbook, this time.
It satisfies the requirements nicely ;)
http://aspn.activestate.com/ASPN/Coo.../Recipe/496691

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

Oct 22 '07 #12
Marco Mariani 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 poor guy
was just trying to get his homework done!

:>

TJG
Oct 22 '07 #13
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?
Oct 22 '07 #14
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

Oct 22 '07 #15
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

Oct 22 '07 #16
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
Oct 22 '07 #17
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)

Oct 22 '07 #18
"me********@aol .com" <me********@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))
Oct 22 '07 #19
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.

Oct 22 '07 #20

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
1886
by: revhemphill | last post by:
I wrote this program to calculate factorials by recursion, how would I make it nonrecursive and iterative? Thank you to whom ever may be of assistance #include <iostream> using std::cout; using std::endl; #include <iomanip>
0
10899
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
10638
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10280
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9419
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7824
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
7012
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5680
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
4481
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
4058
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.