Naive solution here - basically construct a dictionary with the sum of all possible weight combinations for initial weight a and then add all possible combinations of weights to initial weight b to determine which is the smallest number of weights to achieve equilibrium.
I will be working on refactoring to make this more efficient, but I figured I'd code out a naive implementation as a baseline first before moving on and improving time complexity.
Python
importitertoolsdefbalance(scaleArr):a,b=scaleArr[0]weights=scaleArr[1]lowest_quantity=Nonea_weight=Noneb_weight=Nonesum_dict={a:()}combo_dict={}foriinrange(len(weights)):combos=list(itertools.combinations(weights,i))combo_dict[i]=combosforxinrange(len(combos)):sum=afornincombos[x]:sum+=nifsum==b:lowest_quantity=ia_weight=combos[x]b_weight=()ifsuminsum_dict:ifx<len(sum_dict[sum]):sum_dict[sum]=combos[x]else:sum_dict[sum]=combos[x]foriinrange(len(weights)):combos=combo_dict[i]forxinrange(len(combos)):sum=bfornincombos[x]:sum+=nifsuminsum_dict:current_quantity=i+len(sum_dict[sum])iflowest_quantityisNoneorcurrent_quantity<lowest_quantity:lowest_quantity=current_quantitya_weight=sum_dict[sum]b_weight=combos[x]iflowest_quantityisNone:return'not possible'left=', '.join(str(n)fornina_weight)iflen(a_weight)else'nothing'right=', '.join(str(n)forninb_weight)iflen(b_weight)else'nothing'return('The fewest number of weights needed for equality is 'f'{lowest_quantity}, putting {left} on the left and {right} on the right.')
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
Naive solution here - basically construct a dictionary with the sum of all possible weight combinations for initial weight
a
and then add all possible combinations of weights to initial weightb
to determine which is the smallest number of weights to achieve equilibrium.I will be working on refactoring to make this more efficient, but I figured I'd code out a naive implementation as a baseline first before moving on and improving time complexity.
Python