473,836 Members | 1,452 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 5828
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

Oct 22 '07 #21
to*****@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)

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

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

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


Oct 23 '07 #25
"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

Oct 23 '07 #26
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...

Oct 23 '07 #27
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
Oct 23 '07 #28
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.

Oct 23 '07 #29
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.

Oct 23 '07 #30

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
9816
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10840
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...
0
10546
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10588
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
10254
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...
1
7790
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
5647
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
4448
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
3
3112
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.