Microblog : A very long article Wikipedia article on the orientation of toilet paper [7 jun à 22:52] [R]

Samedi, 21 mars 2009

No for, no if

Traduction: [ Google | Babelfish ]

Catégories : [ Informatique ]

The mission: write a program that iterates over a list and asks the user, on every item, if he wants to change the current number, or quit (and keep the rest of the list unchanged).

Here's a possible python implementation.

def loop(data, index):
  return decide(index == len(data) - 1, 
                lambda: quit(data), 
                lambda: run(data, index+1)
               )
 
def decide(condition, iftrue, iffalse):
  return (iffalse, iftrue)[condition]()
 
def choose(selector, choices, default):
  return choices.get(selector, default)()
 
def change(data, index, new_value):
  data[index] = new_value
  return loop(data, index)
 
def run(data, index):
  print data[index]," Change? [n/q/]",
  reply = raw_input()
  return choose(reply.lower(),
                { 
                  "n": lambda: loop(data, index),
                  "q": lambda: quit(data)
                },
                lambda: decide(reply.isdigit(),
                               lambda: change(data, index, int(reply)),
                               lambda: run(data, index)
                              )
               )
 
def quit(data):
  return data
 
data = range(10)
print run(data, 0)

[ Posté le 21 mars 2009 à 18:09 | 2 commentaires | ]