Fastest way to check variable against two values

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • wswilson

    Fastest way to check variable against two values

    In python, I could write:

    a = 1

    if a in [1, 2]:
    do something...


    In c (and many other languages):

    int a = 1;

    if (a == 1 || a == 2) {
    do something...
    }

    Is there a shorter, cleaner syntax?
  • fred.l.kleinschmidt@boeing.com

    #2
    Re: Fastest way to check variable against two values

    On May 2, 8:06 am, wswilson <wswil...@gmail .comwrote:
    In python, I could write:
    >
    a = 1
    >
    if a in [1, 2]:
       do something...
    >
    In c (and many other languages):
    >
    int a = 1;
    >
    if (a == 1 || a == 2) {
       do something...
    >
    }
    >
    Is there a shorter, cleaner syntax?
    It depends on many things, such as what types of variables
    you are using (int, double, strings, etc.)

    In some cases, using a switch statement is useful here:

    switch(a) {
    case 1: case2:
    /*do something */
    break;
    case 3: case 4:
    /* do something else */
    break;
    default:
    /* etc. */
    break;
    }


    The above is likely to be implemented using a jump table,
    which is probably faster than the nested if's. But it
    only works if the comparisons are to constants.
    --
    Fred Kleinschmidt

    Comment

    • Bartc

      #3
      Re: Fastest way to check variable against two values


      "wswilson" <wswilson@gmail .comwrote in message
      news:06746a00-8bad-497a-81a7-5e3363bc82e9@e3 9g2000hsf.googl egroups.com...
      In python, I could write:
      >
      a = 1
      >
      if a in [1, 2]:
      do something...
      Is this supposed to be an example of a /fast/ method? I think Python creates
      an array containing 1 and 2, then searches it for a.

      Being neat and short isn't necessarily fast. However you do it in C, it will
      be faster.

      -- Bartc



      Comment

      • Eligiusz Narutowicz

        #4
        Re: Fastest way to check variable against two values

        "Bartc" <bc@freeuk.comw rites:
        "wswilson" <wswilson@gmail .comwrote in message
        news:06746a00-8bad-497a-81a7-5e3363bc82e9@e3 9g2000hsf.googl egroups.com...
        >In python, I could write:
        >>
        >a = 1
        >>
        >if a in [1, 2]:
        > do something...
        >
        Is this supposed to be an example of a /fast/ method? I think Python creates
        an array containing 1 and 2, then searches it for a.
        Nowhere did he mention "fast". He mentioned shorter cleaner syntax. And
        it is.
        >
        Being neat and short isn't necessarily fast. However you do it in C, it will
        be faster.

        Comment

        • Robert Gamble

          #5
          Re: Fastest way to check variable against two values

          On May 2, 11:43 am, Eligiusz Narutowicz<elig iuszdotn...@hot mail.com>
          wrote:
          "Bartc" <b...@freeuk.co mwrites:
          "wswilson" <wswil...@gmail .comwrote in message
          news:06746a00-8bad-497a-81a7-5e3363bc82e9@e3 9g2000hsf.googl egroups.com...
          In python, I could write:
          >
          a = 1
          >
          if a in [1, 2]:
          do something...
          >
          Is this supposed to be an example of a /fast/ method? I think Python creates
          an array containing 1 and 2, then searches it for a.
          >
          Nowhere did he mention "fast". He mentioned shorter cleaner syntax. And
          it is.
          The subject of the message was "Fastest way to check variable against
          two values".

          --
          Robert Gamble

          Comment

          • Eligiusz Narutowicz

            #6
            Re: Fastest way to check variable against two values

            Robert Gamble <rgamble99@gmai l.comwrites:
            On May 2, 11:43 am, Eligiusz Narutowicz<elig iuszdotn...@hot mail.com>
            wrote:
            >"Bartc" <b...@freeuk.co mwrites:
            "wswilson" <wswil...@gmail .comwrote in message
            >news:06746a0 0-8bad-497a-81a7-5e3363bc82e9@e3 9g2000hsf.googl egroups.com...
            >In python, I could write:
            >>
            >a = 1
            >>
            >if a in [1, 2]:
            > do something...
            >>
            Is this supposed to be an example of a /fast/ method? I think Python creates
            an array containing 1 and 2, then searches it for a.
            >>
            >Nowhere did he mention "fast". He mentioned shorter cleaner syntax. And
            >it is.
            >
            The subject of the message was "Fastest way to check variable against
            two values".
            It did indeed . I am sorry - I really only listened to the body of the
            message which made it pretty clear. I can think that he is meaning
            "fastest to type" in the subject as was clear from the body.

            Comment

            • wswilson

              #7
              Re: Fastest way to check variable against two values

              On May 2, 11:45 am, Robert Gamble <rgambl...@gmai l.comwrote:
              On May 2, 11:43 am, Eligiusz Narutowicz<elig iuszdotn...@hot mail.com>
              wrote:
              >
              "Bartc" <b...@freeuk.co mwrites:
              "wswilson" <wswil...@gmail .comwrote in message
              >news:06746a0 0-8bad-497a-81a7-5e3363bc82e9@e3 9g2000hsf.googl egroups.com....
              >In python, I could write:
              >
              >a = 1
              >
              >if a in [1, 2]:
              >  do something...
              >
              Is this supposed to be an example of a /fast/ method? I think Python creates
              an array containing 1 and 2, then searches it for a.
              >
              Nowhere did he mention "fast". He mentioned shorter cleaner syntax. And
              it is.
              >
              The subject of the message was "Fastest way to check variable against
              two values".
              >
              --
              Robert Gamble
              Thanks for the help guys. I did mention fast in the title but I meant
              clean and short (as in the post). Sorry :-)

              Comment

              • Walter Roberson

                #8
                Re: Fastest way to check variable against two values

                In article <06746a00-8bad-497a-81a7-5e3363bc82e9@e3 9g2000hsf.googl egroups.com>,
                wswilson <wswilson@gmail .comwrote:
                >In python, I could write:
                >a = 1
                >if a in [1, 2]:
                do something...
                >In c (and many other languages):
                >int a = 1;
                >if (a == 1 || a == 2) {
                do something...
                >}
                >Is there a shorter, cleaner syntax?
                If none of the values are 0 and none exceed the maximum char:

                char ac[] = {1,2};

                int a = 1;

                if (strchar(ac, a)) {
                do something...
                }

                --
                Q: Why did the chicken cross the Mobius strip?

                A: There were manifold reasons.

                Comment

                • Robert Gamble

                  #9
                  Re: Fastest way to check variable against two values

                  On May 2, 11:06 am, wswilson <wswil...@gmail .comwrote:
                  In python, I could write:
                  >
                  a = 1
                  >
                  if a in [1, 2]:
                  do something...
                  >
                  In c (and many other languages):
                  >
                  int a = 1;
                  >
                  if (a == 1 || a == 2) {
                  do something...
                  >
                  }
                  >
                  Is there a shorter, cleaner syntax?
                  In your example Python creates a list of values and the in operator
                  compares each element of this list to "a" until it finds such a value
                  or the list is exhausted. The C method you propose won't likely be
                  any slower. As far as shorter/cleaner, it depends. There isn't a
                  better mechanism built into the language but if you are doing
                  operations like this a lot on multiple values you may want to write a
                  function to do what the "in" operator does in python, for example:

                  ==cut==
                  int in_list (int search, int *p, size_t size)
                  {
                  for (size_t i = 0; i < size; i++)
                  if (search == p[i]) return 1;
                  return 0;
                  }

                  int main (void)
                  {
                  if (in_list(1, (int []){1, 2, 3, 4, 5}, 5))
                  puts("element is in list");
                  else
                  puts("element is not in list");

                  return 0;
                  }
                  ==cut==

                  In this (C99) example we define a function in_list that takes an
                  integer to search for, an array of integers to search, and the size of
                  the array; it returns 1 if the searched for item was found, 0 if it
                  was not. We call it with a compound literal as a "shorter/cleaner"
                  method than creating a separate array which you would have to do if
                  using C89. The two major problems with this function are that it only
                  works for ints and it is easy to specify an incorrect size with longer
                  lists. You could generalize the in_list function to work with any
                  type by modifying it to receive a comparison function and making the
                  appropriate changes to the types passed on. To alleviate the second
                  issue you could pass in an array of pointers to values using NULL to
                  terminate the list, this can get messy for non-string types though. I
                  have used similar methods successfully in the past, whether it is
                  "clean" is a matter of opinion.

                  --
                  Robert Gamble

                  Comment

                  • Robert Gamble

                    #10
                    Re: Fastest way to check variable against two values

                    On May 2, 12:22 pm, rober...@ibd.nr c-cnrc.gc.ca (Walter Roberson)
                    wrote:
                    In article <06746a00-8bad-497a-81a7-5e3363bc8...@e3 9g2000hsf.googl egroups.com>,
                    >
                    wswilson <wswil...@gmail .comwrote:
                    In python, I could write:
                    a = 1
                    if a in [1, 2]:
                    do something...
                    In c (and many other languages):
                    int a = 1;
                    if (a == 1 || a == 2) {
                    do something...
                    }
                    Is there a shorter, cleaner syntax?
                    >
                    If none of the values are 0 and none exceed the maximum char:
                    >
                    char ac[] = {1,2};
                    >
                    You are going to need the terminating null character:

                    char ac[] = {1, 2, 0};
                    int a = 1;
                    >
                    if (strchar(ac, a)) {
                    It's strchr, not strchar.
                    do something...
                    >
                    }
                    --
                    Robert Gamble

                    Comment

                    • Bartc

                      #11
                      Re: Fastest way to check variable against two values


                      "wswilson" <wswilson@gmail .comwrote in message
                      news:06746a00-8bad-497a-81a7-5e3363bc82e9@e3 9g2000hsf.googl egroups.com...
                      In python, I could write:
                      >
                      a = 1
                      >
                      if a in [1, 2]:
                      do something...
                      >
                      >
                      In c (and many other languages):
                      >
                      int a = 1;
                      >
                      if (a == 1 || a == 2) {
                      do something...
                      }
                      If you want something short then, try this macro:

                      #define in(a,b,c) ((a)==(b) | (a)==(c))

                      And use it like this:

                      if (in(a,1,2))...

                      (Although, I don't use macros much and there are probably some pitfalls. You
                      may also like to use || instead of |)

                      -- Bartc



                      Comment

                      • Peter Nilsson

                        #12
                        Re: Fastest way to check variable against two values

                        wswilson wrote:
                        In c (and many other languages):
                        >
                        int a = 1;
                        >
                        if (a == 1 || a == 2) {
                        do something...
                        }
                        >
                        Is there a shorter, cleaner syntax?
                        Shorter, but not necessarily better...

                        if (a - 1u < 2)

                        --
                        Peter

                        Comment

                        • user923005

                          #13
                          Re: Fastest way to check variable against two values

                          On May 2, 8:06 am, wswilson <wswil...@gmail .comwrote:
                          In python, I could write:
                          >
                          a = 1
                          >
                          if a in [1, 2]:
                             do something...
                          >
                          In c (and many other languages):
                          >
                          int a = 1;
                          >
                          if (a == 1 || a == 2) {
                             do something...
                          >
                          }
                          >
                          Is there a shorter, cleaner syntax?
                          If the list of items contains a small maximum, you can use:

                          /*
                          7.21.5.4 The strpbrk function
                          Synopsis
                          1 #include <string.h>
                          char *strpbrk(const char *s1, const char *s2);
                          Description
                          2 The strpbrk function locates the first occurrence in the string
                          pointed to by s1 of any character from the string pointed to by s2.
                          Returns
                          3 The strpbrk function returns a pointer to the character, or a
                          null pointer if no character from s2 occurs in s1.
                          */
                          #include <string.h>
                          #include <stdio.h>

                          /* You can't find zero in the list, and the last entry must be 0: */
                          static const unsigned char list[] =
                          {
                          1, 2, 3, 4, 5, 6, 7, 8, 9, 21, 23, 25, 'a', 'A', 'Z', 'Q', 0
                          };

                          int main(void)
                          {
                          char string[256];
                          char *where;

                          puts("Enter a string:");
                          fflush(stdout);
                          fgets(string, sizeof string, stdin);
                          where = strpbrk(string, list);
                          if (where)
                          printf("first match is %d.\n", (int) *where);
                          else
                          puts("No characters match.");
                          return 0;
                          }
                          /*
                          Enter a string:
                          zzzAn
                          first match is 65.
                          */

                          Comment

                          • Serve L

                            #14
                            Re: Fastest way to check variable against two values


                            "wswilson" <wswilson@gmail .comschreef in bericht
                            news:06746a00-8bad-497a-81a7-5e3363bc82e9@e3 9g2000hsf.googl egroups.com...
                            In python, I could write:
                            >
                            a = 1
                            >
                            if a in [1, 2]:
                            do something...
                            >
                            >
                            In c (and many other languages):
                            >
                            int a = 1;
                            >
                            if (a == 1 || a == 2) {
                            do something...
                            }
                            >
                            Is there a shorter, cleaner syntax?
                            Its funny to see what you all come up with while the answer is "no there is
                            no cleaner way as in python"

                            Comment

                            • Paul Hsieh

                              #15
                              Re: Fastest way to check variable against two values

                              On May 2, 8:21 am, "Bartc" <b...@freeuk.co mwrote:
                              "wswilson" <wswil...@gmail .comwrote in message
                              news:06746a00-8bad-497a-81a7-5e3363bc82e9@e3 9g2000hsf.googl egroups.com...
                              In python, I could write:
                              >
                              a = 1
                              >
                              if a in [1, 2]:
                              do something...
                              >
                              Is this supposed to be an example of a /fast/ method? I think Python creates
                              an array containing 1 and 2, then searches it for a.
                              I wouldn't be surprised if this was faster. In Python, or any
                              interpreted byte-code executed language, reducing the number of byte-
                              codes is usually more important than the performance of the byte-code
                              itself. If the vector [1,2] is created at interpretation time (I
                              don't know if it is or it isn't), then certainly this is probably the
                              fastest approach in python.
                              Being neat and short isn't necessarily fast. However you do it in C, it will
                              be faster.
                              Indeed. All benchmarks I have seen and written myself put C at
                              between 50 and 200 times faster than Python on a wide variety of
                              code. So its always humorous when I hear about things like "Iron
                              Python" which are supposed to be remarkable for making Python execute
                              about 3 times faster.

                              --
                              Paul Hsieh
                              Pobox has been discontinued as a separate service, and all existing customers moved to the Fastmail platform.


                              Comment

                              Working...