Home > Article > Backend Development > Program to find related numbers in json?
Question
str={'Tom':'1,2,3','Jack':'1,5,9','Bob':'2','Li':'2,7'}
If you find 1 in Tom’s number, then give Jack’s 5,9 to Tom;
If you find 2 in Tom’s number, then give Li’s 7 to Tom, Bob only has a 2 and no other numbers, so he can’t give it;
Found 3 in Tom’s number, and Jack, Bob, and Li don’t have 3, so he can’t give it;
...
Finally, we got:
str_related={'Tom':'5,9,7','Jack':'2,3','Bob':'1,3,7','Li':'1,3'}
No Do you know the description is clear?
The real situation: there are many people, at least 10k, and the number is at least 100k
How to write this program efficiently? Thank you
Answer 1:
can be split like this
const objLast = {} const tempTom = [] const tom = str['Tom'].solit(',') tom.map((item, i)=> { for(let key in str) { if(key != 'Tom') { tempTom.concact(getLastOfArr(str[key].split(','), item)) } } }) objLast.Tom = tempTom.join() function getLastOfArr(arr, removeKey) { return arr.filter((item, index) => { item != removeKey }) }
Because I don’t know if your parameters are certain, so I probably wrote it like this
I later found out that what you wanted was written in php, and mine was js For writing methods, you can look at the ideas~~~~
Answer 2:
python3 set
data = {'Tom':{1,2,3},'Jack':{1,5,9},'Bob':{2},'Li':{2,7}} rslt = {} for k in data: s=set() for x in data: if k!=x: s |= data[k]&data[x] and data[x]-data[k] rslt[k] = s print(rslt)
Result:
{'Jack': {2, 3}, 'Tom': {9, 5, 7}, 'Li': {1, 3}, 'Bob': {1, 3, 7}}
Optimization~
Calculate once first, save the valid set, and avoid unnecessary repeated calculations.
data = {'Tom':{1,2,3},'Jack':{1,5,9},'Bob':{2},'Li':{2,7}} valid = {} # 有效值 for k in data: for x in data: key = '%s-%s'%(x, k) if k != x \ and (key not in valid) \ and data[k] & data[x] \ and data[x] - data[k] \ : valid[key] = data[x] - data[k] rslt = {} for k in data: s=set() for x in data: s |= valid.get('%s-%s'%(x, k),set()) rslt[k] = s print(rslt)