python using any() and all() to check if a list contains one set of values or another -


my code tic tac toe game , checking draw state think question more useful in general sense.

i have list represents board, looks this:

board = [1,2,3,4,5,6,7,8,9] 

when player makes move int moved on replaced marker ('x' or 'o'), have checks in place winning state, can't check draw state, none of list values ints winning state has not been set.

the code have far:

if any(board) != playerone or any(board) != playertwo:     print 'continue' elif all(board) == playerone or playertwo:     print 'draw' 

the if statement works, elif not, think problem 'or' operator, want check is: if every item on board either playerone marker or playertwo marker, if make code:

elif all(board) == playerone or all(board) == playertwo: 

i checking see if every place on board playerone or every place on board playertwo, won't be.

so how check if board taken combination of playerone markers , playertwo markers?

all , any functions take iterable , determine either:

  • in case of all(): if all values in iterable non-false;
  • in case of any(): if any of values in iterable non-false.

so misunderstood little bit how these functions work.

hence, following not thought does:

if any(foobars) == big_foobar: 

...because any(foobars) first evaluated either true or false, , boolean value compared big_foobar, gives false, assuming foobars not booleans.

note: iterable can list, can generator/generator expression (≈ lazily evaluated/generated list) or other iterator.

what want instead is:

if any(x == big_foobar x in foobars): 

which first constructs iterable yields sequence of booleans—for each item in foobars, compares item big_foobar , emits resulting boolean resulting sequence:

tmp = (x == big_foobar x in foobars) 

then any walks on items in tmp , returns true finds first true item. it's if did following:

foobars = ['big', 'small', 'medium', 'nice', 'ugly'] big_foobar = 'big' any(['big' == big_foobar, 'small' == big_foobar, 'medium' == big_foobar, ...]) 

note: dsm pointed out, any(x == y x in xs) case better expressed y in xs—this easier read, write , faster.

some examples:

any(x > 5 x in range(4))  # => false all(isinstance(x, int) x in range(10))  # => true any(x == 'erik' x in ['erik', 'john', 'jane', 'jim'])  # => true all([true, true, true, false, true])  # => false 

i suggest playing any , all various inputs on python shell, or better yet, on ipython shell feel of how works before continue writing actual code.

see also: http://docs.python.org/2/library/functions.html#all


Comments

Popular posts from this blog

java.util.scanner - How to read and add only numbers to array from a text file -

rewrite - Trouble with Wordpress multiple custom querystrings -