0

EDIT: The question isn't a duplicate as i'm asking how to shorten this task which is written out in full and the question that is said to be duplicate to mine asks why 'a == b or c or d' always evaluates to True which i know the answer of and that isn't what I'm stuck with.

I started making this function however i have no idea who to shorten this 'or' task as first of all it doesn't look good and second if the list was 100 elements long it would be ridiculous to be typing moves[n] all the way to moves[n+99].

Any suggestions of how to shorten this as i can't think of anything also side note they need to be integers i know i could have done

if playerMove == '1 2 3 4 5 6 7 8 9'.split():

however playerMove is a integer and the numbers are strings.

def getPlayerMove(playerMove):
    while True:
        n=0
        moves = [1,2,3,4,5,6,7,8,9]
        if playerMove == moves[n] or moves[n+1] or moves[n+2] or moves[+3] or moves[n+4] or moves[n+5] or moves[n+6] or moves[n+7] or moves[n+8] or moves[n+9]:
            return playerMove
        else:
            playerMove = int(input("Enter Number 1-9"))
Ivan
  • 117
  • 1
  • 1
  • 9

1 Answers1

3

You actually want to check the membership so just use in operator. Also as a more pythonic way use a set for preserving your moves since its complexity of membership checking is approximately O(1):

moves = {1,2,3,4,5,6,7,8,9}
if playerMove in moves:
    # do something 
kasravnd
  • 94,640
  • 16
  • 137
  • 166
  • Sorry the comment was in the wrong place. I meant that if the values are every value in the list then just check the upper an lower limits. You only need to use `in` if some intermediate values are missing from the list (1, 3, 5, 6, 9) – sabbahillel Apr 07 '17 at 14:11
  • what is the time complexity of `in` on a Py 3 `range` object; presumably just O(n) like a `list`? – Chris_Rands Apr 07 '17 at 14:14
  • @Chris_Rands, no since python 3.2 membership testing for `range` objects is done in constant time as stated by the documentation. – Wombatz Apr 07 '17 at 14:38
  • 1
    @Chris_Rands http://stackoverflow.com/questions/30081275/why-is-1000000000000000-in-range1000000000000001-so-fast-in-python-3?rq=1 – kasravnd Apr 07 '17 at 14:38
  • @Wombatz Ah ha, thanks both, so it's O(l) for integers – Chris_Rands Apr 07 '17 at 14:48
  • Thank you for the answer :D – Ivan Apr 07 '17 at 15:45