The snippets are under the CC-BY-SA license.

Creative Commons Attribution-ShareAlike 3.0

Logo

Programming-Idioms.org

  • The snippets are under the CC-BY-SA license.
  • Please consider keeping a bookmark
  • (instead of printing)
C Python
1
Print a literal string on standard output
printf("Hello World\n");
print("Hello World")
Alternative implementation:
print('Hello World')
2
Loop to execute some code a constant number of times
for (int i = 0; i < 10; i++) {
    printf("%d", "Hello\n");
}
for _ in range(10):
    print("Hello")
Alternative implementation:
print("Hello\n"*10)
Alternative implementation:
i = 0
while i < 10:
    print('Hello')
    i += 1
Alternative implementation:
def f(): print('Hello')
for x in range(10): f()
Alternative implementation:
f = lambda: print('Hello')
for x in range(10): f()
Alternative implementation:
for x in repeat('Hello', 10): print(x)
Alternative implementation:
www
3
Like a function which doesn't return any value, thus has only side effects (e.g. Print to standard output)
void finish(void) {
    printf("My job here is done.\n");
}
def finish(name):
    print(f'My job here is done. Goodbye {name}')
Alternative implementation:
f = lambda: print('abc')
f()
4
Create a function which returns the square of an integer
int square(int x){
  return x*x;
}
def square(x):
    return x*x
Alternative implementation:
def square(x):
    return x**2
Alternative implementation:
square = lambda x: x * x
5
Declare a container type for two floating-point numbers x and y
typedef struct {
  double x;
  double y;
} Point;
@dataclass
class Point:
    x: float
    y: float
Alternative implementation:
Point = namedtuple("Point", "x y")
Alternative implementation:
point = {'x': 1.2, 'y': 3.4}
Alternative implementation:
class Point:
    def __init__(self, x, y):
        self.x, self.y = x, y
Alternative implementation:
point = dict(x=1.2, y=3.4)
6
Do something with each item x of the list (or array) items, regardless indexes.
for (unsigned int i = 0 ; i < items_length ; ++i){
        Item* x = &(items[i]);
	DoSomethingWith(x);
}
Alternative implementation:
for (size_t i = 0; i < sizeof(items) / sizeof(items[0]); i++) {
	DoSomethingWith(&items[i]);
}
for x in items:
        doSomething( x )
Alternative implementation:
[do_something(x) for x in items]
Alternative implementation:
f = lambda x: ...
for x in items: f(x)
7
Print each index i with its value x from an array-like collection items
for (size_t i = 0; i < n; i++) {
  printf("Item %d = %s\n", i, toString(items[i]));
}
for i, x in enumerate(items):
    print(i, x)
Alternative implementation:
print(*enumerate(items))
8
Create a new map object x, and provide some (key, value) pairs as initial content.
ENTRY a = {"foo", "twenty"};
ENTRY b = {"bar", "three"};
if (hcreate (23)) {
    hsearch(a, ENTER);
    hsearch(b, ENTER);
}
x = {"one" : 1, "two" : 2}
Alternative implementation:
x = dict(a=1, b=2, c=3)
9
The structure must be recursive because left child and right child are binary trees too. A node has access to children nodes, but not to its parent.
struct treenode{
  int value;
  struct treenode* left;
  struct treenode* right;
}
class Node:
	def __init__(self, data):
		self.data = data
		self.left = None
		self.right = None
Alternative implementation:
class Node:
  def __init__(self, data, left_child, right_child):
    self.data = data
    self._left_child = left_child
    self._right_child = right_child
10
Generate a random permutation of the elements of list x
srand(time(NULL));
for (int i = 0; i < N-1; ++i)
{
    int j = rand() % (N-i) + i;
    int temp = x[i];
    x[i] = x[j];
    x[j] = temp;
}
shuffle(x)
Alternative implementation:
random.shuffle(x)
11
The list x must be non-empty.
x[rand() % x_length];
random.choice(x)
Alternative implementation:
if x: z = choice(x)
12
Check if the list contains the value x.
list is an iterable finite container.
bool contains(int x, int* list, size_t list_len) {
    for (int i=0 ; i<list_len ; i++)
        if (list[i] == x)
            return true;
    return false;
}
x in list
14
Pick a random number greater than or equals to a, strictly inferior to b. Precondition : a < b.
double pick(double a, double b)
{
	return a + (double)rand() / ((double)RAND_MAX * (b - a));
}
random.uniform(a,b)
15
Pick a random integer greater than or equals to a, inferior or equals to b. Precondition : a < b.
int pick(int a, int b)
{
	int upper_bound = b - a + 1;
	int max = RAND_MAX - RAND_MAX % upper_bound;
	int r;

	do {
		r = rand();
	} while (r >= max);
	r = r % upper_bound;
	return a + r;
}
random.randint(a,b)
17
The structure must be recursive. A node may have zero or more children. A node has access to its children nodes, but not to its parent.
typedef struct node_s
{
    int value;
    struct node_s *nextSibling;
    struct node_s *firstChild;
} node_t;
class Node:
    def __init__(self, value, *children):
        self.value = value
        self.children = list(children)
19
Reverse the order of the elements of the list x.
This may reverse "in-place" and destroy the original ordering.
int *p1 = x;
int *p2 = x + N-1;

while (p1 < p2)
{
    int temp = *p1;
    *(p1++) = *p2;
    *(p2--) = temp;
}
x = reversed(x)
Alternative implementation:
y = x[::-1]
Alternative implementation:
x.reverse()
20
Implement a function search which looks for item x in a 2D matrix m.
Return indices i, j of the matching cell.
Think of the most idiomatic way in the language to return the two values at the same time.
void search(void ***m,void *x,size_t memb_size,int len_x,int len_y,int *i,int *j)
{
	typedef void *m_type[len_x][len_y];
	m_type *m_ref=(m_type*)m;

	for(*i=0;*i<len_x;*i+=1)
	{
		for(*j=0;*j<len_y;*j+=1)
		{
			if(!memcmp((*m_ref)[*i][*j],x,memb_size))
			{
				return;
			}
		}
	}
	*i=*j=-1;
}
def search(m, x):
    for idx, item in enumerate(m):
        if x in item:
            return idx, item.index(x)
Alternative implementation:
def search(x, m):
    for i, M in enumerate(m):
        for j, N in enumerate(M):
            if N == x: return (i, j)
21
Swap the values of the variables a and b
a^=b;
b^=a;
a^=b;
Alternative implementation:
b = a + b
a = b - a
b = b - a
a, b = b, a
Alternative implementation:
a =int(input("enter a number"))
b =int(input("enter b number")) 
a, b = b, a
 
print("Value of a:", a)
print("Value of a", b)
22
Extract the integer value i from its string representation s (in radix 10)
int i = atoi(s);
Alternative implementation:
i = (int)strtol(s, (char **)NULL, 10);
i = int(s)
23
Given a real number x, create its string representation s with 2 decimal digits following the dot.
sprintf(s, "%.2f", x);
s =  '{:.2f}'.format(x)
Alternative implementation:
s = f'{x:.2f}'
Alternative implementation:
s = '%.2f' % x
Alternative implementation:
s = format(x, '.2f')
24
Declare a new string s and initialize it with the literal value "ネコ" (which means "cat" in japanese)
const char * s = "ネコ";
s = "ネコ"
26
Declare and initialize a matrix x having m rows and n columns, containing real numbers.
double **x=malloc(m*sizeof(double *));
int i;
for(i=0;i<m;i++)
	x[i]=malloc(n*sizeof(double));
Alternative implementation:
const int m = 2;
const int n = 3;
double x[m][n];
x = [[0] * n for _ in range(m)]
Alternative implementation:
x = []
for i in range(m):
    x.append([.0] * n)
Alternative implementation:
x = [*repeat([.0] * n, m)]
27
Declare and initialize a 3D array x, having dimensions boundaries m, n, p, and containing real numbers.
double ***x=malloc(m*sizeof(double **));
int i,j;
for(i=0;i<m;i++)
{
	x[i]=malloc(n*sizeof(double *));
	for(j=0;j<n;j++)
	{
		x[i][j]=malloc(p*sizeof(double));
	}
}
x = [[[0 for k in range(p)] for j in range(n)] for i in range(m)]
Alternative implementation:
x = numpy.zeros((m,n,p))
Alternative implementation:
x = []
for a in range(m):
    t = []
    for b in range(n):
        t.append([.0] * p)
    x.append(t)
Alternative implementation:
f = lambda: [*repeat([.0] * p, m)]
x = [*repeat(f(), n)]
28
Sort the elements of the list (or array-like collection) items in ascending order of x.p, where p is a field of the type Item of the objects in items.
int compareProp (const void *a, const void *b)
{
    return (*(const Item**)a)->p - (*(const Item**)b)->p;
}

qsort(items, N, sizeof(Item*), compareProp);
items = sorted(items, key=lambda x: x.p)
Alternative implementation:
items = sorted(items, key=attrgetter('p'))
31
Create the recursive function f which returns the factorial of the non-negative integer i, calculated from f(i-1)
unsigned int f(unsigned int i)
{
	return i?i*f(i-1):1;
}
def f(i):
   if i == 0:
       return 1
   else:
       return i * f(i-1)
32
Create function exp which calculates (fast) the value x power n.
x and n are non-negative integers.
unsigned int exp(unsigned int x,unsigned int n)
{
    if(n==0)
    {
        return 1;
    }
    if(n==1)
    {
        return x;
    }
    if(!(n%2))
    {
        return exp(x*x,n/2);
    }
    return x*exp(x*x,(n-1)/2);
}
def exp(x, n):
        return x**n
38
Find substring t consisting in characters i (included) to j (excluded) of string s.
Character indices start at 0 unless specified otherwise.
Make sure that multibyte characters are properly handled.
char *t=malloc((j-i+1)*sizeof(char));
strncpy(t,s+i,j-i);
t = s[i:j]
Alternative implementation:
t = s[slice(i, j)]
39
Set the boolean ok to true if the string word is contained in string s as a substring, or to false otherwise.
int ok = strstr(s,word) != NULL;
ok = word in s
41
Create the string t containing the same characters as the string s, in reverse order.
The original string s must remain unaltered. Each character must be handled correctly regardless its number of bytes in memory.
char *strrev(char *s)
{
	size_t len = strlen(s);
	char *rev = malloc(len + 1);

	if (rev) {
		char *p_s = s + len - 1;
		char *p_r = rev;

		for (; len > 0; len--)
			*p_r++ = *p_s--;
		*p_r = '\0';
	}
	return rev;
}
t = s[::-1]
Alternative implementation:
t = ''.join(reversed(s))
42
Print each item v of list a which is not contained in list b.
For this, write an outer loop to iterate on a and an inner loop to iterate on b.
int *v = a;
while (v < a+N)
{
    int *w = b;
    while (w < b+M)
    {
        if (*v == *w)
            goto OUTER;
        
        ++w;
    }
    printf("%d\n", *v);
    
    OUTER: ++v;
}
for v in a:
    try:
        for u in b:
            if v == u:
                raise Exception()
        print(v)
    except Exception:
        continue
Alternative implementation:
for v in a:
  keep = True
  for w in b:
    if w == v:
      keep = False
      break
  if keep:
    print(v)
Alternative implementation:
z = False
for x in a:
    for y in b:
        if y == x:
            z = True
            break
    if not z: print(x)
    z = False
43
Look for a negative value v in 2D integer matrix m. Print it and stop searching.
int i,j;
for(i=0;i<sizeof(m)/sizeof(*m);i++)
{
	for(j=0;j<sizeof(*m)/sizeof(**m);j++)
	{
		if(m[i][j]<0)
		{
			printf("%d\n",m[i][j]);
			goto end;
		}
	}
}
end:
class BreakOuterLoop (Exception): pass

try:
    position = None
    for row in m:
        for column in m[row]:
            if m[row][column] == v:
                position = (row, column)
                raise BreakOuterLoop
except BreakOuterLoop:
    pass
Alternative implementation:
def loop_breaking(m, v): 
    for i, row in enumerate(m): 
        for j, value in enumerate(row): 
            if value == v: 
                return (i, j)
    return None

print(loop_breaking(([1,2,3],[4,5,6],[7,8,9]), 6))
Alternative implementation:
matrix = [[1,2,3],[4,-5,6],[7,8,9]]
try:
    print(next(i for i in chain.from_iterable(matrix) if i < 0))
except StopIteration:
    pass
Alternative implementation:
b = False
for r in m:
    for i in r:
        if i < 0:
            print(i)
            b = True
    if b: break
Alternative implementation:
z = False
for a in m:
    for b in a:
        if z := b < 0:
            print(b)
            break
    if z: break
45
Sleep for 5 seconds in current thread, before proceeding with the next instructions.
usleep(5000000);
Alternative implementation:
Sleep(5000);
time.sleep(5)
48
Assign to variable s a string literal consisting in several lines of text, including newlines.
char *s = "Huey\n"
          "Dewey\n"
          "Louie";
s = """Huey
Dewey
Louie"""
Alternative implementation:
s = ('line 1\n'
     'line 2\n'
     'line 3\n'
     'line 4')
49
Build list chunks consisting in substrings of the string s, separated by one or more space characters.
chunks[0] = strtok(s, " ");
for (int i = 1; i < N; ++i)
{
    chunks[i] = strtok(NULL, " ");
    
    if (!chunks[i])
        break;
}
chunks = s.split()
Alternative implementation:
chunks = split(' +', s)
50
Write a loop that has no end clause.
forever {
	// Do something
}
Alternative implementation:
for(;;){
	// Do something
}
Alternative implementation:
while(1){
	// Do something
}
Alternative implementation:
loop:
	goto loop;
while True:
    pass
Alternative implementation:
while 1: ...
53
Concatenate elements of string list x joined by the separator ", " to create a single string y.
#define DELIM ", "
#define L 64

char y[L] = {'\0'};

for (int i = 0; i < N; ++i)
{
    if (i && x[i][0])
        strcat(y, DELIM);
    
    strcat(y, x[i]);
}
y = ', '.join(x)
Alternative implementation:
y = ', '.join(map(str, x))
Alternative implementation:
f = lambda a, b: f'{a}, {b}'
y = reduce(f, x)
54
Calculate the sum s of the integer list or array x.
int i,s;
for(i=s=0;i<n;i++)
{
	s+=x[i];
}
Alternative implementation:
int sum = 0;
for (int i = 0; i < n; ++i) {
  sum += x[i];
}
s = sum(x)
Alternative implementation:
s = reduce(add, x)
55
Create the string representation s (in radix 10) of the integer value i.
char s[0x1000]={};
itoa(i,s,10);
s = str(i)
58
Create the string lines from the content of the file with filename f.
FILE *file;
size_t len=0;
char *lines;
assert(file=fopen(f,"rb"));
assert(lines=malloc(sizeof(char)));

while(!feof(file))
{
	assert(lines=realloc(lines,(len+0x1000)*sizeof(char)));
	len+=fread(lines,1,0x1000,file);
}

assert(lines=realloc(lines,len*sizeof(char)));
Alternative implementation:
int err = 0;
int fd = 0;
void * ptr = NULL;
struct stat st;
if ((fd = open (f, O_RDONLY))
&& (err = fstat (fd, &st)) == 0
&& (ptr = mmap (NULL, st.st_size, PROT_READ, MAP_PRIVATE, fd, 0)) != -1) {
    const char * lines = ptr;
    puts (lines);
    munmap (ptr, st.st_size);
    close (fd);
}
lines = open(f).read()
Alternative implementation:
with open(f) as fo:
    lines = fo.read()
59
Print the message "x is negative" to standard error (stderr), with integer x value substitution (e.g. "-2 is negative").
fprintf(stderr,"%d is negative\n",x);
print(x, "is negative", file=sys.stderr)
60
Assign to x the string value of the first command line parameter, after the program name.
void main(int argc, char *argv[])
{
    char *x = argv[1];
}
x = sys.argv[1]
61
Assign to the variable d the current date/time value, in the most standard type.
time_t d=time(0);
d = datetime.datetime.now()
62
Set i to the first position of string y inside string x, if exists.

Specify if i should be regarded as a character index or as a byte index.

Explain the behavior when y is not contained in x.
int i=(int)(x-strstr(x,y));
i = x.find(y)
65
From the real value x in [0,1], create its percentage string representation s with one digit after decimal point. E.g. 0.15625 -> "15.6%"
char s[7];
sprintf(s, "%.2lf%%", x * 100);
s = '{:.1%}'.format(x)
Alternative implementation:
s = f"{x:.01%}"
Alternative implementation:
s = '%.1f%%' % (x * 100)
Alternative implementation:
s = format(x, '.1%')
67
Calculate binom(n, k) = n! / (k! * (n-k)!). Use an integer type able to handle huge numbers.
long long binom(long long n, long long k){
  long long outp = 1;
  for(long long i = n - k + 1; i <= n; ++i) outp *= i;
  for(long long i = 2; i <= k; ++i) outp /= i;
  return outp;
}
def binom(n, k):
    return math.factorial(n) // math.factorial(k) // math.factorial(n - k)
Alternative implementation:
def binom(n, k):
    return math.comb(n, k)
69
Use seed s to initialize a random generator.

If s is constant, the generator output will be the same each time the program runs. If s is based on the current value of the system clock, the generator output will be different each time.
srand(s);
rand = random.Random(s)
70
Get the current datetime and provide it as a seed to a random generator. The generator sequence will be different at each run.
srand((unsigned)time(0));
rand = random.Random()
71
Basic implementation of the Echo program: Print all arguments except the program name, separated by space, followed by newline.
The idiom demonstrates how to skip the first argument if necessary, concatenate arguments as strings, append newline and print it to stdout.
int main(int argc, char *argv[])
{
    while (*++argv) {
        printf("%s", *argv);
        if (argv[1]) printf(" ");
    }
    printf("\n");
    return EXIT_SUCCESS;
}
print(' '.join(sys.argv[1:]))
Alternative implementation:
print(*argv[1:])
74
Compute the greatest common divisor x of big integers a and b. Use an integer type able to handle huge numbers.
mpz_t _a, _b, _x;
mpz_init_set_str(_a, "123456789", 10);
mpz_init_set_str(_b, "987654321", 10);
mpz_init(_x);

mpz_gcd(_x, _a, _b);
gmp_printf("%Zd\n", _x);
x = gcd(a, b)
Alternative implementation:
x = math.gcd(a, b)
75
Compute the least common multiple x of big integers a and b. Use an integer type able to handle huge numbers.
mpz_t _a, _b, _x;
mpz_init_set_str(_a, "123456789", 10);
mpz_init_set_str(_b, "987654321", 10);
mpz_init(_x);

mpz_lcm(_x, _a, _b);
gmp_printf("%Zd\n", _x);
x = (a*b)//gcd(a, b)
Alternative implementation:
x = math.lcm(a, b)
77
Declare a complex x and initialize it with value (3i - 2). Then multiply it by i.
float complex _x = -2 + 3 * I;

_x *= I;
x = 3j-2
y = x * 1j
78
Execute a block once, then execute it again as long as boolean condition c is true.
do {
	someThing();
	someOtherThing();
} while(c);
Alternative implementation:
do
{
  stuff()
} while ( c ) ;
while True:
    do_something()
    if not c:
        break
Alternative implementation:
x = True
while x:
    x = c
Alternative implementation:
import turtle

# 设置屏幕
screen = turtle.Screen()
screen.bgcolor("white")

# 创建小球
ball = turtle.Turtle()
ball.shape("circle")
ball.color("red")
ball.penup()
ball.speed(0)

# 初始速度和位置
ball.dx = 2
ball.dy = 2

# 动画循环
while True:
    # 移动小球
    ball.setx(ball.xcor() + ball.dx)
    ball.sety(ball.ycor() + ball.dy)
    
    # 边界检测
    if ball.ycor() > 290 or ball.ycor() < -290:
        ball.dy *= -1
    if ball.xcor() > 390 or ball.xcor() < -390:
    
79
Declare the floating point number y and initialize it with the value of the integer x .
float y = (float)x;
y = float(x)
80
Declare integer y and initialize it with the value of floating point number x . Ignore non-integer digits of x .
Make sure to truncate towards zero: a negative x must yield the closest greater integer (not lesser).
int y = (int)x;
y = int(x)
81
Declare the integer y and initialize it with the rounded value of the floating point number x .
Ties (when the fractional part of x is exactly .5) must be rounded up (to positive infinity).
int y = (int)floorf(x + 0.5f);
y = int(x + 0.5)
Alternative implementation:
c = Context(rounding=ROUND_HALF_UP)
y = round(Decimal(x, c))
82
Find how many times string s contains substring t.
Specify if overlapping occurrences are counted.
unsigned n;
for (n = 0; s = strstr(s, t); ++n, ++s)
	;
count = s.count(t)
84
Count number c of 1s in the integer i in base 2.

E.g. i=6 → c=2
uint32_t c = i;
c = (c & 0x55555555) + ((c & 0xAAAAAAAA) >> 1);
c = (c & 0x33333333) + ((c & 0xCCCCCCCC) >> 2);
c = (c & 0x0F0F0F0F) + ((c & 0xF0F0F0F0) >> 4);
c = (c & 0x00FF00FF) + ((c & 0xFF00FF00) >> 8);
c = (c & 0x0000FFFF) + ((c & 0xFFFF0000) >> 16);
c = bin(i).count("1")
Alternative implementation:
c = i.bit_count()
85
Write boolean function addingWillOverflow which takes two integers x, y and return true if (x+y) overflows.

An overflow may be above the max positive value, or below the min negative value.
bool addingWillOverflow(int x, int y) {
  return ((x > 0) && (y > INT_MAX - x)) ||
         ((x < 0) && (y < INT_MIN - x));
}
def adding_will_overflow(x,y):
    return False
87
Exit immediately.
If some extra cleanup work is executed by the program runtime (not by the OS itself), describe it.
exit (EXIT_SUCCESS);
Alternative implementation:
return 0;
Alternative implementation:
abort();
sys.exit(1)
88
Create a new bytes buffer buf of size 1,000,000.
void *buf = malloc(1000000);
buf = bytearray(1000000)
89
You've detected that the integer value of argument x passed to the current function is invalid. Write the idiomatic way to abort the function execution and signal the problem.
enum {
    E_OK,
    E_OUT_OF_RANGE
};

int square(int x, int *result) {
    if (x > 1073741823) {
        return E_OUT_OF_RANGE;
    }
    *result = x*x;
    return E_OK;
}
raise ValueError("x is invalid")
93
Implement the procedure control which receives one parameter f, and runs f.
void control (void (*f)()) {
        (*f)();
}
def control(f):
    f()
Alternative implementation:
def control(f: Callable): f()
95
Assign to variable x the length (number of bytes) of the local file at path.
FILE *f = fopen(path, "rb");
fseek(f, 0, SEEK_END);
int x = ftell(f);
fclose(f);
Alternative implementation:
struct stat st;
if (stat (path &st) == 0) x = st.st_size;
x = os.path.getsize(path)
96
Set the boolean b to true if string s starts with prefix prefix, false otherwise.
bool b = !strncmp(s, prefix, sizeof(prefix)-1);
b = s.startswith(prefix)
100
Sort elements of array-like collection items, using a comparator c.

int c(const void *a,const void *b)
{
	int x = *(const int *)a;
	int y = *(const int *)b;

	if (x < y) return -1;
	if (x > y) return +1;
	return 0;
}

int main(void)
{
	int arr[]={1,6,3,7,2};
	qsort(arr,sizeof(arr)/sizeof(*arr),sizeof(*arr),c);

	return 0;
}
items.sort(key=c)
Alternative implementation:
items.sort(key=functools.cmp_to_key(c))
105
1
#ifdef _WIN32
#define PATH_SEP '\\'
#else
#define PATH_SEP '/'
#endif

int main(int argc, char* argv[])
{
    char *s = strchr(argv[0], PATH_SEP);
    s = s ? s + 1 : argv[0];

    return 0;
}
s = sys.argv[0]
106
Assign to string dir the path of the working directory.
(This is not necessarily the folder containing the executable itself)
char *dir = getcwd(NULL, 0);
dir = os.getcwd()
107
Assign to string dir the path of the folder containing the currently running executable.
(This is not necessarily the working directory, though.)
int main()
{
    char exe[PATH_MAX], real_exe[PATH_MAX];
    ssize_t r;
    char *dir;

    if ((r = readlink("/proc/self/exe", exe, PATH_MAX)) < 0)
      exit(1);
    if (r == PATH_MAX)
	r -= 1;
    exe[r] = 0;
    if (realpath(exe, real_exe) == NULL)
	exit(1);
    dir = dirname(real_exe);
    puts(dir);
}
dir = os.path.dirname(os.path.abspath(__file__))
Alternative implementation:
dir = str(Path(__file__).parent)
109
Set n to the number of bytes of a variable t (of type T).
n = sizeof (t);
n = pympler.asizeof.asizeof(t)
Alternative implementation:
n = getsizeof(t)
110
Set the boolean blank to true if the string s is empty, or null, or contains only whitespace ; false otherwise.
bool blank = true;
for (const char *p = s; *p; p++) {
	if (!isspace(*p)) {
		blank = false;
		break;
	}
}
blank = not s or s.isspace()
Alternative implementation:
blank = not s or \
        not sub(r'\s+', '', s)
Alternative implementation:
blank = not s or \
        not any(x not in ws for x in s)
111
From current process, run program x with command-line parameters "a", "b".
int system("x a b");
subprocess.call(['x', 'a', 'b'])
117
Set n to the number of elements of the list x.
size_t n = sizeof(x)/sizeof(*x);
Alternative implementation:
int n;
int x[5];
n = sizeof(x)/sizeof(*x);
n = len(x)
120
Read an integer value from the standard input into the variable n
int n;
scanf("%d", &n);
Alternative implementation:
int n[15];
fgets(n, 15, stdin);
n = int(input("Input Prompting String: "))
Alternative implementation:
n = int(input())
122
Create an enumerated type Suit with 4 possible values SPADES, HEARTS, DIAMONDS, CLUBS.
enum Suit {
    SPADES,
    HEARTS,
    DIAMONDS,
    CLUBS
};
class Suit:
	SPADES, HEARTS, DIAMONDS, CLUBS = range(4)
Alternative implementation:
class Suit(Enum):
	SPADES = 1
	HEARTS = 2
	DIAMONDS = 3
	CLUBS = 4
123
Verify that predicate isConsistent returns true, otherwise report assertion violation.
Explain if the assertion is executed even in production environment or not.
assert(isConsistent());
assert isConsistent
126
Write a function foo that returns a string and a boolean value.
typedef struct {
    const char * const a;
    const bool b;
} RetStringBool;

RetStringBool foo() {
    return (RetStringBool) {.a = "Hello", .b = true};
}
def foo():
    return 'string', True
Alternative implementation:
foo = lambda: ('abc', True)
127
Import the source code for the function foo body from a file "foobody.txt".
void foo()
{
#include "foobody.txt"
}
foo = imp.load_module('foobody', 'foobody.txt').foo
131
Execute f1 if condition c1 is true, or else f2 if condition c2 is true, or else f3 if condition c3 is true.
Don't evaluate a condition when a previous condition was true.
if (c1)
{
    f1();
} 
else if (c2)
{
    f2();
}
else if (c3)
{
    f3();
}
f1() if c1 else f2() if c2 else f3() if c3 else None
Alternative implementation:
if c1:
    f1()
elif c2:
    f2()
elif c3:
    f3()
Alternative implementation:
if c1: f1()
elif c2: f2()
elif c3: f3()
137
Set the boolean b to true if the string s contains only characters in the range '0'..'9', false otherwise.
char b = 0;
int n = strlen(s);
for (int i = 0; i < n; i++) {
	if (! (b = (s[i] >= '0' && s[i] <= '9')))
		break;
}
Alternative implementation:
bool b = true;
const int n = strlen(s);
for (int i = 0; i < n; ++i) {
  if (!isdigit(s[i])) {
    b = false;
    break;
  }
}
b = s.isdigit()
Alternative implementation:
b = all(x in digits for x in s)
Alternative implementation:
try:
  int(s)
  b = true
except:
  b = false
138
Create a new temporary file on the filesystem.
const char tmpl[] = "XXXXXX.tmp";
int fd = mkstemp(tmpl);
file = tempfile.TemporaryFile()
142
Assign to string s the hexadecimal representation (base 16) of integer x.

E.g. 999 -> "3e7"
char s[32];
snprintf(s, sizeof(s), "%x", i);
s = hex(x)
Alternative implementation:
s = format(x, 'x')
Alternative implementation:
s = '%x' % x
144
Set boolean b to true if file at path fp exists on filesystem; false otherwise.

Beware that you should not do this and then in the next instruction assume the result is still valid, this is a race condition on any multitasking OS.
bool b = access(_fp, F_OK) == 0
b = os.path.exists(fp)
Alternative implementation:
b = Path(fp).exists()
152
Create string s containing only the character c.
char s[2] = {0};
s[0] = c;
s = c
155
Delete from filesystem the file having path filepath.
int main(void)
{
	if (unlink(filepath) == -1)
		err(1, "unlink");
	return 0;
}
path = pathlib.Path(_filepath)
path.unlink()
Alternative implementation:
os.remove(filepath)
157
Initialize a constant planet with string value "Earth".
const char *_planet = "Earth";
PLANET = 'Earth'
161
Multiply all the elements of the list elements by a constant c
for(int i = 0; i < elements_size; ++i) elements[i] *= c;
elements = [c * x for x in elements]
Alternative implementation:
f = lambda x: x * c
elements = [*map(f, elements)]
Alternative implementation:
for i, x in enumerate(elements):
    elements[i] = x * c
162
execute bat if b is a program option and fox if f is a program option.
int main(int argc, char * argv[])
{
        int optch;
        while ((optch = getopt(argc, argv, "bf")) != -1) {
                switch (optch) {
                        case 'b': bat(); break;
                        case 'f': fox(); break;
                }
        }
        return 0;
}
if 'b' in sys.argv[1:]: bat()
if 'f' in sys.argv[1:]: fox()
Alternative implementation:
options = {
	'b': bat
	'f': fox
}

for option, function in options:
	if option in sys.argv[1:]:
		function()
Alternative implementation:
a = dict.fromkeys(argv[1:])
for x in a.keys():
    match x:
        case 'b': bat()
        case 'f': fox()
Alternative implementation:
s = argv[1:]
for x, f in (('b', bat), ('f', fox)):
    if x in s: f()
163
Print all the list elements, two by two, assuming list length is even.
for (unsigned i = 0; i < sizeof(list) / sizeof(list[0]); i += 2)
	printf("%d, %d\n", list[i], list[i + 1]);
for x in zip(list[::2], list[1::2]):
    print(x)
Alternative implementation:
def pairwise(iterable):
    "s -> (s0,s1), (s1,s2), (s2, s3), ..."
    a, b = tee(iterable)
    next(b, None)
    return zip(a, b)

for a, b in pairwise(list):
    print(a, b)
Alternative implementation:
for x in batched(a, 2): print(x)
Alternative implementation:
x = iter(list)
print(*zip_longest(x, x))
Alternative implementation:
for x in range(0, len(list), 2):
    print(list[x], list[x + 1])
165
Assign to the variable x the last element of the list items.
int length = sizeof(items) / sizeof(items[0]);
int x = items[length - 1];
x = items[-1]
167
Create the string t consisting of the string s with its prefix p removed (if s starts with p).
size_t l = strlen(p);
const char * t = strncmp(s, p, l) ? s : s + l;
t = s[s.startswith(p) and len(p):]
Alternative implementation:
t = s.removeprefix(p)
173
Number will be formatted with a comma separator between every group of thousands.
setlocale(LC_ALL, "");
printf("%'d\n", 1000);
f'{1000:,}'
Alternative implementation:
format(1000, ',')
Alternative implementation:
'{:,}'.format(1000)
175
From the array a of n bytes, build the equivalent hex string s of 2n digits.
Each byte (256 possible values) is encoded as two hexadecimal characters (16 possible values per digit).
char *s = calloc(n * 2 + 1, 1);
for(int i = 0; i < n; ++i){
  char temp[3];
  sprintf(temp, "%02x", a[i]);
  s[2 * i] = temp[0];
  s[2 * i + 1] = temp[1];
}
s = a.hex()
176
From hex string s of 2n digits, build the equivalent array a of n bytes.
Each pair of hexadecimal characters (16 possible values per digit) is decoded into one byte (256 possible values).
const char* hexstring = "deadbeef";
size_t length = sizeof(hexstring);
unsigned char bytearray[length / 2];

for (size_t i = 0, j = 0; i < (length / 2); i++, j += 2)
	bytearray[i] = (hexstring[j] % 32 + 9) % 25 * 16 + (hexstring[j+1] % 32 + 9) % 25;
a = bytearray.fromhex(s)
178
Set boolean b to true if if the point with coordinates (x,y) is inside the rectangle with coordinates (x1,y1,x2,y2) , or to false otherwise.
Describe if the edges are considered to be inside the rectangle.
int isInsideRect(double x1, double y1, double x2, double y2, double px, double py){
	return px >= x1 && px <= x2 && py >= y1 && py <= y2; 
}
b = (x1 < x < x2) and (y1 < y < y2)
Alternative implementation:
class Rectangle:
    def __init__(self, x, y, w, h):
        self.x, self.y = x, y
        self.w, self.h = w, h
    def contains(self, x, y):
        a, b = self.x, self.y
        w, h = self.w, self.h
        return a <= x <= (a + w) and \
               b <= y <= (b + h)
w, h = x2 - x1, y2 - y1
r = Rectangle(x1, y1, w, h)
b = r.contains(x, y)
180
Create the list x containing the contents of the directory d.

x may contain files and subfolders.
No recursive subfolder listing.
struct dirent ** x = NULL;
int n = scandir (p, &x, NULL, alphasort);
x = os.listdir(d)
182
Output the source of the current program. A quine is a computer program that takes no input and produces a copy of its own source code as its only output.

Reading the source file from disk is cheating.
int main(){char*s="int main(){char*s=%c%s%c;printf(s,34,s,34);return 0;}";printf(s,34,s,34);return 0;}
Alternative implementation:
main(p){printf(p="main(p){printf(p=%c%s%1$c,34,p);}",34,p);}
s = 's = %r\nprint(s%%s)'
print(s%s)
186
Exit a program cleanly indicating no error to OS
exit(EXIT_SUCCESS);
sys.exit(0)
190
Declare an external C function with the prototype

void foo(double *a, int n);

and call it, passing an array (or a list) of size 10 to a and 10 to n.

Use only standard features of your language.
void foo(double *a, int n);
double a[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
foo (a, sizeof(a)/sizeof(*a));
a = (c_int * 10)(*range(10))
n = 10
libc = cdll.LoadLibrary('/path/to/c_library')
libc.foo(c_void_p(a), c_int(n))
191
Given a one-dimensional array a, check if any value is larger than x, and execute the procedure f if that is the case
unsigned i;
for (i = 0; i < sizeof(a) / sizeof(a[0]); ++i) {
	if (a[i] > x) {
		f();
		break;
	}
}
if any(v > x for v in a):
    f()
Alternative implementation:
if any(z > x for z in a): f()
198
Abort program execution with error condition x (where x is an integer value)
exit(x);
sys.exit(x)
204
Given a real number a, print the fractional part and the exponent of the internal representation of that number. For 3.14, this should print (approximately)

0.785 2
  double d = 3.14;
  double res;
  int e;

  res = frexp(d, &e);
  printf("%f %d\n",res,e);
print(math.frexp(a))
205
Read an environment variable with the name "FOO" and assign it to the string variable foo. If it does not exist or if the system does not support environment variables, assign a value of "none".
const char * foo = getenv("FOO");
if (foo == NULL) foo = "none";
try:
    foo = os.environ['FOO']
except KeyError:
    foo = "none"
Alternative implementation:
foo = getenv('FOO', 'none')
Alternative implementation:
foo = os.environ.get('FOO', 'none')
208
Given the arrays a,b,c,d of equal length and the scalar e, calculate a = e*(a+b*c+cos(d)).
Store the results in a.
  for (int i=0; i<n; i++)
    a[i] = e*(a[i]+b[i]*c[i]+cos(d[i]));
for i in xrange(len(a)):
	a[i] = e*(a[i] + b[i] + c[i] + math.cos(a[i]))
Alternative implementation:
a = [e*(a[i] + b[i] + c[i] + math.cos(d[i])) for i in range(len(a))]
Alternative implementation:
f = lambda a, b, c, d: \
    e * (a + (b * c) + cos(d))
a = list(map(f, a, b, c, d))
Alternative implementation:
def f(a, b, c, d):
    return e * (a + (b * c) + cos(d))
a = list(map(f, a, b, c, d))
237
Assign to c the result of (a xor b)
int c = a ^ b;
c = a ^ b
252
Assign to the variable x the string value "a" if calling the function condition returns true, or the value "b" otherwise.
x = condition() ? "a" : "b";
x = "a" if condition() else "b"
Alternative implementation:
x = 'ba'[condition()]
Alternative implementation:
x = ('b', 'a')[condition()]
256
Print the numbers 5, 4, ..., 0 (included), one line per number.
for (int i = 5; i >= 0; i--) {
	printf("%d\n", i);
}
for i in range(5, -1, -1):
    print(i)
Alternative implementation:
print(*reversed(range(6)), sep='\n')
262
Assign to t the number of trailing 0 bits in the binary representation of the integer n.

E.g. for n=112, n is 1110000 in base 2 ⇒ t=4
int t = -1;
if (n)
        while (! (n & 1<<++t));
else
        t = 8*sizeof(n);
t = bin(n)[::-1].find('1')
Alternative implementation:
b = len(s := format(n, 'b'))
t = b - len(s.rstrip('0'))
266
Assign to the string s the value of the string v repeated n times, and write it out.

E.g. v="abc", n=5 ⇒ s="abcabcabcabcabc"
char *s = calloc(strlen(v) * n + 1, 1);
for(int i = 0; i < n; ++i) strcat(s, v);
s = v * n
Alternative implementation:
s = ''.join(repeat(v, n))
275
From the string s consisting of 8n binary digit characters ('0' or '1'), build the equivalent array a of n bytes.
Each chunk of 8 binary digits (2 possible values per digit) is decoded into one byte (256 possible values).
unsigned char *a = calloc(strlen(s) / 8, 1);
for(int i = 0; i < strlen(s); ++i){
  a[i / 8] |= (s[i] == '1') << (7 - i % 8);
}
n = (len(s) - 1) // 8 + 1
a = bytearray(n)
for i in range(n):
    b = int(s[i * 8:(i + 1) * 8], 2)
    a[i] = b
Alternative implementation:
f = lambda x: int(s[x:x + 8], 2)
a = [*map(f, range(0, len(s), 8))]
Alternative implementation:
f = lambda x: int(''.join(x), 2)
a = [*map(f, batched(s, 8))]
Alternative implementation:
p = re.findall('.{8}', s)
a = [*map(lambda x: int(x, 2), p)]
Alternative implementation:
p = findall('.{8}', s)
a = bytes(int(x, 2) for x in p)
284
Create a new list a (or array, or slice) of size n, where all elements are integers initialized with the value 0.
int *a = calloc(n, sizeof(*a));
a = [0] * n
Alternative implementation:
a = [*repeat(0, n)]
299
Write a line of comments.

This line will not be compiled or executed.
// This is a comment.
# This is a comment
302
Given the integer x = 8, assign to the string s the value "Our sun has 8 planets", where the number 8 was evaluated from x.
char s[32] = "";
sprintf(s, "Our sun has %i planets", x);
s = f'Our sun has {x} planets'
Alternative implementation:
s = 'Our sun has {} planets'.format(x)
Alternative implementation:
s = 'Our sun has %s planets' % x
305
Compute and print a^b, and a^n, where a and b are floating point numbers and n is an integer.
printf("%f %f", pow(a, b), pow(a, n));
print(a ** b, a ** n)
320
Set b to true if the string s is empty, false otherwise
bool b = !strlen(s);
b = s == ''
Alternative implementation:
b = not s
337
Extract the integer value i from its string representation s, in radix b
int i = strtol(s, NULL, b);
i = int(s, b)
343
Rename the file at path1 into path2
rename(path1, path2);
os.rename(path1, path2)