r/Clojure • • May 22 '25
Make the code more readable in Clojure (I doubt it's possible)
def twoSum(nums: list, target: int, i=0):
if len(nums) == i or nums[i] > target:
return []
if nums[i] == target:
return [i]
if nums[i] < target:
dont_take_current = twoSum(nums, target, i + 1)
if len(dont_take_current) > 0:
return dont_take_current
take_current = twoSum(nums, target - nums[i], i + 1)
if len(take_current) > 0:
return [i] + take_current
return []Given an array of integers nums and an integer target, return indices of the numbers such that they add up to target.
Constraints: the nums list contains no duplicates and is sorted, nums contains only positive numbers.
There might be a better solution, but you should take the same approach, i.e. brute force.
class MyTestCase(unittest.TestCase):
def test_something(self):
self.assertEqual([0, 1], twoSum([1, 2, 4], 3))
def test_something_else(self):
self.assertEqual([0], twoSum([0,3,4], 0))
0
Upvotes
4
u/ydsaydsa May 23 '25
"Readable" is subjective but heres a solution in a similar style to yours
16
u/jcolechanged May 22 '25
2
u/birdspider May 22 '25
explain the 2nd testcase, index 0 does not point to 2 nums which sum (0+3) equals 0
EDIT: I mean why expect
[0]3
u/joinr May 22 '25
I doubt it's impossible.
1
u/didibus May 24 '25 edited May 24 '25
You can just translate it 1:1