473,836 Members | 1,438 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 5827
Anurag <an**********@g mail.comwrote:
What about this no map, reduce, mutiplication or even addition
Its truly interative and You will need to interate till infinity if
you want correct answer ;)

def factorial(N):
"""
Increase I ...and go on increasing...
"""
import random

myNumer = range(N)
count = 0
I = 10000 #10**(N+1)
for i in range(I):
bucket = range(N)
number = []
for i in range(N):
k = bucket[ random.randrang e(0,len(bucket) )]
bucket.remove(k )
number.append(k )

if number == myNumer:
count+=1

return int(I*1.0/count+.5)
;-)

Note you can write your middle loop as

for i in range(I):
number = myNumer[:]
random.shuffle( number)
if number == myNumer:
count+=1
--
Nick Craig-Wood <ni**@craig-wood.com-- http://www.craig-wood.com/nick
Oct 30 '07 #51
Nick Craig-Wood wrote:
Note you can write your middle loop as

for i in range(I):
number = myNumer[:]
random.shuffle( number)
if number == myNumer:
count+=1
Nice. Try 'em all, then count 'em.

Another wtfery would be a SQLAlchemy solution, generating dynamic
queries, using only OUTER JOINs and COUNT(). Could be a way to justify
hardware upgrades.
Oct 30 '07 #52
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.
fact = lambda n : len(map([1].__imul__,range (1,n+1))[0])

hth :)

BB
Oct 30 '07 #53
On Oct 30, 3:30 pm, Nick Craig-Wood <n...@craig-wood.comwrote:
Anurag <anuraguni...@g mail.comwrote:
What about this no map, reduce, mutiplication or even addition
Its truly interative and You will need to interate till infinity if
you want correct answer ;)
deffactorial(N) :
"""
Increase I ...and go on increasing...
"""
import random
myNumer = range(N)
count = 0
I = 10000 #10**(N+1)
for i in range(I):
bucket = range(N)
number = []
for i in range(N):
k = bucket[ random.randrang e(0,len(bucket) )]
bucket.remove(k )
number.append(k )
if number == myNumer:
count+=1
return int(I*1.0/count+.5)

;-)

Note you can write your middle loop as

for i in range(I):
number = myNumer[:]
random.shuffle( number)
if number == myNumer:
count+=1

--
Nick Craig-Wood <n...@craig-wood.com--http://www.craig-wood.com/nick- Hide quoted text -

- Show quoted text -
good :) i thinkif go on improving this we will have worlds' best
useless factorial function.

actually number = myNumer[:] can be moved out of the loop.

Oct 30 '07 #54
On Tue, Oct 30, 2007 at 01:09:38PM +0100, Boris Borcic wrote regarding 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.

fact = lambda n : len(map([1].__imul__,range (1,n+1))[0])

hth :)
Nice one. I was trying to grok it, and started out by breaking it down:
>>[1].__imul__(2)
[1, 1]
>>map([1].__imul__,range (1,3))
[[1, 1], [1, 1]]

So far so good, but I tried to break it down a little more:
>>[1].__imul__(1), [1].__imul__(2), [1].__imul__(3)
([1], [1, 1], [1, 1, 1])

Hmm. Wasn't what I was expecting.

Then it hit me:
>>L = [1]
L.__imul__(1) , L.__imul__(2), L.__imul__(3)
([1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1])

Pretty sneaky, sis.

Cheers,
Cliff

P.S. Regards to those who lack a grounding in American pop-culture, or who are to young to remember the origins of "Pretty sneaky, sis."
Oct 30 '07 #55
On Tue, Oct 30, 2007 at 01:09:38PM +0100, Boris Borcic wrote regarding 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.

fact = lambda n : len(map([1].__imul__,range (1,n+1))[0])
OK. Now I've been sucked in. How about this:

def fact(x):
def f(x):
if int(x) != x:
raise ValueError
elif x 1:
return f(x-1) ** x
elif x == 1:
return 10
else:
raise ValueError
return len(str(f(x))) -1

The great part about this recursive solution is that you don't have to worry about the stack limit because performance degrades so quickly on the conversion to string! fact(8) takes a little less than a second, fact(9) takes about a minute, and fact(10) takes more time than I had patience to wait for!

Cheers,
Cliff

Oct 30 '07 #56
On Oct 30, 10:25 am, "J. Clifford Dyer" <j...@sdf.lones tar.orgwrote:
On Tue, Oct 30, 2007 at 01:09:38PM +0100, Boris Borcic wrote regarding 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.
fact = lambda n : len(map([1].__imul__,range (1,n+1))[0])

OK. Now I've been sucked in. How about this:

def fact(x):
def f(x):
if int(x) != x:
raise ValueError
elif x 1:
return f(x-1) ** x
elif x == 1:
return 10
else:
raise ValueError
return len(str(f(x))) -1

The great part about this recursive solution is that you don't have to worry about the stack limit because performance degrades so quickly on the conversion to string! fact(8) takes a little less than a second, fact(9) takes about a minute, and fact(10) takes more time than I had patience to wait for!
And the not-so-great part is that it raises an exception
on fact(0) which makes it utterly useless for calculating
combinations of m things taken n at a time: m!/n!*(m-n)!

Why is it that no one seems able to get this right?
>
Cheers,
Cliff

Oct 30 '07 #57
On Tue, Oct 30, 2007 at 11:37:57AM -0700, me********@aol. com wrote regarding Re: Iteration for Factorials:
>
On Oct 30, 10:25 am, "J. Clifford Dyer" <j...@sdf.lones tar.orgwrote:
On Tue, Oct 30, 2007 at 01:09:38PM +0100, Boris Borcic wrote regarding 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.
fact = lambda n : len(map([1].__imul__,range (1,n+1))[0])
OK. Now I've been sucked in. How about this:

def fact(x):
def f(x):
if int(x) != x:
raise ValueError
elif x 1:
return f(x-1) ** x
elif x == 1:
return 10
else:
raise ValueError
return len(str(f(x))) -1

The great part about this recursive solution is that you don't have to worry about the stack limit because performance degrades so quickly on the conversion to string! fact(8) takes a little less than a second, fact(9) takes about a minute, and fact(10) takes more time than I had patience to wait for!

And the not-so-great part is that it raises an exception
on fact(0) which makes it utterly useless for calculating
combinations of m things taken n at a time: m!/n!*(m-n)!

Why is it that no one seems able to get this right?
I can't speak for everyone, but my excuses are as follows:

* I haven't studied math or done math-heavy work in 8 years.
* I'm not at my home computer, and most of the thread (wherein, I now recall, that particular rule was specified) is downloaded to my home computer, so I was working from my feeble memory.
* I didn't care enough to google for it.

That said, s/elif x == 1:/elif x in (0,1):/ should solve the problem
Oct 30 '07 #58
On Oct 30, 1:52 pm, "J. Clifford Dyer" <j...@sdf.lones tar.orgwrote:
On Tue, Oct 30, 2007 at 11:37:57AM -0700, mensana...@aol. com wrote regarding Re: Iteration for Factorials:


On Oct 30, 10:25 am, "J. Clifford Dyer" <j...@sdf.lones tar.orgwrote:
On Tue, Oct 30, 2007 at 01:09:38PM +0100, Boris Borcic wrote regarding 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.
fact = lambda n : len(map([1].__imul__,range (1,n+1))[0])
OK. Now I've been sucked in. How about this:
def fact(x):
def f(x):
if int(x) != x:
raise ValueError
elif x 1:
return f(x-1) ** x
elif x == 1:
return 10
else:
raise ValueError
return len(str(f(x))) -1
The great part about this recursive solution is that you don't have to worry about the stack limit because performance degrades so quickly on the conversion to string! fact(8) takes a little less than a second, fact(9) takes about a minute, and fact(10) takes more time than I had patience to wait for!
And the not-so-great part is that it raises an exception
on fact(0) which makes it utterly useless for calculating
combinations of m things taken n at a time: m!/n!*(m-n)!
Why is it that no one seems able to get this right?

I can't speak for everyone, but my excuses are as follows:

* I haven't studied math or done math-heavy work in 8 years.
Fair enough. I primarily do math-heavy work, and am familiar
with such matters. But that's just me.
* I'm not at my home computer, and most of the thread (wherein,
I now recall, that particular rule was specified) is downloaded
to my home computer, so I was working from my feeble memory.
Well, I've only had to point it out a dozen times already in
this thread. Nice to see that all that effort has been for nought.
* I didn't care enough to google for it.
Quoting from Monty Python:
"It's just as easy to get these things right, you know."
>
That said, s/elif x == 1:/elif x in (0,1):/ should solve the problem
Sure, it's always easily solvable. I just hope someone learns the
lesson on how to test properly, to make sure things work the way
they should and to fail the way they should so that one can actually
trust the algorithms they write.

Oct 30 '07 #59
En Tue, 30 Oct 2007 15:37:57 -0300, me********@aol. com
<me********@aol .comescribió:
On Oct 30, 10:25 am, "J. Clifford Dyer" <j...@sdf.lones tar.orgwrote:
>The great part about this recursive solution is that you don't have to
worry about the stack limit because performance degrades so quickly on
the conversion to string! fact(8) takes a little less than a second,
fact(9) takes about a minute, and fact(10) takes more time than I had
patience to wait for!

And the not-so-great part is that it raises an exception
on fact(0) which makes it utterly useless for calculating
combinations of m things taken n at a time: m!/n!*(m-n)!

Why is it that no one seems able to get this right?
Uhmmm... don't be so serious, most of those recipes are a joke :)
Who cares about fact(0) when fact(10) can't be computed...? At least,
that's how I see it, Nimo dixit.

--
Gabriel Genellina

Oct 31 '07 #60

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
9665
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
1
10585
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
10249
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
7785
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
6976
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
5645
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...
0
5818
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
4007
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3108
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.