List into list

Hello @Faud_Sami, I see you are learning more and more! (Maybe translating more Python code as well :wink:)
Here are a couple of other ideas for this function:

# the original, pared down a bit
function pair_sum(nums, target)
    d = Set()
    output = NTuple{2, eltype(nums)}[]
    for x in nums
        y = target - x
        if y in d
            push!(output, (x, y))
        else
            push!(d, x)
        end
    end
    return output
end

# the same idea, more "direct"
# might want to ensure `nums` is unique for this
# or you'll have repeats
function pair_sum2(nums, target)
    N = length(nums)
    output = []
    for i in 1:N, j in (i+1):N
        if nums[i] + nums[j] == target
            push!(output, (nums[i], nums[j]))
        end
    end
    output
end

# if you don't care about repeats like (2, 7) and (7, 2)
pair_sum3(nums, y) = [(x, y-x) for x in nums if y-x in nums]

And their benchmarks

julia> nums = unique(rand(1:500, 100));

julia> target = rand(1:600)
579

julia> @btime pair_sum($nums, Ref(target)[])
  10.951 μs (18 allocations: 4.50 KiB)
10-element Array{Tuple{Int64,Int64},1}:
 (331, 248)
 (429, 150)
 (152, 427)
 (161, 418)
 (300, 279)
 (426, 153)
 (334, 245)
 (277, 302)
 (85, 494)
 (188, 391)

julia> @btime pair_sum2($nums, Ref(target)[]);
  5.203 μs (16 allocations: 704 bytes)

julia> @btime pair_sum3($nums, Ref(target)[]);
  5.134 μs (11 allocations: 1.30 KiB)
2 Likes