Home > OS >  How to find the closest number from summed numbers with showing which numbers are used
How to find the closest number from summed numbers with showing which numbers are used

Time:09-10

I'm doing a project where I have a list of number random numbers get choosen from it:

list = [1,2,3,4,5,6,7,8,9]
for i in range(5):
    first = int(random.choice(list))
    second = int(random.choice(list))
    third = int(random.choice(list))
    sumofall = (first   second   third)

And It sums the random numbers and gives a result as 'int' and I have str that gives which numbers summed to get that result like:

    which_num = str(first)   '   '   str(second)   '   '   str(third) #Equals 7

As it showen in the 1st code i want to find its result and which numbers are summed to find it and from the results like: 9, 12, 8. I want to find the which of the result is the closest to this int and also show which numbers are summed to get that result

Want result like

list of summed numbers: 9, 12 ,8, 10, 13

I want the number closest to 14
It prints/shows:
Closest one is: 13
Summed these: 2   5   6

Maybe it can be solved easier with pandas but I'm not sure

CodePudding user response:

You have to store in dictionary to simply the approach,

def closest(n, lst):
    return min(lst, key=lambda x: abs(x - n))

lst = [1, 2, 3, 4, 5, 6, 7, 8, 9]
d = {}
for i in range(5):
    vals = vals = [random.choice(lst) for _ in range(3)]
    d[sum(vals)] = vals

print(f'list of summed numbers: {list(d.keys())}')
print(f'I want the number closest to {14}')

closed_one = closest(14, d.keys())

print(f'Closest one is: {closed_one}')
print(f'Summed these: {d[closed_one]}')

Output:

list of summed numbers: [18, 7, 10, 5, 15]
I want the number closest to 14
Closest one is: 15
Summed these: [5, 9, 1]

EDIT As Vald mentioned, there if there is a duplication dictionary will override the key exiting. So you can do an approach like this,

def closest(n, lst):
     return min(lst, key=lambda x: abs(int(x.split("_")[1]) - n)) 
 
lst = [1, 2, 3, 4, 5, 6, 7, 8, 9]
d = {}
for i in range(5):
     vals = vals = [random.choice(lst) for _ in range(3)]
     d[f"{i}_{sum(vals)}"] = vals
 
print(f"list of summed numbers: {list(map(lambda x: x.split('_')[1], d.keys()))}")
print(f"I want the number closest to {14}")
 
closed_one = closest(14, d.keys())

print(f"Closest one is: {closed_one.split('_')[1]}")
print(f"Summed these: {d[closed_one]}")

Output

list of summed numbers: ['21', '15', '20', '17', '18']
I want the number closest to 14
Closest one is: 15
Summed these: [5, 6, 4]

CodePudding user response:

Without trying to format the output or figuring out where the input values come from, here's an approach that may be useful...

from random import choice

NSELECTIONS = 5
NVALS = 3

list_of_numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]

selected_values = {}

while len(selected_values) < NSELECTIONS:
    t = [choice(list_of_numbers) for _ in range(NVALS)]
    selected_values[sum(t)] = t

nearest_to = 14

kv = min(selected_values, key=lambda x: abs(x-nearest_to))

print(kv, selected_values[kv])

CodePudding user response:

you need to save the sum in an array with the index of summed number it is better to use random.randint

    from json.encoder import INFINITY
    from ntpath import join
    import random
    
    
    number = 14
    list_of_sum = []
    list = [1,2,3,4,5,6,7,8,9]
    for i in range(5):
        first_index = random.randint(0,len(list)-1)
        second_index = random.randint(0,len(list)-1)
        third_index = random.randint(0,len(list)-1)
        first = list[first_index]
        second = list[second_index]
        third = list[third_index]
        sum = first   second   third
        list_of_sum.append([sum,[first_index,second_index,third_index]])
        which_num = str(first)   '   '   str(second)   '   '   str(third)    ' = '   str(sum)
        print(which_num)
    
    items_of_sum = ','.join([str(item[0])  for item in list_of_sum])
    print('list of summed numbers: '   items_of_sum   '\n')
    
    
    start_value = INFINITY
    numbers_index = 0
    sum_index = 0
    for i in range(5):
        sub = abs(list_of_sum[i][0] - number)
        if sub < start_value:
            start_value = sub
            sum_index = i
            numbers_index = list_of_sum[i][1]
    
    
    
    print('Closest one is: '    str(list_of_sum[sum_index][0]))
    
    print('Summed these: '    ','.join([str(list[index])  for index in numbers_index]))

  • Related