Python Forum
Cant get my head round the algorithm
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Cant get my head round the algorithm
#2
(Apr-09-2019, 10:29 PM)hshivaraj Wrote: List 500 700 1000 1400 2000
target 2300

There inst a direct match but the closest is 1400 + 700 which gives me 2100. And this the right answer.

The closet is 1000 + 1400 which gives 2400

items = (500, 700, 1000, 1400, 2000)
target = 2300

from itertools import combinations

nearest = target
best_match = None

for item1, item2 in combinations(items, 2):
    differance = abs(target - (item1 + item2))
    if differance <= nearest:
        best_match = (item1, item2)
        nearest = differance
        
print(f'The best match to {target} is {best_match} at {sum(best_match)}')
Output:
The best match to 2300 is (1000, 1400) at 2400
Unless the best match must be must be equal to or below the target.
items = (500, 700, 1000, 1400, 2000)
target = 2300

from itertools import combinations

nearest = target
best_match = None

for item1, item2 in combinations(items, 2):
    differance = abs(target - (item1 + item2))
    if differance <= nearest and (item1 + item2) <= target:
        best_match = (item1, item2)
        nearest = differance
        
print(f'The best match to {target} is {best_match} at {sum(best_match)}')
Output:
The best match to 2300 is (700, 1400) at 2100
Reply


Messages In This Thread
Cant get my head round the algorithm - by hshivaraj - Apr-09-2019, 10:29 PM
RE: Cant get my head round the algorithm - by Yoriz - Apr-09-2019, 10:38 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  numpy.array has no attribute head Led_Zeppelin 1 1,490 Jul-13-2022, 12:56 AM
Last Post: Led_Zeppelin
  Cannot get output for df.head() Led_Zeppelin 0 1,168 Jun-28-2022, 02:15 PM
Last Post: Led_Zeppelin
  Pyhton code help from head first with python Shaikat_99 3 3,362 Jun-07-2020, 09:12 AM
Last Post: snippsat
  Pandas: .(head) Can I specify a range in head? eeps24 6 4,121 May-11-2020, 04:27 PM
Last Post: eeps24
  Unexpected round behavior pythonCoder 1 2,365 Feb-19-2019, 02:39 PM
Last Post: marienbad
  Add parameter to math.floor() to round to specific decimal point gabrield 2 2,861 Mar-09-2018, 08:43 PM
Last Post: wavic
  invalid syntax in my program, really doing my head in! Fazz92 1 4,077 May-07-2017, 12:54 PM
Last Post: Bass
  Round a number up to certain significant figures brocq_18 4 7,387 Apr-06-2017, 06:49 PM
Last Post: alicarlos13

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020