I have a list of possibilities and a desired input:
possibles = [20, 30, 40, 50, 60, 70, 80, 100]
desired = [20, 30, 40]
I want to generate the close by lists. Example:
# Distance of 1 (i.e. 1 element changes to a close-by)
[30, 30, 40]
[20, 40, 40]
[20, 30, 30]
[20, 30, 50]
# Distance of 2:
[40, 30, 40]
[30, 30, 50]
[30, 40, 40]
...
My current version is only varying one element at a time, thus, as soon as the distance is above 1, I'm missing a lot of combination.
def generate_close_by(possibles, desired):
for k in range(1, 4):
for i, elt in enumerate(desired):
id = possibles.index(elt)
new = desired[:]
if id < len(possibles)-k-1:
new[i] = possibles[id+k]
yield (new)
if id > k:
new[i] = possibles[id-k]
yield (new)
# Output
[30, 30, 40]
[20, 40, 40]
[20, 30, 50]
[20, 30, 30]
[40, 30, 40]
[20, 50, 40]
[20, 30, 60]
[50, 30, 40]
[20, 60, 40]
[20, 30, 70]
I'm quite sure a module should already exist to do this kind of iteration (itertools?), could you point me to the write function?
Thanks.
EDIT:
Update on the tries...
I'm trying to generate a list the same size of desired in which each element correspond to how much I have to move the element of desired.
desired = [20, 30, 40]
# Distance of 1:
distance = [1, 0, 0]
distance = [0, 1, 0]
distance = [0, 0, 1]
distance = [-1, 0, 0]
distance = [0, -1, 0]
distance = [0, 0, -1]
And then plan was to try to create the new list, and if it can't (out of bounds), it just continues. Not working yet, but might be a good approach.
k
– Fletcherdesired
always subset ofpossibles
? – Janenejanenna[20, 20, 40]
? – Interfere