[Tutor] help with random.randint (cont. -- now: pseudo code)

bob gailer bgailer at gmail.com
Wed Feb 3 08:46:59 CET 2010


David wrote:

[snip]


My suggestion (untested):

MAX = 12
NQ = 20 # of questions to ask

# create a 2 dimensional array of 1's
row = [1]*MAX
pool = [row[:] for i in range(MAX)]

incorrect = [] # store incorrectly answered combos here

def askQuestions():  # generate and ask questions:
  for i in range(NQ):
    while 1: # loop till we get an unused combo
      x, y = [random.randint(1,MAX) for i in 'ab']
      if mtable[x][y] == 1: # combo is available
        break
    askQuestion(x,y)
    # indicate asked
    mtable[x][y] = 0
    mtable[y][x] = 0
  showStats()

def askQuestion(x,y):
  solution = x*y
  # take answer from user
  ok =  user answer == solution
  if ok:
    correct += 1
  else:
    incorrect.append((x,y))
  return ok

def askFaultyAnswers():
  answer = raw_input("Try again the incorrect questions? (y/n) ")
  if answer == "y":
    correct = 0
    for x,y in incorrect:
      ok = askQuestion(x,y)
      # could use ok to remove combo from incorrect list.
  showStats()

askQuestions()
askFaultyAnswers()
print "good-bye!"

>
>
> </CODE>
>
> I think it is sensible to
>
> * first create all possible solutions, then
> * kick out doublettes, and only then
> * ask questions
>
> I have some questions though:
>
> Is the overall structure and flow of this program okay? What are the 
> main problems you can spot immediately

Calculating kicking randomizing is overkill. My code uses a 2 dimension 
array to track which x,y combos are available.

break is only valid within a loop.

Recursively calling askQuestions is not a good idea. Save recursion for 
when it is is meaningful. Use a loop instead.

There is no need for an incorrect counter. we can calculate it later 
(incorrect = NQ -correct)

>
> In the very end I would like to take this code as a basis for a 
> wxPython program. Are there any structural requirements I am violating 
> here?

Not that I can see. It is common practice to separate logic from display.
>
> If I want to limit the number of questions asked, say to 20, would I 
> operate with slicing methods on the randomised pool?

My solution does not use a randomized pool. Just a loop over range(NQ)
>
> How would you go about showing stats for the second run (i.e. the 
> FaultyAnswers)? Right now I am thinking of setting the global 
> variables correct and incorrect to 0 from _within_ askFaultyAnswers; 
> then I would run showStats() also from _within_ askFaultyAnswers. Good 
> idea?

Yes indeed. That is what I did before reading your comment! Great minds 
think alike.

-- 
Bob Gailer
919-636-4239
Chapel Hill NC



More information about the Tutor mailing list