Running Python 3.6.5
I'm very new to python. When I run these lines separately in the terminal, I get exactly what I want. When I run the python file, the input prompt 'ideal weight?' won't end after I submit a number. It keeps repeating 'ideal weight?'. I'm trying to find the combination of numbers from the 'weights' set that will sum up to the user input.
import itertools
weights = [3, 3, 7.5, 7.5, 10]
weightint = int(input('ideal weight? '))
result = [seq for i in range(len(weights), 0, -1) for seq in itertools.combinations(weights, i) if sum(seq) == weightint]
print(result)
Can someone help explain what I'm doing wrong. Thank you!
Not sure whats wrong with your terminal. Consider using argparse instead of input:
import itertools
import argparse
MY_WEIGHTS = [3, 3, 7.5, 7.5, 10]
def find_weight(w):
result = [seq for i in range(len(MY_WEIGHTS), 0, -1) for seq in itertools.combinations(MY_WEIGHTS, i) if sum(seq) == w]
return result
def main():
parser = argparse.ArgumentParser()
parser.add_argument('-w', '--weight', required=True, type=int, help='The weight')
args = parser.parse_args()
result = find_weight(args.weight)
print('result: {}'.format(result))
if __name__ == '__main__':
main()
Then call it from command line with --weight or -w:
python3 ./weight.py --weight 10
result: [(10,)]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With