简体   繁体   中英

How can i use numpy allclose to compare arrays of variable length?

My full code is: https://pastebin.com/ChqTHRzY

Basically if the arrays i want to compare are exactly the same length, it works great. If they are shorter or longer it fail. I want it to compare the values in moves_user against each group in arrayof_wins. The code does this but only when they are the same length, which isn´t going to be the case. How can i get this to be compared despite having fewer or greater numbers of items in the "moves" arrays compared to the arrayof_wins?

I´ll paste the code here too in case you cant see the page above:

import numpy as np

arrayof_wins = [[11,12,13],[21,22,23],[31,32,33],[11,21,31],[12,22,32],[13,23,33],[11,22,33],[13,22,31]]
moves_user = [22, 12, 32]
moves_computer = [21,22]

result = ""

moves_user.sort()
moves_computer.sort()

founduser = False
x = 0
while founduser == False and x <= 7:
    founduser = (np.allclose(moves_user, arrayof_wins[x]))
    x += 1


foundcomp = False
y = 0
while foundcomp == False and y <= 7:
    foundcomp = (np.allclose(moves_computer, arrayof_wins[y]))
    y += 1



if founduser == True:
    result = "You win!"
elif foundcomp == True:
    result = "Computer wins!"

print(result)

If all the elements are (arrays of) integers then you don't need allclose , which is meant for comparing floating point variables within a tolerance threshold. If I understand you correctly something like

founduser = False
for win in arrayof_wins:
    if set(win).issubset(set(moves_user)):
        founduser = True
        break

might work for you: the variable founduser will be True is any of the winning sequences is a subset of the moves_user array. This assumes that neither ordering nor repetitions matter. The final break statement is optional, but prevents unnecessary tests after the first match has been found. Of course it would be even better to do the conversion from lists to sets only once.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM