[Tutor] Anyone fancy giving me some tips and an expert opinion??
Ricardo Aráoz
ricaraoz at gmail.com
Sat Feb 9 13:53:13 CET 2008
Damian Archer wrote:
> I have written what i see as a pretty decent script to resolve this
> question:
>
> Write an improved version of the Chaos program from Chapter 1 that
> allows a user to input two initial
> values and the number of iterations and then prints a nicely formatted
> table showing how the values
> change over time. For example, if the starting values were .25 and .26
> with 10 iterations, the table
> might look like this:
> index 0.25 0.26
> ----------------------------
> 1 0.731250 0.750360
> 2 0.766441 0.730547
> 3 0.698135 0.767707
> 4 0.821896 0.695499
> 5 0.570894 0.825942
> 6 0.955399 0.560671
> 7 0.166187 0.960644
> 8 0.540418 0.147447
> 9 0.968629 0.490255
> 10 0.118509 0.974630
>
> Although it works I am sure I could have gone about this a better way,
> it probably doesn't fit all the rules of best practice either. Was
> wondering if anyone would mind having a look and offering a few tips??
>
> # chaos.py
> # A program to mimic the chaos theory
>
> def main():
>
> print "Example of Chaos"
>
> # User inputs numbers to compare, z is for the index counter
> x = input("Enter a number between 1 and 0: ")
> y = input("Enter a second number between 1 and 0: ")
> z = 0
>
> # Prints the table borders and titles
> print '%10s %20s %20s' % ("Index", x, y)
> print "-----------------------------
> -----------------------------"
> tempx = x
> tempy = y
>
> # Loops calculates 'chaotic behaviour for input numbers
> for i in range(10):
> tempx = 3.9 * tempx * (1 - tempx)
> tempy = 3.9 * tempy * (1 - tempy)
> z = z + 1
> # Print chaotice results into table
> print '%10s %20s %20s' % (z, tempx, tempy)
>
> raw_input("Press any key to exit")
>
> main()
>
>From a procedural POV,
UNTESTED :
# chaos.py
# A program to mimic the chaos theory
def main() :
print "Example of Chaos"
x, y, iterations = getUserInput()
printTitles(x, y)
for i in range(1, iterations+1)
print '%10s %20s %20s' % (i, chaos(x), chaos(y))
raw_input("Press any key to exit")
def printTitles(x, y) :
# Prints the table borders and titles
print '%10s %20s %20s' % ("Index", x, y)
print "----------------------------------------------------------"
def getUserInput() :
# Should put this inside a try/except block
x = float(raw_input("Enter a number between 1 and 0: "))
y = float(raw_input("Enter a second number between 1 and 0: "))
iterations = float(raw_input("Enter a number of iterations: "))
return x, y, iterations
def chaos(x) :
return (3.9 * x * (1 - x))
if __name__ == '__main__' :
main()
More information about the Tutor
mailing list