473,402 Members | 2,053 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,402 software developers and data experts.

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?
Jun 27 '08 #1
17 3232
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
Jun 27 '08 #2

"wswilson" <ws******@gmail.comwrote in message
news:06**********************************@e39g2000 hsf.googlegroups.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

Jun 27 '08 #3
"Bartc" <bc@freeuk.comwrites:
"wswilson" <ws******@gmail.comwrote in message
news:06**********************************@e39g2000 hsf.googlegroups.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.
Jun 27 '08 #4
On May 2, 11:43 am, Eligiusz Narutowicz<eligiuszdotn...@hotmail.com>
wrote:
"Bartc" <b...@freeuk.comwrites:
"wswilson" <wswil...@gmail.comwrote in message
news:06**********************************@e39g2000 hsf.googlegroups.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
Jun 27 '08 #5
Robert Gamble <rg*******@gmail.comwrites:
On May 2, 11:43 am, Eligiusz Narutowicz<eligiuszdotn...@hotmail.com>
wrote:
>"Bartc" <b...@freeuk.comwrites:
"wswilson" <wswil...@gmail.comwrote in message
news:06**********************************@e39g200 0hsf.googlegroups.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.

Jun 27 '08 #6
On May 2, 11:45*am, Robert Gamble <rgambl...@gmail.comwrote:
On May 2, 11:43 am, Eligiusz Narutowicz<eligiuszdotn...@hotmail.com>
wrote:
"Bartc" <b...@freeuk.comwrites:
"wswilson" <wswil...@gmail.comwrote in message
>news:06**********************************@e39g200 0hsf.googlegroups.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 :-)
Jun 27 '08 #7
In article <06**********************************@e39g2000hsf. googlegroups.com>,
wswilson <ws******@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.
Jun 27 '08 #8
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
Jun 27 '08 #9
On May 2, 12:22 pm, rober...@ibd.nrc-cnrc.gc.ca (Walter Roberson)
wrote:
In article <06746a00-8bad-497a-81a7-5e3363bc8...@e39g2000hsf.googlegroups.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
Jun 27 '08 #10

"wswilson" <ws******@gmail.comwrote in message
news:06**********************************@e39g2000 hsf.googlegroups.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

Jun 27 '08 #11
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
Jun 27 '08 #12
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.
*/
Jun 27 '08 #13

"wswilson" <ws******@gmail.comschreef in bericht
news:06**********************************@e39g2000 hsf.googlegroups.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"

Jun 27 '08 #14
On May 2, 8:21 am, "Bartc" <b...@freeuk.comwrote:
"wswilson" <wswil...@gmail.comwrote in message
news:06**********************************@e39g2000 hsf.googlegroups.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
http://www.pobox.com/~qed/
http://bstring.sf.net/
Jun 27 '08 #15

"Paul Hsieh" <we******@gmail.comwrote in message
news:c4**********************************@b9g2000p rh.googlegroups.com...
On May 2, 8:21 am, "Bartc" <b...@freeuk.comwrote:
>"wswilson" <wswil...@gmail.comwrote in message
news:06**********************************@e39g200 0hsf.googlegroups.com...
In python, I could write:
a = 1
if a in [1, 2]:
do something...
>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.
I'd been developing interpreted languages for years to go with my
applications.

For pure integer code, I always found it difficult to break the 10x slower
barrier compared with, say, C (although I'm currently working on that!).

But, I had decided originally that when the interpreted language was used
properly, it should only be between 1x to 2x as slow as a compiled
equivalent, and in most cases this was achieved, while making development a
delight because it was so easy.

Even forgetting library calls, an interpreted language doing high level
things (working with strings, entire arrays, etc) can compare well with pure
C.

--
Bartc

Jun 27 '08 #16
"Bartc" <bc@freeuk.comwrote in message
news:0T******************@text.news.virginmedia.co m...
>
"Paul Hsieh" <we******@gmail.comwrote in message
news:c4**********************************@b9g2000p rh.googlegroups.com...
>On May 2, 8:21 am, "Bartc" <b...@freeuk.comwrote:
>>"wswilson" <wswil...@gmail.comwrote in message
news:06**********************************@e39g20 00hsf.googlegroups.com...
In python, I could write:

a = 1

if a in [1, 2]:
do something...
>>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.

I'd been developing interpreted languages for years to go with my
applications.

For pure integer code, I always found it difficult to break the 10x slower
barrier compared with, say, C (although I'm currently working on that!).

But, I had decided originally that when the interpreted language was used
properly, it should only be between 1x to 2x as slow as a compiled
equivalent, and in most cases this was achieved, while making development
a delight because it was so easy.

Even forgetting library calls, an interpreted language doing high level
things (working with strings, entire arrays, etc) can compare well with
pure C.
Most of the time, scripting languages are used as drivers for compiled
programs. For this purpose, they really excel. I don't know why people
want to pan languages like Python or Perl because they make life so much
easier.

There are definitely projects where I would choose to write the major
portion in (for instance) Java. Nothing wrong with that. If it cuts
development cost and maintenance effort and is still fast enough, then it is
foolish to choose another method that might be a tiny bit faster but cost a
lot more.

Computer languages all have their strengths and weaknesses. There is no
"one size fits all" language that I know of. Each one has its own area
where it is the better choice.

IMO-YMMV
** Posted from http://www.teranews.com **
Jun 27 '08 #17
In article <0T******************@text.news.virginmedia.com> ,
Bartc <bc@freeuk.comwrote:
>For pure integer code, I always found it difficult to break the 10x slower
barrier compared with, say, C (although I'm currently working on that!).

But, I had decided originally that when the interpreted language was used
properly, it should only be between 1x to 2x as slow as a compiled
equivalent, and in most cases this was achieved, while making development a
delight because it was so easy.

Even forgetting library calls, an interpreted language doing high level
things (working with strings, entire arrays, etc) can compare well with pure
C.
Interpreted languages doing high level things are most likely
translating one or two language primitives into "call a big chunk of
compiled code", and when you're doing that the return on investment for
spending extra time optimizing the compiled code goes way up, so it
usually ends up faster than writing the code directly in C. (Unless
you do something dumb like using an expensive language primitive to do
an operation that can be done cheaply without it.)
Compiling to native code wins easily when you can't reduce code that
does nontrivial things to a short sequence of language primitives,
though, since the interpreter has to stop and look up what to do again
after every interpreted-language instruction, and compiled code can
skip that part.

I work with people who like to write everything in Matlab.
For what it's good at (pretty much any easy-to-describe numerical
computation), I won't even bother trying to make my C run as fast as
the Matlab runtime. I occasionally convert Matlab code to something we
can call from a C program without having to ship with the Matlab
runtime, but if it's performance-critical I'll tell them to just ship
the Matlab code.
But occasionally they'll come to me with code that loops over a big
array doing something that there aren't Matlab primitives to do
array-at-a-time and that's way too slow, and when that happens I can
easily get a factor of five or ten speedup even before I ask the
compiler to optimize it (i.e. working with one hand tied behind my
back), just by writing C code to do the same thing.
Good interpreted languages[1] make it easy to write compiled-to-native
code and call it from the interpreted scripts, which essentially lets
the user-programmer write their own primitives. Though making it as
easy to optimize as aggressively as they do for the builtin ones is a
little bit harder, and well beyond the scope of what the people who
sell the interpreted languages are trying to do.
dave

[1] Matlab meets this criterion for "good" (it's the only one I've had
reason to find out about).

--
Dave Vandervies dj3vande at eskimo dot com
Have you checked under your desk for stray sixes?
So *that's* where the beast is!
--Normal L. DeForest and Stuart Lamble in the scary devil monastery
Jun 27 '08 #18

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

0
by: richardkreidl | last post by:
What I'd like to do is to check the values in an element if they're greater than a certain time and if they are, then change the font color of the time. I have about 10 elements that I will check...
60
by: Julie | last post by:
What is the *fastest* way in .NET to search large on-disk text files (100+ MB) for a given string. The files are unindexed and unsorted, and for the purposes of my immediate requirements, can't...
11
by: hoopsho | last post by:
Hi Everyone, I am trying to write a program that does a few things very fast and with efficient use of memory... a) I need to parse a space-delimited file that is really large, upwards fo a...
5
by: Soren S. Jorgensen | last post by:
Hi, In my app I've got a worker thread (background) doing some calculations based upon user input. A new worker thread might be invoked before the previous worker thread has ended, and I wan't...
19
by: Taras_96 | last post by:
Hi everyone, How do you detect that a form element has been changed? This thread: ...
6
by: Klaas Vantournhout | last post by:
Hi, I have a question, which is just out of interest. What is the fastest way to do an odd/even check with c++ and if needed assembler. Assume n is an unsigned integer like type (unsigned...
4
by: giftson.john | last post by:
Hi, I am creating an application which migrates all documents from one repository to another repository. Before migration i have to verify all the documents are unique. No duplicates has to be...
10
by: BostonNole | last post by:
Using Visual Studio 2005, .NET 2.0 and VB.NET: I am looking for the fastest possible way to import a very large fixed width file (over 6 million records and over 1.2 GB file size) into a...
21
by: Pieter | last post by:
Hi, I need some type of array/list/... In which I can store objects together with a unique key. The most important thing is performance: I will need to do the whole time searches in the list of...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.