Finding the index of an element to be inserted in a sorted listGiven an ordered set S, find the points in S corresponding to another listFinding all elements within a certain range in a sorted listFinding an index with certain conditionsFinding duplicates in a listFinding the index of (x,y) pairs in a listClean and handy Options management/filteringEasiest/most efficient way to delete duplicates from one list at the positions of another?Corresponding list value and index in a listHow to use the value returned from Position as index for another list?Inserting an integer into a sorted listFinding the index of a specific element in a list

What does the hyphen "-" mean in "tar xzf -"?

Parameterize chained calls to a utility program in Bash

Can White Castle?

Improving triangulation on AutoCAD-generated stl files

What is the origin of Scooby-Doo's name?

Drawing people along with x and y axis

Employer wants to use my work email account after I quit

Explain why a line can never intersect a plane in exactly two points.

Do I have any obligations to my PhD supervisor's requests after I have graduated?

Unusual mail headers, evidence of an attempted attack. Have I been pwned?

How to find the last non zero element in every column throughout dataframe?

When two first person POV characters meet

Why do all the teams that I have worked with always finish a sprint without completion of all the stories?

Is it illegal to withhold someone's passport and green card in California?

What can I do with a research project that is my university’s intellectual property?

LWC - Best practice for routing?

Why do even high-end cameras often still include normal (non-cross-type) AF sensors?

Output of "$OSTYPE:6" on old releases of Mac OS X

How to make clear to people I don't want to answer their "Where are you from?" question?

Would it be a copyright violation if I made a character’s full name refer to a song?

How to model a twisted cylinder like this

How is hair tissue mineral analysis performed?

Are all instances of trolls turning to stone ultimately references back to Tolkien?

How to remove this component from PCB



Finding the index of an element to be inserted in a sorted list


Given an ordered set S, find the points in S corresponding to another listFinding all elements within a certain range in a sorted listFinding an index with certain conditionsFinding duplicates in a listFinding the index of (x,y) pairs in a listClean and handy Options management/filteringEasiest/most efficient way to delete duplicates from one list at the positions of another?Corresponding list value and index in a listHow to use the value returned from Position as index for another list?Inserting an integer into a sorted listFinding the index of a specific element in a list






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








4












$begingroup$


I have a sorted list with no duplicates:



L = 1, 2, 5, 7, 8


Given an integer n, I want to find the index of n if it is to be inserted into L.



I have been using



Length[Select[L, # <= n &]]



But that is incredibly unoptimal as I should be able to do this in $log n$ by bisecting the set. How should I approach this?










share|improve this question









New contributor



user66097 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.






$endgroup$


















    4












    $begingroup$


    I have a sorted list with no duplicates:



    L = 1, 2, 5, 7, 8


    Given an integer n, I want to find the index of n if it is to be inserted into L.



    I have been using



    Length[Select[L, # <= n &]]



    But that is incredibly unoptimal as I should be able to do this in $log n$ by bisecting the set. How should I approach this?










    share|improve this question









    New contributor



    user66097 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
    Check out our Code of Conduct.






    $endgroup$














      4












      4








      4


      1



      $begingroup$


      I have a sorted list with no duplicates:



      L = 1, 2, 5, 7, 8


      Given an integer n, I want to find the index of n if it is to be inserted into L.



      I have been using



      Length[Select[L, # <= n &]]



      But that is incredibly unoptimal as I should be able to do this in $log n$ by bisecting the set. How should I approach this?










      share|improve this question









      New contributor



      user66097 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.






      $endgroup$




      I have a sorted list with no duplicates:



      L = 1, 2, 5, 7, 8


      Given an integer n, I want to find the index of n if it is to be inserted into L.



      I have been using



      Length[Select[L, # <= n &]]



      But that is incredibly unoptimal as I should be able to do this in $log n$ by bisecting the set. How should I approach this?







      list-manipulation function-construction






      share|improve this question









      New contributor



      user66097 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.










      share|improve this question









      New contributor



      user66097 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.








      share|improve this question




      share|improve this question








      edited Jun 13 at 3:34









      David G. Stork

      25.6k22256




      25.6k22256






      New contributor



      user66097 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.








      asked Jun 13 at 2:45









      user66097user66097

      241




      241




      New contributor



      user66097 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.




      New contributor




      user66097 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.






















          3 Answers
          3






          active

          oldest

          votes


















          4












          $begingroup$

          ClearAll[pos0, pos1, pos2, pos3]
          pos0[l_, n_] := Total@UnitStep[n - l]
          pos1[l_, n_] := LengthWhile[l, # < n &]
          pos2[l_, n_] := Ordering[Ordering[Join[n, l]]][[1]]
          pos3[l_, n_] := If[n <= Length[l]/3, pos1[l, n], pos2[l, n]]


          L = 1, 2, 5, 7, 8;
          pos0[L,3], pos1[L, 3], pos2[L, 3], pos3[L, 3]



          2, 2, 2, 2







          share|improve this answer











          $endgroup$




















            3












            $begingroup$

            You could use a variation of my LeftNeighbor function, although it returns the left neighbor strictly less than the number instead of less equal as in your solution:



            LeftNeighbor[s_]:=LeftNeighborFunction[s,Nearest[s->"Index"]]
            LeftNeighbor[s_,list_List]:=LeftNeighbor[s][list]
            LeftNeighbor[s_, elem_]:=First@LeftNeighbor[s][elem]

            LeftNeighborFunction[s_,nf_][list_List]:=With[n=nf[list][[All,1]],n-UnitStep[s[[n]]-list]]
            LeftNeighborFunction[s_,nf_][elem_]:=First @ LeftNeighborFunction[s,nf][elem]

            MakeBoxes[i:LeftNeighborFunction[s_,nf_], StandardForm] ^:= Module[

            len=Length[s],
            g = FirstCase[ToBoxes[nf], _GraphicsBox, GraphicsBox[Point[0,0]],Infinity]
            ,
            BoxForm`ArrangeSummaryBox[
            LeftNeighborFunction,
            i,
            RawBoxes@g,

            BoxForm`MakeSummaryItem["Data points: ",Length[s],StandardForm],
            BoxForm`MakeSummaryItem["Range: ",MinMax[s],StandardForm]
            ,
            ,
            StandardForm,
            "Interpretable"->True
            ]
            ]


            Then:



            L=1,2,5,7,8;
            lnf = LeftNeighbor[L];

            lnf[5]
            lnf[Range[0, 9]]



            2



            0, 0, 1, 2, 2, 2, 3, 3, 4, 5




            It should be possible to modify the code to return the left neighbor that is less equal than the requested number if desired.



            A remark on performance



            The construction of the LeftNeighborFunction can be slow, but if you want to find the index of many numbers into the same list L, then you will only have to construct the LeftNeighborFunction once. Here is a comparison with a large list:



            L = Sort @ RandomReal[100, 10^6];


            The construction of the LeftNeightbor is a bit slow:



            lnf = LeftNeighbor[L]; //RepeatedTiming



            0.052, Null




            But finding the index of many numbers is very fast:



            sample = RandomReal[100, 10^3];
            r1 = lnf[sample]; //RepeatedTiming



            0.00020, Null




            Compare this with one of kglr's solution:



            r2 = pos0[L, #]& /@ sample; //RepeatedTiming



            3.05, Null




            Check :



            r1 === r2



            True







            share|improve this answer











            $endgroup$




















              2












              $begingroup$

              It seems to me that the issue of how to handle inappropriate inputs is as important finding the position of an integer that is in the list being considered. Therefore, I would write something like this:



              positionOfN[data : __Integer, n_Integer] := 
              First[First[Position[data, n], Return[$Failed]]]
              positionOfN[_, _] = $Failed;


              Testing



              data = 1, 2, 5, 7, 8;
              positionOfN[data, 5]



              3




              positionOfN[data, -5]



              $Failed




              positionOfN[data, 5.]



              $Failed




              positionOfN["foo", "bar", 5]



              $Failed




              Note



              If you don't want $Failed to be returned as the failure value, substitute whatever value you like for the two occurrences of $Failed.






              share|improve this answer









              $endgroup$















                Your Answer








                StackExchange.ready(function()
                var channelOptions =
                tags: "".split(" "),
                id: "387"
                ;
                initTagRenderer("".split(" "), "".split(" "), channelOptions);

                StackExchange.using("externalEditor", function()
                // Have to fire editor after snippets, if snippets enabled
                if (StackExchange.settings.snippets.snippetsEnabled)
                StackExchange.using("snippets", function()
                createEditor();
                );

                else
                createEditor();

                );

                function createEditor()
                StackExchange.prepareEditor(
                heartbeatType: 'answer',
                autoActivateHeartbeat: false,
                convertImagesToLinks: false,
                noModals: true,
                showLowRepImageUploadWarning: true,
                reputationToPostImages: null,
                bindNavPrevention: true,
                postfix: "",
                imageUploader:
                brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
                contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
                allowUrls: true
                ,
                onDemand: true,
                discardSelector: ".discard-answer"
                ,immediatelyShowMarkdownHelp:true
                );



                );






                user66097 is a new contributor. Be nice, and check out our Code of Conduct.









                draft saved

                draft discarded


















                StackExchange.ready(
                function ()
                StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fmathematica.stackexchange.com%2fquestions%2f200260%2ffinding-the-index-of-an-element-to-be-inserted-in-a-sorted-list%23new-answer', 'question_page');

                );

                Post as a guest















                Required, but never shown

























                3 Answers
                3






                active

                oldest

                votes








                3 Answers
                3






                active

                oldest

                votes









                active

                oldest

                votes






                active

                oldest

                votes









                4












                $begingroup$

                ClearAll[pos0, pos1, pos2, pos3]
                pos0[l_, n_] := Total@UnitStep[n - l]
                pos1[l_, n_] := LengthWhile[l, # < n &]
                pos2[l_, n_] := Ordering[Ordering[Join[n, l]]][[1]]
                pos3[l_, n_] := If[n <= Length[l]/3, pos1[l, n], pos2[l, n]]


                L = 1, 2, 5, 7, 8;
                pos0[L,3], pos1[L, 3], pos2[L, 3], pos3[L, 3]



                2, 2, 2, 2







                share|improve this answer











                $endgroup$

















                  4












                  $begingroup$

                  ClearAll[pos0, pos1, pos2, pos3]
                  pos0[l_, n_] := Total@UnitStep[n - l]
                  pos1[l_, n_] := LengthWhile[l, # < n &]
                  pos2[l_, n_] := Ordering[Ordering[Join[n, l]]][[1]]
                  pos3[l_, n_] := If[n <= Length[l]/3, pos1[l, n], pos2[l, n]]


                  L = 1, 2, 5, 7, 8;
                  pos0[L,3], pos1[L, 3], pos2[L, 3], pos3[L, 3]



                  2, 2, 2, 2







                  share|improve this answer











                  $endgroup$















                    4












                    4








                    4





                    $begingroup$

                    ClearAll[pos0, pos1, pos2, pos3]
                    pos0[l_, n_] := Total@UnitStep[n - l]
                    pos1[l_, n_] := LengthWhile[l, # < n &]
                    pos2[l_, n_] := Ordering[Ordering[Join[n, l]]][[1]]
                    pos3[l_, n_] := If[n <= Length[l]/3, pos1[l, n], pos2[l, n]]


                    L = 1, 2, 5, 7, 8;
                    pos0[L,3], pos1[L, 3], pos2[L, 3], pos3[L, 3]



                    2, 2, 2, 2







                    share|improve this answer











                    $endgroup$



                    ClearAll[pos0, pos1, pos2, pos3]
                    pos0[l_, n_] := Total@UnitStep[n - l]
                    pos1[l_, n_] := LengthWhile[l, # < n &]
                    pos2[l_, n_] := Ordering[Ordering[Join[n, l]]][[1]]
                    pos3[l_, n_] := If[n <= Length[l]/3, pos1[l, n], pos2[l, n]]


                    L = 1, 2, 5, 7, 8;
                    pos0[L,3], pos1[L, 3], pos2[L, 3], pos3[L, 3]



                    2, 2, 2, 2








                    share|improve this answer














                    share|improve this answer



                    share|improve this answer








                    edited Jun 13 at 3:14

























                    answered Jun 13 at 3:00









                    kglrkglr

                    199k10228454




                    199k10228454























                        3












                        $begingroup$

                        You could use a variation of my LeftNeighbor function, although it returns the left neighbor strictly less than the number instead of less equal as in your solution:



                        LeftNeighbor[s_]:=LeftNeighborFunction[s,Nearest[s->"Index"]]
                        LeftNeighbor[s_,list_List]:=LeftNeighbor[s][list]
                        LeftNeighbor[s_, elem_]:=First@LeftNeighbor[s][elem]

                        LeftNeighborFunction[s_,nf_][list_List]:=With[n=nf[list][[All,1]],n-UnitStep[s[[n]]-list]]
                        LeftNeighborFunction[s_,nf_][elem_]:=First @ LeftNeighborFunction[s,nf][elem]

                        MakeBoxes[i:LeftNeighborFunction[s_,nf_], StandardForm] ^:= Module[

                        len=Length[s],
                        g = FirstCase[ToBoxes[nf], _GraphicsBox, GraphicsBox[Point[0,0]],Infinity]
                        ,
                        BoxForm`ArrangeSummaryBox[
                        LeftNeighborFunction,
                        i,
                        RawBoxes@g,

                        BoxForm`MakeSummaryItem["Data points: ",Length[s],StandardForm],
                        BoxForm`MakeSummaryItem["Range: ",MinMax[s],StandardForm]
                        ,
                        ,
                        StandardForm,
                        "Interpretable"->True
                        ]
                        ]


                        Then:



                        L=1,2,5,7,8;
                        lnf = LeftNeighbor[L];

                        lnf[5]
                        lnf[Range[0, 9]]



                        2



                        0, 0, 1, 2, 2, 2, 3, 3, 4, 5




                        It should be possible to modify the code to return the left neighbor that is less equal than the requested number if desired.



                        A remark on performance



                        The construction of the LeftNeighborFunction can be slow, but if you want to find the index of many numbers into the same list L, then you will only have to construct the LeftNeighborFunction once. Here is a comparison with a large list:



                        L = Sort @ RandomReal[100, 10^6];


                        The construction of the LeftNeightbor is a bit slow:



                        lnf = LeftNeighbor[L]; //RepeatedTiming



                        0.052, Null




                        But finding the index of many numbers is very fast:



                        sample = RandomReal[100, 10^3];
                        r1 = lnf[sample]; //RepeatedTiming



                        0.00020, Null




                        Compare this with one of kglr's solution:



                        r2 = pos0[L, #]& /@ sample; //RepeatedTiming



                        3.05, Null




                        Check :



                        r1 === r2



                        True







                        share|improve this answer











                        $endgroup$

















                          3












                          $begingroup$

                          You could use a variation of my LeftNeighbor function, although it returns the left neighbor strictly less than the number instead of less equal as in your solution:



                          LeftNeighbor[s_]:=LeftNeighborFunction[s,Nearest[s->"Index"]]
                          LeftNeighbor[s_,list_List]:=LeftNeighbor[s][list]
                          LeftNeighbor[s_, elem_]:=First@LeftNeighbor[s][elem]

                          LeftNeighborFunction[s_,nf_][list_List]:=With[n=nf[list][[All,1]],n-UnitStep[s[[n]]-list]]
                          LeftNeighborFunction[s_,nf_][elem_]:=First @ LeftNeighborFunction[s,nf][elem]

                          MakeBoxes[i:LeftNeighborFunction[s_,nf_], StandardForm] ^:= Module[

                          len=Length[s],
                          g = FirstCase[ToBoxes[nf], _GraphicsBox, GraphicsBox[Point[0,0]],Infinity]
                          ,
                          BoxForm`ArrangeSummaryBox[
                          LeftNeighborFunction,
                          i,
                          RawBoxes@g,

                          BoxForm`MakeSummaryItem["Data points: ",Length[s],StandardForm],
                          BoxForm`MakeSummaryItem["Range: ",MinMax[s],StandardForm]
                          ,
                          ,
                          StandardForm,
                          "Interpretable"->True
                          ]
                          ]


                          Then:



                          L=1,2,5,7,8;
                          lnf = LeftNeighbor[L];

                          lnf[5]
                          lnf[Range[0, 9]]



                          2



                          0, 0, 1, 2, 2, 2, 3, 3, 4, 5




                          It should be possible to modify the code to return the left neighbor that is less equal than the requested number if desired.



                          A remark on performance



                          The construction of the LeftNeighborFunction can be slow, but if you want to find the index of many numbers into the same list L, then you will only have to construct the LeftNeighborFunction once. Here is a comparison with a large list:



                          L = Sort @ RandomReal[100, 10^6];


                          The construction of the LeftNeightbor is a bit slow:



                          lnf = LeftNeighbor[L]; //RepeatedTiming



                          0.052, Null




                          But finding the index of many numbers is very fast:



                          sample = RandomReal[100, 10^3];
                          r1 = lnf[sample]; //RepeatedTiming



                          0.00020, Null




                          Compare this with one of kglr's solution:



                          r2 = pos0[L, #]& /@ sample; //RepeatedTiming



                          3.05, Null




                          Check :



                          r1 === r2



                          True







                          share|improve this answer











                          $endgroup$















                            3












                            3








                            3





                            $begingroup$

                            You could use a variation of my LeftNeighbor function, although it returns the left neighbor strictly less than the number instead of less equal as in your solution:



                            LeftNeighbor[s_]:=LeftNeighborFunction[s,Nearest[s->"Index"]]
                            LeftNeighbor[s_,list_List]:=LeftNeighbor[s][list]
                            LeftNeighbor[s_, elem_]:=First@LeftNeighbor[s][elem]

                            LeftNeighborFunction[s_,nf_][list_List]:=With[n=nf[list][[All,1]],n-UnitStep[s[[n]]-list]]
                            LeftNeighborFunction[s_,nf_][elem_]:=First @ LeftNeighborFunction[s,nf][elem]

                            MakeBoxes[i:LeftNeighborFunction[s_,nf_], StandardForm] ^:= Module[

                            len=Length[s],
                            g = FirstCase[ToBoxes[nf], _GraphicsBox, GraphicsBox[Point[0,0]],Infinity]
                            ,
                            BoxForm`ArrangeSummaryBox[
                            LeftNeighborFunction,
                            i,
                            RawBoxes@g,

                            BoxForm`MakeSummaryItem["Data points: ",Length[s],StandardForm],
                            BoxForm`MakeSummaryItem["Range: ",MinMax[s],StandardForm]
                            ,
                            ,
                            StandardForm,
                            "Interpretable"->True
                            ]
                            ]


                            Then:



                            L=1,2,5,7,8;
                            lnf = LeftNeighbor[L];

                            lnf[5]
                            lnf[Range[0, 9]]



                            2



                            0, 0, 1, 2, 2, 2, 3, 3, 4, 5




                            It should be possible to modify the code to return the left neighbor that is less equal than the requested number if desired.



                            A remark on performance



                            The construction of the LeftNeighborFunction can be slow, but if you want to find the index of many numbers into the same list L, then you will only have to construct the LeftNeighborFunction once. Here is a comparison with a large list:



                            L = Sort @ RandomReal[100, 10^6];


                            The construction of the LeftNeightbor is a bit slow:



                            lnf = LeftNeighbor[L]; //RepeatedTiming



                            0.052, Null




                            But finding the index of many numbers is very fast:



                            sample = RandomReal[100, 10^3];
                            r1 = lnf[sample]; //RepeatedTiming



                            0.00020, Null




                            Compare this with one of kglr's solution:



                            r2 = pos0[L, #]& /@ sample; //RepeatedTiming



                            3.05, Null




                            Check :



                            r1 === r2



                            True







                            share|improve this answer











                            $endgroup$



                            You could use a variation of my LeftNeighbor function, although it returns the left neighbor strictly less than the number instead of less equal as in your solution:



                            LeftNeighbor[s_]:=LeftNeighborFunction[s,Nearest[s->"Index"]]
                            LeftNeighbor[s_,list_List]:=LeftNeighbor[s][list]
                            LeftNeighbor[s_, elem_]:=First@LeftNeighbor[s][elem]

                            LeftNeighborFunction[s_,nf_][list_List]:=With[n=nf[list][[All,1]],n-UnitStep[s[[n]]-list]]
                            LeftNeighborFunction[s_,nf_][elem_]:=First @ LeftNeighborFunction[s,nf][elem]

                            MakeBoxes[i:LeftNeighborFunction[s_,nf_], StandardForm] ^:= Module[

                            len=Length[s],
                            g = FirstCase[ToBoxes[nf], _GraphicsBox, GraphicsBox[Point[0,0]],Infinity]
                            ,
                            BoxForm`ArrangeSummaryBox[
                            LeftNeighborFunction,
                            i,
                            RawBoxes@g,

                            BoxForm`MakeSummaryItem["Data points: ",Length[s],StandardForm],
                            BoxForm`MakeSummaryItem["Range: ",MinMax[s],StandardForm]
                            ,
                            ,
                            StandardForm,
                            "Interpretable"->True
                            ]
                            ]


                            Then:



                            L=1,2,5,7,8;
                            lnf = LeftNeighbor[L];

                            lnf[5]
                            lnf[Range[0, 9]]



                            2



                            0, 0, 1, 2, 2, 2, 3, 3, 4, 5




                            It should be possible to modify the code to return the left neighbor that is less equal than the requested number if desired.



                            A remark on performance



                            The construction of the LeftNeighborFunction can be slow, but if you want to find the index of many numbers into the same list L, then you will only have to construct the LeftNeighborFunction once. Here is a comparison with a large list:



                            L = Sort @ RandomReal[100, 10^6];


                            The construction of the LeftNeightbor is a bit slow:



                            lnf = LeftNeighbor[L]; //RepeatedTiming



                            0.052, Null




                            But finding the index of many numbers is very fast:



                            sample = RandomReal[100, 10^3];
                            r1 = lnf[sample]; //RepeatedTiming



                            0.00020, Null




                            Compare this with one of kglr's solution:



                            r2 = pos0[L, #]& /@ sample; //RepeatedTiming



                            3.05, Null




                            Check :



                            r1 === r2



                            True








                            share|improve this answer














                            share|improve this answer



                            share|improve this answer








                            edited Jun 13 at 3:32

























                            answered Jun 13 at 3:20









                            Carl WollCarl Woll

                            84.8k3109220




                            84.8k3109220





















                                2












                                $begingroup$

                                It seems to me that the issue of how to handle inappropriate inputs is as important finding the position of an integer that is in the list being considered. Therefore, I would write something like this:



                                positionOfN[data : __Integer, n_Integer] := 
                                First[First[Position[data, n], Return[$Failed]]]
                                positionOfN[_, _] = $Failed;


                                Testing



                                data = 1, 2, 5, 7, 8;
                                positionOfN[data, 5]



                                3




                                positionOfN[data, -5]



                                $Failed




                                positionOfN[data, 5.]



                                $Failed




                                positionOfN["foo", "bar", 5]



                                $Failed




                                Note



                                If you don't want $Failed to be returned as the failure value, substitute whatever value you like for the two occurrences of $Failed.






                                share|improve this answer









                                $endgroup$

















                                  2












                                  $begingroup$

                                  It seems to me that the issue of how to handle inappropriate inputs is as important finding the position of an integer that is in the list being considered. Therefore, I would write something like this:



                                  positionOfN[data : __Integer, n_Integer] := 
                                  First[First[Position[data, n], Return[$Failed]]]
                                  positionOfN[_, _] = $Failed;


                                  Testing



                                  data = 1, 2, 5, 7, 8;
                                  positionOfN[data, 5]



                                  3




                                  positionOfN[data, -5]



                                  $Failed




                                  positionOfN[data, 5.]



                                  $Failed




                                  positionOfN["foo", "bar", 5]



                                  $Failed




                                  Note



                                  If you don't want $Failed to be returned as the failure value, substitute whatever value you like for the two occurrences of $Failed.






                                  share|improve this answer









                                  $endgroup$















                                    2












                                    2








                                    2





                                    $begingroup$

                                    It seems to me that the issue of how to handle inappropriate inputs is as important finding the position of an integer that is in the list being considered. Therefore, I would write something like this:



                                    positionOfN[data : __Integer, n_Integer] := 
                                    First[First[Position[data, n], Return[$Failed]]]
                                    positionOfN[_, _] = $Failed;


                                    Testing



                                    data = 1, 2, 5, 7, 8;
                                    positionOfN[data, 5]



                                    3




                                    positionOfN[data, -5]



                                    $Failed




                                    positionOfN[data, 5.]



                                    $Failed




                                    positionOfN["foo", "bar", 5]



                                    $Failed




                                    Note



                                    If you don't want $Failed to be returned as the failure value, substitute whatever value you like for the two occurrences of $Failed.






                                    share|improve this answer









                                    $endgroup$



                                    It seems to me that the issue of how to handle inappropriate inputs is as important finding the position of an integer that is in the list being considered. Therefore, I would write something like this:



                                    positionOfN[data : __Integer, n_Integer] := 
                                    First[First[Position[data, n], Return[$Failed]]]
                                    positionOfN[_, _] = $Failed;


                                    Testing



                                    data = 1, 2, 5, 7, 8;
                                    positionOfN[data, 5]



                                    3




                                    positionOfN[data, -5]



                                    $Failed




                                    positionOfN[data, 5.]



                                    $Failed




                                    positionOfN["foo", "bar", 5]



                                    $Failed




                                    Note



                                    If you don't want $Failed to be returned as the failure value, substitute whatever value you like for the two occurrences of $Failed.







                                    share|improve this answer












                                    share|improve this answer



                                    share|improve this answer










                                    answered Jun 13 at 3:29









                                    m_goldbergm_goldberg

                                    90.6k875203




                                    90.6k875203




















                                        user66097 is a new contributor. Be nice, and check out our Code of Conduct.









                                        draft saved

                                        draft discarded


















                                        user66097 is a new contributor. Be nice, and check out our Code of Conduct.












                                        user66097 is a new contributor. Be nice, and check out our Code of Conduct.











                                        user66097 is a new contributor. Be nice, and check out our Code of Conduct.














                                        Thanks for contributing an answer to Mathematica Stack Exchange!


                                        • Please be sure to answer the question. Provide details and share your research!

                                        But avoid


                                        • Asking for help, clarification, or responding to other answers.

                                        • Making statements based on opinion; back them up with references or personal experience.

                                        Use MathJax to format equations. MathJax reference.


                                        To learn more, see our tips on writing great answers.




                                        draft saved


                                        draft discarded














                                        StackExchange.ready(
                                        function ()
                                        StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fmathematica.stackexchange.com%2fquestions%2f200260%2ffinding-the-index-of-an-element-to-be-inserted-in-a-sorted-list%23new-answer', 'question_page');

                                        );

                                        Post as a guest















                                        Required, but never shown





















































                                        Required, but never shown














                                        Required, but never shown












                                        Required, but never shown







                                        Required, but never shown

































                                        Required, but never shown














                                        Required, but never shown












                                        Required, but never shown







                                        Required, but never shown







                                        Popular posts from this blog

                                        Get product attribute by attribute group code in magento 2get product attribute by product attribute group in magento 2Magento 2 Log Bundle Product Data in List Page?How to get all product attribute of a attribute group of Default attribute set?Magento 2.1 Create a filter in the product grid by new attributeMagento 2 : Get Product Attribute values By GroupMagento 2 How to get all existing values for one attributeMagento 2 get custom attribute of a single product inside a pluginMagento 2.3 How to get all the Multi Source Inventory (MSI) locations collection in custom module?Magento2: how to develop rest API to get new productsGet product attribute by attribute group code ( [attribute_group_code] ) in magento 2

                                        Category:9 (number) SubcategoriesMedia in category "9 (number)"Navigation menuUpload mediaGND ID: 4485639-8Library of Congress authority ID: sh85091979ReasonatorScholiaStatistics

                                        Magento 2.3: How do i solve this, Not registered handle, on custom form?How can i rewrite TierPrice Block in Magento2magento 2 captcha not rendering if I override layout xmlmain.CRITICAL: Plugin class doesn't existMagento 2 : Problem while adding custom button order view page?Magento 2.2.5: Overriding Admin Controller sales/orderMagento 2.2.5: Add, Update and Delete existing products Custom OptionsMagento 2.3 : File Upload issue in UI Component FormMagento2 Not registered handleHow to configured Form Builder Js in my custom magento 2.3.0 module?Magento 2.3. How to create image upload field in an admin form