case do problem

Peter Otten __peter__ at web.de
Wed Mar 3 03:39:54 EST 2010


Tracubik wrote:

> hi, i've to convert from Pascal this code:

program loop;

function generic_condition: boolean;
begin
   generic_condition := random > 0.7
end;

procedure loop;
var
   iterations, count, m: integer;
begin
   iterations := 0;
   count := 0;
   m := 0;
   repeat
      iterations := iterations+1;
      (*...*)
      writeln(iterations:2, count:2, m:4);
      (*...*)
      if generic_condition then
	    inc(count);
      (*...*)
      case count of
	1: m := 1;
	2: m := 10;
	3: m := 100
      end
   until (count = 4) or (iterations = 20)
end;

begin
   loop;
   writeln("That's all, folks")
end.

Hey, I have a Pascal compiler just one apt-get away ;)

Here's how I'd translate the above, without trying to be too clever:

from random import random

def generic_condition():
    return random() > 0.7

def loop():
    count = 0
    m = 0
    lookup = {1: 1, 2: 10, 3: 100}
    for iterations in range(20): # off by one
        # ...
        print "%2d %1d %3d" % (iterations, count, m)
        # ...
        if generic_condition():
            count += 1
        # ...
        m = lookup.get(count, m)
        if count == 4:
            break

if __name__ == "__main__":
    loop()
    print "That's all, folks"

Something must be wrong with me today because I find the Pascal code /more/ 
readable...

Peter



More information about the Python-list mailing list