Price list behind API: Difference between revisions

(New draft task with Python solution)
 
Line 15:
# Show output from a sample run here.
 
=={{header|PythonPhix}}==
{{trans|Python}}
Note that defaulted arguments of the form mx=get_max_price() are not currently supported, hence a slightly hacky workaround.
<lang Phix>constant price_list_size = 99_000 + rand(2_001) - 1,
price_list = sq_sub(sq_rand(repeat(100_000,price_list_size)),1),
delta_price = 1 -- Minimum difference between any two different prices.
function get_prange_count(integer startp, endp)
return length(filter(price_list,"in",{startp,endp},"[]"))
end function
 
function get_max_price()
return max(price_list)
end function
 
function get_5k(integer mn=0, mx=-1, num=5_000)
if mx=-1 then mx = get_max_price() end if
-- Binary search for num items between mn and mx, adjusting mx
integer count = get_prange_count(mn, mx)
atom delta_mx = (mx - mn) / 2
while count != num and delta_mx >= delta_price / 2 do
mx = floor(mx + iff(count > num ? -delta_mx : +delta_mx))
{count, delta_mx} = {get_prange_count(mn, mx), delta_mx / 2}
end while
return {mx, count}
end function
 
function get_all_5k(integer mn=0, mx=-1, num=5_000)
if mx=-1 then mx = get_max_price() end if
-- Get all non-overlapping ranges
integer {partmax, partcount} = get_5k(mn, mx, num)
sequence result = {{mn, partmax, partcount}}
while partmax < mx do
integer partmin = partmax + delta_price
{partmax, partcount} = get_5k(partmin, mx, num)
result = append(result,{partmin, partmax, partcount})
end while
return result
end function
 
printf(1,"Using %d random prices from 0 to %d\n",{price_list_size,get_max_price()})
sequence result = get_all_5k()
printf(1,"Splits into %d bins of approx 5000 elements\n",{length(result)})
for i=1 to length(result) do
printf(1," From %8.1f ... %8.1f with %d items.\n",result[i])
end for
if length(price_list) != sum(vslice(result,3)) then
printf(1,"\nWhoops! Some items missing:\n")
end if</lang>
{{out}}
<pre>
Using 99714 random prices from 0 to 99999
Splits into 20 bins of approx 5000 elements
From 0.0 ... 4977.0 with 5000 items.
From 4978.0 ... 10019.0 with 4999 items.
From 10020.0 ... 15114.0 with 4999 items.
From 15115.0 ... 19987.0 with 4998 items.
From 19988.0 ... 25088.0 with 4996 items.
From 25089.0 ... 30080.0 with 4995 items.
From 30081.0 ... 35117.0 with 5000 items.
From 35118.0 ... 40081.0 with 4999 items.
From 40082.0 ... 45080.0 with 5000 items.
From 45081.0 ... 50181.0 with 5000 items.
From 50182.0 ... 55223.0 with 5000 items.
From 55224.0 ... 60271.0 with 5000 items.
From 60272.0 ... 65102.0 with 4999 items.
From 65103.0 ... 70140.0 with 5000 items.
From 70141.0 ... 75195.0 with 4997 items.
From 75196.0 ... 80203.0 with 4998 items.
From 80204.0 ... 85210.0 with 4999 items.
From 85211.0 ... 90182.0 with 5000 items.
From 90183.0 ... 95268.0 with 4999 items.
From 95269.0 ... 104722.0 with 4736 items.
</pre>
 
=={{header|Python}}==
<lang python>import random
 
7,806

edits