Syntax and Control Flow

Of Python3 and C++

By Ariel Parra

Simplest Python Template for input output program

def main():
    
    n = int(input()) # delcares a variable 'n' and asign an integer from standart input
    print(n) # writes the variable 'n' followed by a newline '\n' to standart output

main() # calls the main function to run
CPC Γα=Ω5

Simple Python Template for competitive programming

import sys # imports fast input/output library 
read = sys.stdin.readline # fast input function
write = sys.stdout.write # fast output function

def main():
    
    n = int(read()) # delcares a variable 'n' and asign an integer from standart input
    write(f"{n}\n") # writes the variable 'n' followed by a newline '\n' to standart output

main() 

Try the code on https://www.onlinegdb.com/

CPC Γα=Ω5

Simple C++ template for competitive programming

#include <bits/stdc++.h> // includes all librarys in c++
using namespace std; // std::cout<<"hi"; -> cout<<"hi"; 

int main(){
ios::sync_with_stdio(0);cin.tie(0); // enables fast input/output

    int n;       // variable to store the input number
    cin >> n;    // reads an integer 'n' from standard input
    cout << n;   // writes the integer to standard output

return 0;
}
CPC Γα=Ω5

Conditionals

CPC Γα=Ω5

Truth Tables for Boolean (Logical) Operators

Py not, C++!

p ¬p
F T
T F

Py and, C++ &&

p q p ∧ q
F F F
F T F
T F F
T T T

Py or, C++ ||

p q p ∨ q
F F F
F T T
T F T
T T T
CPC Γα=Ω5

simple if's

Python

programming, studying = True, True
if programming:
    write("True\n")  # output with endline '\n'
else:
    write("False\n")

C++

bool programming, studying = true;
if(programming) //asumes if(programming == true) 
    cout << "true\n"; // output with endline '\n'
else //asume if(programming == false) or if(!programming)
    cout << "false" << endl; // output with endl  
CPC Γα=Ω5

Ternary operator

First, the boolean condition is written, followed by the ? operator, which indicates the value that will be returned if the condition is true. After the : operator, the value that will be returned if the condition is false is placed.

py

write("Learning " if programming else "procrastinating") # Py

c++

cout << (programming ? "Learning " : "procrastinating"); //C++
cout << (programming && studying ? "I will succeed in competitions"
 : (programming || studying ? "maybe I will succeed" : "well I won't succeed"));
CPC Γα=Ω5

Switch-case in c++

It allows evaluating an expression and executing different code blocks efficiently. In this case, a is the evaluated expression and can only be numeric (int / long long) or a character (char). Note that Python doesn't have a switch-case statement, so you would need to use if-else statements instead.

switch(a) { 
    case 'A': case '1':
        cout << "just chars 'A' and '1'";
        break;
    case 'a' ... 'z': 
        cout << "lowercase lettters"; 
        break; 
    case 0 ... 10:
        cout << "numbers 0 to 10"; 
        break;
    default:
        cout << "everything else";
} 
CPC Γα=Ω5

Cycles

CPC Γα=Ω5

for

  • traditional for
for i in range(n):
    write(f"{i} ")
for (int i=0; i < n; ++i) {
    cout << i << " ";
}

Output if n=10: 0 1 2 3 4 5 6 7 8 9

CPC Γα=Ω5
  • single-line for
for (int i=0; i < n; ++i) cout << i << " ";
[write(f"{i} ") for i in range(n)]
  • range for
vector<int> numbers = {1, 2, 3, 4, 5};
for (int number : numbers) {
    cout << number << " ";
}
numbers = [1, 2, 3, 4, 5]
for number in numbers:
    write(f"{number} ")
CPC Γα=Ω5

while

  • while
i = 0
while True:  # condition
    write(f"{i}")
    i += 1
    if i > n:
        break  # instead of true
int i = 0;
while (true) { // condition
    cout << i;
    if (i++ > n) break; //insted of true contition
}
CPC Γα=Ω5
  • do-while (Python doesn't have do-while)
i = 0
write("\n")
while True:
    i += 1
    write(f"{i}")
    if not (i < n):
        break
int i = 0;
cout<<endl;
do {
    cout << ++i;
} while (i < n);
CPC Γα=Ω5

Math sequences

arithmetic sequence

for example: 5,8,11,14,...
py

a, d, n = 5, 3, 10
for i in range(n):
    write(f"{a + i * d} ")  # prints all until n term

c++

int a = 5, d = 3, n = 10; 
for (int i = 0; i < n; ++i) { 
    cout << a + i * d << " ";//prints all until n term
}
CPC Γα=Ω5

geometric sequence

for example: 5,15,45,135,...

a, r, n = 5, 3, 10
for i in range(n):
    write(f"{a * (r ** i)} ")  # prints all until n term
int a = 5, r = 3, n = 10;
for (int i = 0; i < n; ++i) {
   cout << a * pow(r, i) << " "; // prints all until n term
}
CPC Γα=Ω5

Arithmetic sequences

  • Formula for the nth term:

   int an = a1 + (n - 1) * d;
  • Formula for the sum of the first n terms:

    int sn = ( n * (2 * a1 + (n - 1) * d) ) /2;
  • or equivalently:

CPC Γα=Ω5

Geometric sequences

  • Formula for the nth term:

    int an = a1 * pow(r, n - 1);
  • Formula for the sum of the first n terms:

For r != 1:

    int Sn = a1 * (pow(r, n) - 1) / (r - 1);
  • Formula for the sum of an infinite geometric series (when |r| < 1):

CPC Γα=Ω5

Summation / Sumatorias (Σ)

Summation (sigma notation: Σ) is used to sum a sequence of terms.

int n = 10, sum = 0;
for (int i = 1; i <= n; ++i) {
    sum += i;
}

Riemann sum formula for consecutive integers:

int rs = n * (n + 1) / 2;  // Direct formula instead of loop
CPC Γα=Ω5

Product of a secuence / productoriu / multiplicatoria (Π)

The product of a sequence (pi notation: Π) is used to multiply a sequence of terms.

int n = 5, product = 1;
for (int i = 1; i <= n; ++i) {
    product *= i;
}

Factorial formula for consecutive integers:

#include <cmath>
int factorial = tgamma(n + 1);  // Using gamma function (requires <cmath>)
CPC Γα=Ω5

Jump Statements

  • break: Terminates the loop or switch statement and transfers control to the statement immediately following.
for (int i = 1; i <= 10; ++i) {
    if (i == 5) break;
    cout << i << " ";
}
  • continue: Skips the current iteration of a loop and continues with the next iteration.
for (int i = 1; i <= 10; ++i) {
    if (i == 5) continue;
    cout << i << " ";
}
CPC Γα=Ω5
  • return: Exits a function and returns a value to the caller.
int add(int a, int b) {
    return a + b;
}
int result = add(3, 4);
cout << result << endl;
  • goto: Transfers control to a labeled statement within the same function. (Note: can create unreadable and error-prone code, but can also solve problems with recursion).
int i = 1;
start:
    if (i > 5) goto end;
    cout << i << " ";
    ++i;
    goto start;
end:
CPC Γα=Ω5

Functions

CPC Γα=Ω5

Nesting

Nesting occurs when we nest conditionals inside one another. This leads to code that is difficult to read.

inline void foo() {
    if (var) {
        if (qux) {
            if (baz) {
                cout << "All conditions are true";
            } else {
                cout << "baz is false";
            }
        } else {
            cout << "qux is false";
        }
    } else {
        cout << "var is false";
    }
}

There are two methods to avoid nesting and become a never-nester: inversion and extraction.

CPC Γα=Ω5

1.Inversion

It consists of handling negative cases first and using return statements to exit the control flow as early as possible.

inline void foo() {
    if (!var) {
        cout << "var is false";
        return;
    }
    if (!qux) {
        cout << "qux is false";
        return;
    }
    if (!baz) {
        cout << "baz is false";
        return;
    }
    cout << "All conditions are true";
}
CPC Γα=Ω5

2.Extraction

It consists of dividing the code into smaller and more specific functions to improve readability.

inline void checkBaz() {
    if (!baz) {
        cout << "baz is false";
        return;
    } cout << "All conditions are true";
}
inline void checkQux() {
    if (!qux) {
        cout << "qux is false";
        return;
    } checkBaz();
}
inline void foo() {
    if (!var) {
        cout << "var is false";
        return;
    } checkQux();
}
CPC Γα=Ω5

Branching & Branchless

The term branching refers to conditionals, when the program diverges into two paths it can become slow in certain cases because the CPU tries to get ahead by preloading one of the possible functions. The branchless methodology avoids this, but it can make the function less readable.

inline int minorBranch(int a, int b) {
    if (a < b)  
        return a;
    return b;
}
inline int minorBranchLess(int a, int b) {
    return a * (a < b) + b * (b <= a);
}
CPC Γα=Ω5

Lambda λ

Lambdas or lambda functions allow defining anonymous functions concisely. They are useful for creating short functions that are used in the context of another function, such as in STL algorithms.

An example:

py

suma = lambda a, b: a + b
res = suma(5, 3)

c++

auto suma = [](int a, int b) -> int { return a + b; };
int res = suma(5, 3);
CPC Γα=Ω5

Problems

CPC Γα=Ω5

References

CPC Γα=Ω5

Recordar el write = sys.stdout.write ya que no se volvera a repetir y se asumira en lugar de print para ejemplos

mencionar que la parte del codigo que nos interesa es el algoritmo en si, el read y el write

El chiste es que conditional suena similar a conditioner

F = False, T = True

En el ultimo snippet de código preguntar cuales serian los resultados cuando programming

explicar que el while no parara con true

Aquí los ejemplos seran en c++ y ya si quieren python que pregunten a chatpgt xD

Progreción aritmetica en español

explicar cada funcion

a_n is the nth term. / a_n es el término n-ésimo. a_1 is the first term. / a_1 es el primer término. n is the term number. / n es el número del término. d is the common difference. / d es la diferencia común.

a_n is the nth term. / a_n es el término n-ésimo. a_1 is the first term. / a_1 es el primer término. n is the term number. / n es el número del término. r is the common ratio. / r es la razón común.

i=1: Es el índice de la sumatoria. En el código, es la variable de iteración del bucle for. Donde 1 es el valor inicial. n: Es el valor final del índice i. En el código, corresponde a la condición de paro del bucle i <= n. i: Es el término general que se suma. En el código, es lo que se suma a la variable sum en cada iteración sum += i.

i=1: Es el índice de la sumatoria. En el código, es la variable de iteración del bucle for. Donde 1 es el valor inicial. n: Es el valor final del índice i. En el código, corresponde a la condición de paro del bucle i <= n. i: Es el término general que se multiplica. En el código, es lo que se multiplica por la variable product en cada iteración product *= i.

si preguntan Inline obliga al compilador a siempre poner la funcion dentro del bloque donde se llama (aunque aveces el compilador lo hace solo)

esto es redundante y no tan necesario ya que el codigo no es legible y aun asi el compilador optimizaria este codigo

La sintaxis básica de una lambda es: [capturas](parámetros) -> tipo_retorno { // Cuerpo de la función };

auto nos ahorra escribir: std::function<int(int, int)> suma = [](int a, int b) -> int { return a + b; };

explicar que es necesario hacer el primer problema en el club y el segundo se lo pueden llevar de tarea