create table testtb(n int);
insert into testtb values(959),(3480),(9346),(8367),(2847),(8330),(6946),(9586),(9722),(2775);
Мне хотелось бы найти в списке элементы с суммой 43219.
Я считал, что SQL — не лучший выбор, поэтому выбрал программирование и закончил его.
Вот как я это сделал на Python, используя следующий скрипт:
import random
ls=[959, 3480, 9346, 8367, 2847, 8330, 6946, 9586, 9722, 2775]
length=len(ls)
flag=True
while flag:
new_ls=random.sample(ls,length) #get a list with the same elements but in different order
print(f'\n\na new list with the following combination begins: {new_ls}')
total=0
index=0
for n in new_ls:
total=total+n
if total>43219: #there is no need to keep on using the current list
break
elif total==43219: #found the answer
print(f'\nfound the combination:{new_ls[:index+1]}')
print(f'it has a length of {index+1}')
print(f'the sorted list is:{sorted(new_ls[:index+1])}')
flag=False
break
index+=1
После запуска скрипта я получил ответ после нескольких неудачных комбинаций:
a new list with the following combination begins: [8330, 9346, 8367, 9722, 959, 9586, 2847, 3480, 6946, 2775]
a new list with the following combination begins: [6946, 2847, 2775, 959, 8367, 8330, 3480, 9346, 9586, 9722]
a new list with the following combination begins: [2775, 3480, 959, 8367, 9586, 9722, 8330, 6946, 9346, 2847]
found the combination:[2775, 3480, 959, 8367, 9586, 9722, 8330]
it has a length of 7
the sorted list is:[959, 2775, 3480, 8330, 8367, 9586, 9722]
Конечно, подобное можно сделать и в MySQL. Временную таблицу можно создать с помощью:
Затем используйте курсор, чтобы получить значение из каждой строки и добавить их одну за другой. И сравните сумму с постоянным значением.
В любом случае проблема в том, что разрешение зависит от слишком большой случайности. Есть ли лучший способ добиться этого? (будь то Python или MySQL)
У меня есть список, состоящий из числовых значений: В python это записывается как: [code][959, 3480, 9346, 8367, 2847, 8330, 6946, 9586, 9722, 2775] [/code] Или в случае с Mysql: [code]create table testtb(n int); insert into testtb values(959),(3480),(9346),(8367),(2847),(8330),(6946),(9586),(9722),(2775); [/code] Мне хотелось бы найти в списке элементы с суммой 43219. Я считал, что SQL — не лучший выбор, поэтому выбрал программирование и закончил его. Вот как я это сделал на Python, используя следующий скрипт: [code]import random ls=[959, 3480, 9346, 8367, 2847, 8330, 6946, 9586, 9722, 2775] length=len(ls)
flag=True while flag: new_ls=random.sample(ls,length) #get a list with the same elements but in different order print(f'\n\na new list with the following combination begins: {new_ls}') total=0 index=0 for n in new_ls: total=total+n if total>43219: #there is no need to keep on using the current list break elif total==43219: #found the answer print(f'\nfound the combination:{new_ls[:index+1]}') print(f'it has a length of {index+1}') print(f'the sorted list is:{sorted(new_ls[:index+1])}') flag=False break index+=1
[/code] После запуска скрипта я получил ответ после нескольких неудачных комбинаций: [code]a new list with the following combination begins: [8330, 9346, 8367, 9722, 959, 9586, 2847, 3480, 6946, 2775]
a new list with the following combination begins: [6946, 2847, 2775, 959, 8367, 8330, 3480, 9346, 9586, 9722]
a new list with the following combination begins: [2775, 3480, 959, 8367, 9586, 9722, 8330, 6946, 9346, 2847]
found the combination:[2775, 3480, 959, 8367, 9586, 9722, 8330] it has a length of 7 the sorted list is:[959, 2775, 3480, 8330, 8367, 9586, 9722] [/code] Конечно, подобное можно сделать и в MySQL. Временную таблицу можно создать с помощью: [code]select n from testtb order by rand(); [/code] Затем используйте курсор, чтобы получить значение из каждой строки и добавить их одну за другой. И сравните сумму с постоянным значением. В любом случае проблема в том, что разрешение зависит от слишком большой случайности. Есть ли лучший способ добиться этого? (будь то Python или MySQL)