Python string to int

Python string to int

In Python, the int() function is used to convert a string to an integer

Example:

Python2:

#!/usr/bin/python

############################################
#                                          #
# File Name : stringToInt.py               #
# Author    : IziTutz (https://izitutz.com)#
#                                          #
############################################

age = int("18")
print "Age is : ", age

and the output:

Age is :  18

Python3:

#!/usr/bin/python3

############################################
#                                          #
# File Name : stringToInt1.py              #
# Author    : IziTutz (https://izitutz.com)#
#                                          #
############################################

age = int("18")
print("Age is : ", age)

and the output:

Age is :  18

Square root in Python

The math.sqrt() function calculates the square root of a number

Example:

Python2:

#!/usr/bin/python

############################################
#                                          #
# File Name : sqrt.py                      #
# Author    : IziTutz (https://izitutz.com)#
#                                          #
############################################

from math import sqrt

print "sqrt(0) = ", sqrt(0)
print "sqrt(4) = ", sqrt(4)
print "sqrt(3) = ", sqrt(3)

and the output:

sqrt(0) =  0.0
sqrt(4) =  2.0
sqrt(3) =  1.73205080757

Python3:

#!/usr/bin/python3

############################################
#                                          #
# File Name : sqrt1.py                     #
# Author    : IziTutz (https://izitutz.com)#
#                                          #
############################################

from math import sqrt

print("sqrt(0) = ", sqrt(0))
print("sqrt(4) = ", sqrt(4))
print("sqrt(3) = ", sqrt(3))

and the output:

sqrt(0) =  0.0
sqrt(4) =  2.0
sqrt(3) =  1.73205080757

// in Python

// floor division

Description

Returns the integral part of the quotient.

Syntax

A // B

A : Any expression evaluating to a numeric type.

B: Any expression evaluating to a numeric type.

Return Value

According to coercion rules.

Time Complexity

#TODO

Remarks

Also referred to as integer division. The resultant value is a whole integer, though the result’s type is not necessarily int.

Example

>>> 5.0 / 2
2.5
>>> 5.0 // 2
2.0

ASCII table

The following table contains all 256 ASCII
character (Character), decimal (Dec), hexadecimal (Hex), binary (Bin) and
octal (Oct) codes.

ASCII control characters (character code 0-31): The first 32 characters in the ASCII-table are unprintable control codes and are used to control peripherals such as printers.
ASCII printable characters (character code 32-127): Codes 32-127 are common for all the different variations of the ASCII table, they are called printable characters, represent letters, digits, punctuation marks, and a few miscellaneous symbols. You will find almost every character on your keyboard. Character 127 represents the command DEL.
The extended ASCII codes (character code 128-255): There are several different variations of the 8-bit ASCII table. The table below is according to Windows-1252 (CP-1252) which is a superset of ISO 8859-1, also called ISO Latin-1, in terms of printable characters, but differs from the IANA’s ISO-8859-1 by using displayable characters rather than control characters in the 128 to 159 range.

CharacterDecHexBinOct
NUL – null0000
SOH – start of heading1111
STX – start of text22102
ETX – end of text33113
EOT – end of transmission441004
ENQ – enquiry551015
ACK – acknowledge661106
BEL – bell771117
BS – backspace88100010
TAB – horizontal tab99100111
LF – line feed10A101012
VT – vertical tab11B101113
FF – form feed12C110014
CR – carriage return13D110115
SO – shift out14E111016
SI – shift in15F111117
DLE – data link escape16101000020
DC1 – device control 117111000121
DC2 – device control 218121001022
DC3 – device control 319131001123
DC4 – device control 420141010024
NAK – negative acknowledge21151010125
SYN – synchronous idle22161011026
ETB – end of trans. block23171011127
CAN – cancel24181100030
EM – end of medium25191100131
SUB – substitute261A1101032
ESC – escape271B1101133
FS – file separator281C1110034
GS – group separator291D1110135
RS – record separator301E1111036
US – unit separator311F1111137
SP – Space322010000040
!332110000141
342210001042
#352310001143
$362410010044
%372510010145
&382610011046
392710011147
(402810100050
)412910100151
*422A10101052
+432B10101153
,442C10110054
452D10110155
.462E10111056
/472F10111157
0483011000060
1493111000161
2503211001062
3513311001163
4523411010064
5533511010165
6543611011066
7553711011167
8563811100070
9573911100171
:583A11101072
;593B11101173
<603C11110074
=613D11110175
>623E11111076
?633F11111177
@64401000000100
A65411000001101
B66421000010102
C67431000011103
D68441000100104
E69451000101105
F70461000110106
G71471000111107
H72481001000110
I73491001001111
J744A1001010112
K754B1001011113
L764C1001100114
M774D1001101115
N784E1001110116
O794F1001111117
P80501010000120
Q81511010001121
R82521010010122
S83531010011123
T84541010100124
U85551010101125
V86561010110126
W87571010111127
X88581011000130
Y89591011001131
Z905A1011010132
[915B1011011133
\925C1011100134
]935D1011101135
^945E1011110136
_955F1011111137
`96601100000140
a97611100001141
b98621100010142
c99631100011143
d100641100100144
e101651100101145
f102661100110146
g103671100111147
h104681101000150
i105691101001151
j1066A1101010152
k1076B1101011153
l1086C1101100154
m1096D1101101155
n1106E1101110156
o1116F1101111157
p112701110000160
q113711110001161
r114721110010162
s115731110011163
t116741110100164
u117751110101165
v118761110110166
w119771110111167
x120781111000170
y121791111001171
z1227A1111010172
{1237B1111011173
|1247C1111100174
}1257D1111101175
~1267E1111110176
1277F1111111177
1288010000000200
1298110000001201
1308210000010202
ƒ1318310000011203
1328410000100204
1338510000101205
1348610000110206
1358710000111207
ˆ1368810001000210
1378910001001211
Š1388A10001010212
1398B10001011213
Œ1408C10001100214
1418D10001101215
Ž1428E10001110216
1438F10001111217
1449010010000220
1459110010001221
1469210010010222
1479310010011223
1489410010100224
1499510010101225
1509610010110226
1519710010111227
˜1529810011000230
1539910011001231
š1549A10011010232
1559B10011011233
œ1569C10011100234
1579D10011101235
ž1589E10011110236
Ÿ1599F10011111237
160A010100000240
¡161A110100001241
¢162A210100010242
£163A310100011243
¤164A410100100244
¥165A510100101245
¦166A610100110246
§167A710100111247
¨168A810101000250
©169A910101001251
ª170AA10101010252
«171AB10101011253
¬172AC10101100254
­173AD10101101255
®174AE10101110256
¯175AF10101111257
°176B010110000260
±177B110110001261
²178B210110010262
³179B310110011263
´180B410110100264
µ181B510110101265
182B610110110266
·183B710110111267
¸184B810111000270
¹185B910111001271
º186BA10111010272
»187BB10111011273
¼188BC10111100274
½189BD10111101275
¾190BE10111110276
¿191BF10111111277
À192C011000000300
Á193C111000001301
Â194C211000010302
Ã195C311000011303
Ä196C411000100304
Å197C511000101305
Æ198C611000110306
Ç199C711000111307
È200C811001000310
É201C911001001311
Ê202CA11001010312
Ë203CB11001011313
Ì204CC11001100314
Í205CD11001101315
Î206CE11001110316
Ï207CF11001111317
Ð208D011010000320
Ñ209D111010001321
Ò210D211010010322
Ó211D311010011323
Ô212D411010100324
Õ213D511010101325
Ö214D611010110326
×215D711010111327
Ø216D811011000330
Ù217D911011001331
Ú218DA11011010332
Û219DB11011011333
Ü220DC11011100334
Ý221DD11011101335
Þ222DE11011110336
ß223DF11011111337
à224E011100000340
á225E111100001341
â226E211100010342
ã227E311100011343
ä228E411100100344
å229E511100101345
æ230E611100110346
ç231E711100111347
è232E811101000350
é233E911101001351
ê234EA11101010352
ë235EB11101011353
ì236EC11101100354
í237ED11101101355
î238EE11101110356
ï239EF11101111357
ð240F011110000360
ñ241F111110001361
ò242F211110010362
ó243F311110011363
ô244F411110100364
õ245F511110101365
ö246F611110110366
÷247F711110111367
ø248F811111000370
ù249F911111001371
ú250FA11111010372
û251FB11111011373
ü252FC11111100374
ý253FD11111101375
þ254FE11111110376
ÿ255FF11111111377

malloc

void *malloc(size_t size);

Allocates memory block

Allocates size bytes of memory block, and return a pointer points to the beginning of it.

The newly memory block is not initialized.

If size is zero, the return value may or may not be a null pointer (depends on the particular library)

Parameters:

size: size of the memory block, in bytes (size_t is an unsigned integeral type)

Return Values:

On success, a pointer points to block memory returned. The returned pointer is void*, so it can be cast to the desired type

If the function failed, a null pointer returned

Example:

/*
File Name : malloc.c
Author    : IziTutz (https://izitutz.com)
*/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define MSG "Hello, World!"

int main(int argc, char *argv[]) {
  char *pMessage = (char *) malloc(strlen(MSG) + 1);

  if (pMessage) {
    strcpy(pMessage, MSG);
    printf("pMessage : '%s'\n", pMessage);
    free(pMessage);
  } else
   fprintf(stderr, "Memory allocation failed\n");

  return 0;
}

and the output:

pMessage : 'Hello, World!'

strcmp

int strcmp(const char *str1, const char *str2);

Compare two strings
Compare the C string str1 to the C string str2

The function starts comparing the first character of strings. If they’re equal, it continues with the following pairs till characters differ or null-character reached.

Parameters:
str1: C string needed to compare
str2: C string needed to compare

Return Values:
Returns an integral value indicating the relationship between strings

Return ValueIndicates
<0the first character does not match has lower value
0the two strings are equal
>0 the first character does not match has greater value

Example:

/*
File Name : strcmp.c
Author    : IziTutz (https://izitutz.com)
*/

#include <stdio.h>
#include <string.h>

int main(int argc, char *argv[]) {
  char *str1 = "stringz2";
  char *str2 = "stringa2";

  if (strcmp(str1, str2) > 0)
    printf("'%s' is greater than '%s'\n", str1, str2);
  else if (strcmp(str1, str2) == 0)
    printf("'%s' is equal to '%s'\n", str1, str2);
  else
    printf("'%s' is less than '%s'\n", str1, str2);

  return 0;
}

and the output:

'stringz2' is greater than 'stringa2'

Global variables in C

Global variables in C are variables declared outside all functions.


Global variables are automatically initialized to 0 at the time of declaration

/*
File Name : globalVariables.c
Author    : IziTutz (https://izitutz.com)
*/

#include <stdio.h>

int code;

int main(int argc, char *argv[]) {
  printf("The default value of the global variable code is : %d\n", code);

  return 0;
}

and the output:

The default value of the global variable code is : 0

Can be used by any functions in the program

/*
File Name : globalVariables1.c
Author    : IziTutz (https://izitutz.com)
*/

#include <stdio.h>

int code;

void changeCode() {
  code = 2;
}

int main(int argc, char *argv[]) {
  changeCode();

  printf("The current value of the global variable code is : %d\n", code);

  return 0;
}

and the output:

The current value of the global variable code is : 2

Available till the program terminates

/*
File Name : globalVariables1.c
Author    : IziTutz (https://izitutz.com)
*/

#include <stdio.h>

int code;

void changeCode() {
  code = 2;
}

int main(int argc, char *argv[]) {
  changeCode();

  printf("The current value of the global variable code is : %d\n", code);

  return 0;
}

and the output:

The current value of the global variable code is : 2

The local takes precedence if it and the global have the same name

/*
File Name : globalVariables2.c
Author    : IziTutz (https://izitutz.com)
*/

#include <stdio.h>

int code;

void changeCode() {
  int code = 1;
  code = 2;
}

int main(int argc, char *argv[]) {
  changeCode();

  printf("The current value of the global variable code is : %d\n", code);

  return 0;
}

and the output:

The current value of the global variable code is : 0

C operator precedence

The C operator precedence and associativity are listed in the following table, top to bottom in descending precedence.

Precedence Operator Description Associativity
1 ++ -- Suffix/postfix increment and decrement Left-to-right
() Function call
[] Array subscripting
. Structure and union member access
-> Structure and union member access through pointer
(type){list} Compound literal(C99)
2 ++ -- Prefix increment and decrement Right-to-left
+ - Unary plus and minus
! ~ Logical NOT and bitwise NOT
(type) Type cast
* Indirection (dereference)
& Address-of
sizeof Size-of
_Alignof Alignment requirement(C11)
3 * / % Multiplication, division, and remainder Left-to-right
4 + - Addition and subtraction
5 << >> Bitwise left shift and right shift
6 < <= For relational operators < and ≤ respectively
> >= For relational operators > and ≥ respectively
7 == != For relational = and ≠ respectively
8 & Bitwise AND
9 ^ Bitwise XOR (exclusive or)
10 | Bitwise OR (inclusive or)
11 && Logical AND
12 || Logical OR
13 ?: Ternary conditional Right-to-Left
14 = Simple assignment
+= -= Assignment by sum and difference
*= /= %= Assignment by product, quotient, and remainder
<<= >>= Assignment by bitwise left shift and right shift
&= ^= |= Assignment by bitwise AND, XOR, and OR
15 , Comma Left-to-right

The operand of sizeof can’t be a type cast: the expression sizeof (int) * p is unambiguously interpreted as (sizeof(int)) * p, but not sizeof((int)*p).

The expression in the middle of the conditional operator (between ? and :) is parsed as if parenthesized: its precedence relative to ?: is ignored.

When parsing an expression, an operator which is listed on some row will be bound tighter (as if by parentheses) to its arguments than any operator that is listed on a row further below it. For example, the expression *p++ is parsed as *(p++), and not as (*p)++.

Operators that are in the same cell (there may be several rows of operators listed in a cell) are evaluated with the same precedence, in the given direction. For example, the expression a=b=c is parsed as a=(b=c), and not as (a=b)=c because of right-to-left associativity.

#define in C

The #define directive (preprocessor directive) in C used to define macros (fragments of code with given names). Then the C preprocessor will recognize and expand them. There’re two types of macros:

Object-like macros:
An object-like macro is a simple identifier which will be replaced by a code fragment. It is called object-like because it looks like a data object in code that uses it. They are most commonly used to give symbolic names to numeric constants.

Example:

/*
File Name : macro.c
Author    : IziTutz (https://izitutz.com)
*/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define MSG         "Hello, World!" 

int main(int argc, char *argv[]) {
  char *message = (char *) malloc(strlen(MSG) + 1);

  strcpy(message, MSG);
  printf("%s\n", message);

  return 0;
}

and the output:

Hello, World!

Function-like macros:
You can also define macros whose use looks like a function call. These are called function-like macros.

Example:

/*
File Name : macro1.c
Author    : IziTutz (https://izitutz.com)
*/

#include <stdio.h>

#define SUM(a,b) a + b

int main(int argc, char *argv[]) {
  int a = 4, b = 9;

  printf("Sum of %d and %d is: %d\n", a, b, SUM(a, b));

  return 0;
}

and the output:

Sum of 4 and 9 is: 13

Quick sort program in C?

/*
File Name : quickSort.c
Author    : IziTutz (https://izitutz.com)
*/

#include <stdio.h>

void swap(int *a, int *b) {
  int temp = *a;

  *a = *b;
  *b = temp;
}

int partition(int intArray[], int low, int high) {
  int pivot = intArray[high];
  int index = (low - 1), index1 = low;

  while (index1 <= high - 1) {
    if (intArray[index1] <= pivot) {
      ++index;
      swap(&intArray[index], &intArray[index1]);
    }

    ++index1;
  }

  swap(&intArray[index + 1], &intArray[high]);

  return index + 1;
}

void quickSort(int intArray[], int low, int high) {
  if (low < high) {
    int part = partition(intArray, low, high);

    quickSort(intArray, low, part - 1);
    quickSort(intArray, part + 1, high);
  }
}

void printArray(int intArray[], int numOfElements) {
  int index = 0;

  while (index < numOfElements) {
    printf("%d ", intArray[index]); 
    ++index;
  }
  printf("\n");
}

int main(int argc, char *argv[]) {
  int intArray[] = {11, 79, 26, 35, 4, 21};
  int numOfElements = sizeof(intArray) / sizeof(int);

  printf("Before sorting: ");
  printArray(intArray, numOfElements);

  quickSort(intArray, 0, numOfElements - 1); 

  printf("After sorting: ");
  printArray(intArray, numOfElements);

  return 0;
}

and the output:

Before sorting: 11 79 26 35 4 21
After sorting: 4 11 21 26 35 79