[Edu-sig] Python programming challenge

glingl@aon.at glingl at aon.at
Wed Jun 1 16:23:58 CEST 2005


----- Original von:  Kirby Urner <urnerk at qwest.net>:

> 
Here's a good assignment for those wanting to test their Python skills:

Consider the paper and pencil algorithm for finding the square root of a
number as described in detail here, by means of a worked example:

http://www.homeschoolmath.net/other_topics/square-root-algorithm-example.php

Write a Python generator that yields one more digit of the square root of n,
given n as its argument.  Optionally ignore placement of any decimal points.
...

Hi, Kirby, you expect code? Here's a first try - very conventional:

def places(inp):
    while True:
 	if inp:
            i = 2 - len(inp)%2
            yield int(inp[:i])
            inp = inp[i:]
 	else:
 	    yield 0

def root2(inp):
    p=places(inp)
    num = p.next()
    result = 0
    while True:
        digit = 9
        helper = (20*result+digit)*digit
        while helper > num:
            digit -= 1
            helper = (20*result+digit)*digit
        num -= helper
        num = num*100 + p.next()
        result = 10*result + digit
        yield result

Example:

>>> w = root2("3")
>>> for i in range(20):
	print w.next()

1
17
173
1732
17320
173205
1732050
17320508
173205080
1732050807
17320508075
173205080756
1732050807568
17320508075688
173205080756887
1732050807568877
17320508075688772
173205080756887729
1732050807568877293
17320508075688772935
>>> 

Of course I'm interested in alternate solutions.

Regards,
Gregor


P.S.: Hope indenting will not be destroyed by this web-mail-client
I' not using normally



-------------------------------------------
Versendet durch aonWebmail (webmail.aon.at)


More information about the Edu-sig mailing list