Introduction to Data Science: A Comp-Math-Stat Approach

1MS041, 2021

©2021 Raazesh Sainudiin, Benny Avelin. Attribution 4.0 International (CC BY 4.0)

02. Numbers, Strings, Booleans and Sets

We will start by showing you some of the basic numeric capabilities of SageMath.

Numbers and Arithmetic Operations

A worksheet cell is the area enclosed by a gray rectangle.
You may type any expression you want to evaluate into a worksheet cell. We have already put some expressions into this worksheet.

When you are in a cell you can evaluate the expression in it by pressing or just by clicking the evaluate button below the cell.

To start with, we are going to be using SAGE like a hand-held calculator. Let's perform the basic arithmetic operations of addition, subtraction, multiplication, division, exponentiation, and remainder over the three standard number systems: Integers denoted by $\mathbb{Z}$, Rational Numbers denoted by $\mathbb{Q}$ and Real Numbers denoted by $\mathbb{R}$. Let us recall the real number line and the basics of number systems next.

Number sets within Complex Numbers

The most basic numbers are called natural numbers and they are denoted by $\mathbb{N} :=\{0, 1,2,3,\ldots\}$. See https://en.wikipedia.org/wiki/Natural_number.

The natural numbers are the basis from which many other number sets may be built by extension: the integers, by including (if not yet in) the neutral element 0 and an additive inverse (-n) for each nonzero natural number n; the rational numbers, by including a multiplicative inverse (1/n) for each nonzero integer n (and also the product of these inverses by integers); the real numbers by including with the rationals the limits of (converging) Cauchy sequences of rationals; the complex numbers, by including with the real numbers the unresolved square root of minus one (and also the sums and products thereof); and so on. These chains of extensions make the natural numbers canonically embedded (identified) in the other number systems.

Let us get our fingers dirty with some numerical operations in SageMath.

Note that anything after a '#' symbol is a comment - comments are ignored by SAGE but help programmers to know what's going on.

Example 1: Integer Arithmetic

Try evaluating the cell containing 1+2 below by placing the cursor in the cell and pressing .

Now, modify the above expression and evaluate it again. Try 3+4, for instance.

The multiplication operator is *, the division operator is /.

We will see very soon what a mathematical ring is, if you haven't seen this before.

The exponentiation operator is ^.

However, Python's exponentiation operator ** also works.

Being able to finding the remainder after a division is surprisingly useful in computer programming.

Another way of referring to this is 11 modulus 3, which evaluates to 2. Here % is the modulus operator.

You try

Try typing in and evaluating some expressions of your own. You can get new cells above or below an existing cell by clicking 'Insert' in the menu above and 'Insert Cell Above' or 'Insert Cell below'. You can also place the cursor at an existing cell and click + icon above to get a new cell below.

What happens if you put space between the characters in your expression, like: 1 + 2 instead of 1+2?.

Example 2: Operator Precedence for Evaluating Arithmetic Expressions

Sometimes we want to perform more than one arithmetic operation with some given integers.
Suppose, we want to

Perhaps this can be achieved by evaluating the expression "12/4+2*3-1"?

But could that also be interpreted as

In programming, there are rules for the order in which arithmetic operations are carried out. This is called the order of precedence.

The basic arithmetic operations are: +, -, *, %, /, ^.

The order in which operations are evaluated are as follows:

When operators are at the same level in the list above, what matters is the evaluation order (right to left, or left to right).

Operator precedence can be forced using parenthesis.

Operator precedence can be forced using nested parentheses. When our expression has nested parenthesis, i.e., one pair of parentheses inside another pair, the expression inside the inner-most pair of parentheses is evaluated first.

The following cell evaluates the mathematical expression:

$$\frac{12}{4+2} (3-1)$$

You try

Try writing an expression which will subtract 3 from 5 and then raise the result to the power of 3.

Find out for yourself what we mean by the precedence for exponentiation (^) being from right to left:

Try typing in the different expressions to find out:

Find an expression which will add the squares of four numbers together and then divide that sum of squares by 4.

Find what the precedence is for the modulus operator % that we discussed above: try looking at the difference between the results for 10%2^2 and 10%2*2 (or 10^2+2). Can you see how SageMath is interpreting your expressions?

Note that when you have two operators at the same precedence level (like % and *), then what matters is the order - left to right or right to left. You will see this when you evaluate 10%2*2.

Does putting spaces in your expression make any difference?

Using parenthesis or white spaces can improve readability a lot! So be generous with them to evaluate the following expression:

$$10^2 + 2^8 -4$$

The lesson to learn is that it is always good to use the parentheses: you will make it clear to someone reading your code what you mean to happen as well as making sure that the computer actually does what you mean it to!

Try this 10 minutes-long videos to get some practice if you are really rusty with order of operations:

Example 3: Rational Arithmetic

So far we have been dealing with integers. Integers are a type in SAGE. Algebraically speaking, integers, rational numbers and real numbers form a ring. This is something you will learn in detail in a maths course in Group Theory or Abstract Algebra, but let's take a quick peek at the definition of a ring.

The output above tells us that 1 is of type sage.rings.integer.Integer.

However, life with only integers denoted by $\mathbb{Z} := \{\ldots,-3,-2,-1,0,1,2,3,\ldots\}$ is a bit limited. What about values like $1/2$ or $\frac{1}{2}$?

This brings us to the rational numbers denoted by $\mathbb{Q}$.

Try evaluating the cell containing 1/2 + 2 below.

SageMath seems to have done rational arithmetic for us when evaluating the above expression.

Next, modify the expression in the cell below and evaluate it again. Try 1/3+2/4, for instance.

You can do arithmetic with rationals just as we did with integers.

You try

Write an expression which evaluates to 1 using the rationals 1/3 and 1/12, some integers, and some of the arithmetical operators - there are lots of different expressions you can choose, just try a few.

What does SageMath do with something like 1/1/5? Can you see how this is being interpreted? What should we do if we really want to evaluate 1 divided by 1/5?

Try adding some rationals and some integers together - what type is the result?

Example 4: Real Arithmetic (multi-precision floating-point arithmetic)

Recall that real numbers denoted by $\mathbb{R}$ include natural numbers ($\mathbb{N}$), integers ($\mathbb{Z}$), rational numbers ($\mathbb{Q}$) and various types of irrational numbers like:

Real numbers can be thought of as all the numbers in the real line between negative infinity and positive infinity. Real numbers are represented in decimal format, for e.g. 234.4677878.

We cannot do exact real arithmetic (but do it aproximately) in a computer with http://www.mpfr.org/'s multiprecision floating-point numbers, and can combine them with integer and rational types in SageMath.

Technical note: Computers can be made to exactly compute in integer and rational arithmetic. But, because computers with finite memory (all computers today!) cannot represent the uncountably infinitely many real numbers, they can only mimic or approximate arithmetic over real numbers using finitely many computer-representable floating-point numbers.

Let's take a peak at von Neumann architecture of any typical computer today.

Von_Neumann_Architecture.svg

The punch-line is that the Memory unit or Random Access Memory (RAM) inside the Central Processing Unit as well as Input and Output Devices are physical with finite memory. Therefore we cannot exactly represent all the uncontably infinitely many real numbers in $\mathbb{R}$ and need to resort to their approximation using floating point numbers.

See SageMath Quick Start on Numerical Analysis to understand SageMath's multiprecision real arithmetic.

For now, let's compare the results of evaluating the expressions below to the equivalent expressions using rational numbers above.

You try

Find the type of 1/2.

Try a few different ways of getting the same result as typing ((((1/5) / (1/10)) * (0.1 * 2/5) + 4/100))*5/(3/5) - this exact expression has already been put in for you in the cell below you could try something just using floating point numbers. Then see how important the parentheses are around rationals when you have an expression like this - try taking some of the parenthesis out and just play with complex expressions like these to get familiar.

Example 5: Variables and assignments of numbers and expressions

Loosely speaking one can think of a variable as a way of referring to a memory location used by a computer program. A variable is a symbolic name for this physical location. This memory location contains values, like numbers, text or more complicated types and crucially what is contained in a variable can change based on operations we do to it.

In SageMath, the symbol = is the assignment operator. You can assign a numerical value to a variable in SageMath using the assignment operator. This is a good way to store values you want to use or modify later.

(If you have programmed before using a a language like C or C++ or Java, you'll see that SageMath is a bit different because in SageMath you don't have to say what type of value is going to be assigned to the variable.)

Feel free to take a deeper dive into the computer science concept of assignment.

Just typing the name of a variable to get the value works in the SageMath Notebook, but if you are writing a program and you want to output the value of a variable, you'll probably want to use something like the print command.

Many of the commands in SageMath/Python are "methods" of objects.

That is, we access them by typing:

This is a huge advantage, once you get familiar with it, because it allows you to do only the things that are possible, and all such things. See SageMath programming guide for more details on this.

Let's try to hit the Tab button after the . following x below to view all available methods for x which is currently sqrt(2).

You try

Try assigning some values to some variables - you choose what values and you choose what variable names to use. See if you can print out the values you have assigned.

You can reassign different values to variable names. Using SageMath you can also change the type of the values assigned to the variable (not all programming languages allow you to do this).

You try

Assign the value 2 to a variable named x.

On the next line down in the same cell, assign the value 3 to a variable named y.

Then (on a third line) put in an expression which will evaluate x + y

Now try reassigning a different value to x and re-evaluating x + y

Example 6: Strings

Variables can be strings (an not just numbers). Anything you put inside quote marks will be treated as a string by SageMath/Python.

Strings as str and unicode are built-in sequence types for storing strings of bytes and unicode-encoded characters and and operating over them.

You can also create a string by enclosing them in single quotes or three consecutive single quotes. In SageMath/Python a character (represented by the char type in languages like C/C++/Scala) is just a string made up of one character.

You can assign values to more than one variable on the same line, by separating the assignment expressions with a semicolon ;. However, it is usually best not to do this because it will make your code easier to read (it is hard to spot the other assignments on a single line after the first one).

Using triple single quotes is especially useful if your string has single or double quotes within it. Triple quotes are often used to create DocString to document code in Pyhton/SageMath.

Pride and Prejudice as unicode

We will explore frequencies of strings for the most downloaded book at Project Gutenberg that publishes public domain books online. Currently, books published before 1923 are in the public domain - meaning anyone has the right to copy or use the text in any way.

Pride and Prejudice by Jane Austin had the most number of downloads and it's available from

A quick exploration allows us to see the utf-encoded text here.

For now, we will just show how to download the most popular book from the project and display it's contents for processing down the road.

Next we will show how trivial it is to "read" all the chapters into SageMath/Python using these steps:

(don't worry about the details now - we will revist these in detail later)

You can also type myString.split? for more "introspection" or documentation use ??. But generally help is all you need. Consult the SageMath documentation (or Google Search as needed). But note that in the exam, you will not have open internet access.

As we learn more we will return to this popular book's unicode which is stored in our data directory as data\pride_and_prejudice.txt.

Let us motivate the Python methods we will see soon by using them below to plot the number of occurences of he and she in each of the 61 chapters of the book.

Assignment Gotcha!

Let's examine the three assignments in the cell below.

The first assignment of x=3 is standard: Python/SageMath chooses a memory location for x and saves the integer value 3 in it.

The second assignment of y=x is more interesting and Pythonic: Instead of finding another location for the variable y and copying the value of 3 in it, Python/SageMath differs from the ways of C/C++. Since both variables will have the same value after the assignment, Python/SageMath lets y point to the memory location of x.

Finally, after the third assignment of y=2, x will be NOT be changed to 2 as because the behavior is not that of a C-pointer. Since x and y will not share the same value anymore, y gets its own memory location, containing 2 and x sticks to the originally assigned value 3.

As every instance (object or variable) has an identity or id(), i.e. an integer which is unique within the script or program, we can use id() to understand the above behavior of Python/SageMath assignments.

So, let's have a look at our previous example and see how the identities change with the assignments.

Example 6: Truth statements and Boolean values

Consider statements like "Today is Friday" or "2 is greater than 1" or " 1 equals 1": statements which are either true or not true (i.e., false). SageMath has two values, True and False which you'll meet in this situation. These value are called Booleans values, or values of the type Boolean.

In SageMath, we can express statements like "2 is greater than 1" or " 1 equals 1" with relational operators, also known as value comparison operators. Have a look at the list below.

Lets try some really simple truth statements.

Let us evaluate the following statement.

We can use these operators on variables as well as on values. Again, try assigning different values to x and y, or try using different operators, if you want to.

Note that when we check if something equals something else, we use ==, a double equals sign. This is because =, a single equals sign, is the assignment operator we talked about above. Therefore, to test if x equals y we can't write x = y because this would assign y to x, instead we use the equality operator == and write x == y.

We can also assign a Boolean value to a variable.

If we want to check if two things are not equal we use !=. As we would expect, it gives us the opposite of testing for equality:

You try

Try assigning some values to two variables - you choose what values and you choose what variable names to use. Try some truth statements to check if they are equal, or one is less than the other.

You try

Try some strings (we looked at strings briefly in Example 5 above). Can you check if two strings are equal? Can you check if one string is less than (<) another string. How do you think that Sage is ordering strings (try comparing "fred" and "freddy", for example)?

Example 7: Mathematical constants

Sage has reserved words that are defined as common mathematical constants. For example, pi and e behave as you expect. Numerical approximations can be obtained using the .n() method, as before.

Example 8: SageMath number types and Python number types

We showed how you can find the type of a number value and we demonstrated that by default, SageMath makes 'real' numbers like 3.1 into Sage real literals (sage.rings.real_mpfr.RealLiteral).

If you were just using Python (the programming language underlying most of SageMath) then a value like 3.1 would be a floating point number or float type. Python has some interesting extra operators that you can use with Python floating point numbers, which also work with the Sage rings integer type but not with Sage real literals.

Floor Division (//) - The division of operands where the result is the quotient in which the result is floored, "rounded towards negative infinity: examples: 9//2 = 4 and 9.0//2.0 = 4.0, -11//3 = -4, -11.0//3 = -4.0"

Similarly, we have the light-weight Python integer type int that we may want instead of SageMath integer type for non-mathematical faster arithmetic numerical operations.

One of the differences of SageMath rings integers to plain Python integers is that result of dividing one SageMath rings integer by another is a rational. This probably seems very sensible, but it is not what happens at the moment with Python integers.

We showed the .n() method. If X is some Sage real literal and we use X.n(20) we will be asking for 20 bits of precision, which is about how many bits in the computer's memory will be allocated to hold the number. If we ask for X.n(digits=20) will be asking for 20 digits of precision, which is not the same thing. Also note that 20 digits of precision does not mean showing the number to 20 decimal places, it means all the digits including those in front of the decimal point.

If you want to actually round a number to a specific number of decimal places, you can also use the round(...) function.

For deeper dive see documents on Python 2 Numeric Types, Python 3 Numeric Types and SageMath Numeric Types within SageMath Rings and Fields.

Sets

Set theory is at the very foundation in modern mathematics and is necessary to understand the mathematical notions of probability and statistics. We will take a practical mathemtical tour of the essential concepts from set theory that a data scientist needs to understand and build probabilistic models from the data using statistical principles.

Essentials of Set Theory for Probability and Statistics

These are black-board lectures typeset here.

Let us learn or recall elementary set theory. Sets are perhaps the most fundamental concept in mathematics.

Definitions

Set is a collection of distinct elements.

We write a set by enclosing its elements with curly brackets. Let us see some example next.

The set that contains no elements is the empty set. It is denoted by $$\boxed{\emptyset = \{\}} \ .$$

We say an element belongs to or does not belong to a set with the binary operators

$$\boxed{\in \ \text{or} \ \notin} \ .$$

For example,

We say a set $C$ is a subset of a set $D$ and write

$$\boxed{C \subset D}$$

if every element of $C$ is also an element of $D$. For example,

Set Operations

We can add distinct new elements to an existing set by union operation denoted by $\cup$ symbol.

For example

More formally, we write the union of two sets $A$ and $B$ as $$\boxed{A \cup B = \{x: x \in A \ \text{or} \ x \in B \}} \ .$$

The symbols above are read as $A$ union $B$ is equal to the set of all $x$ such that $x$ belongs to $A$ or $x$ belongs to $B$ and simply means that $A$ union $B$ or $A \cup B$ is the set of elements that belong to $A$ or $B$.

Similarly, the intersection of two sets $A$ and $B$ written as $$\boxed{A \cap B = \{x: x \in A \ \text{and} \ x \in B \}} $$ means $A$ intersection $B$ is the set of elements that belong to both $A$ and $B$.

For example

The set difference of two sets $A$ and $B$ written as

$$\boxed{A \setminus B = \{x: x \in A \ \text{and} \ x \notin B \}} $$

means $A \setminus B$ is the set of elements that belong to $A$ and not belong to $B$.

For example

The equality of two sets $A$ and $B$ is defined in terms of subsets as follows: $$\boxed{A = B \quad \text{if and only if} \quad A \subset B \ \text{and} \ B \subset A} \ .$$

Two sets $A$ anb $B$ are said to be disjoint if $$\boxed{ A \cap B = \emptyset} \ .$$

Given a universal set $\Omega$, we define the complement of a subset $A$ of the universal set by $$\boxed{A^c = \Omega \setminus A = \{x: x \in \Omega \ \text{and} \ x \notin A\}} \ .$$

An Interactive Venn Diagram

Let us gain more intuition by seeing the unions and intersections of sets interactively. The following interact is from interact/misc page of Sage Wiki.

Create and manipulate sets in SageMath.

Example 0: Lists before Sets

A list is a sequential collection that we will revisit in detail soon. For now, we just need to know that we can create a list by using delimiter , between items and by wrapping with left and right square brackets: [ and ]. For example, the following is a list of 4 integers:

List is one of the most primitive data structures and has a long history in a popular computer programming language called LISP - originally created as a practical mathematical notation for computer programs.

For now, we just use lists to create sets.

Example 1: Making sets

In SageMath, you do have to specifically say that you want a set when you make it.

Do the following in SageMath/Python to create the mathematical set:

$$X = \{1,2,3,4\}$$

This is a specialized datatype in Python and more details can be found in Python docs: https://docs.python.org/2/library/datatypes.html

Do the following in SageMath/Python to find out if:

$$4 \in X$$

i.e., if $4$ is an element of $X$ or if $4$ is an element of $X$ or $4$ is in $X$.

We can add new elements to a set.

But remember from the mathematical exposition above that sets contain distinct elements.

You try

Try making the set $Z=\{4,5,6,7\}$ next. The instructions are in the two cells below.

Make a set with the value 2/5 (as a rational) in it. Try adding 0.4 (as a floating point number) to the set.

Does SageMath do what you expect?

Example 2: Subsets

In lectures we talked about subsets of sets.

Recall that Y is a subset of X if each element in Y is also in X.

If you have time: We say Y is a proper subset of X if all the elements in Y are also in X but there is at least one element in X that it is not in Y. If X is a (proper) subset of Y, then we also say that Y is a (proper) superset of X.

Example 3: More set operations

Now let's have a look at the other set operations we talked about above: intersection, union, and difference.

Recall that the intersection of X and Y is the set of elements that are in both X and Y.

The union of X and Y is the set of elements that are in either X or Y.

The set difference between X and Y is the set of elements in X that are not in Y.

You try

Try some more work with sets of strings below.

Fruit and colours are different to us as people, but to the computer, the string 'orange' is just the string 'orange' whether it is in a set called fruit or a set called colours.

Try a few other simple subset examples - make up your own sets and try some intersections, unions, and set difference operations. The best way to try new possible operations on a set such as X we just created is to type a period after X and hit <TAB> key. THis will bring up all the possible methods you can call on the set X.

Infact, there are two ways to make sets in SageMath. We have so far used the python set to make a set.

However we can use the SageMath Set to maka sets too. SageMath Set is more mathematically consisitent. If you are interested in the SageMath Set go to the source and work through the SageMath reference on Sets.

But, first let us appreciate the difference between Python set and SageMath Set!

Example 4

Python also provides something called a frozenset, which you can't change like an ordinary set.

Under the Set's Hood

The key is to remember that sets are unordered: a set {1, 2, 3} is the same as the set {2, 1, 3} is the same as the set {3, 1, 2} ... (soon we will talk about ordered collections like lists where order is important - but for the moment just remember that a set is about collections of unique values or objects). Remember also that the (lower case s) set is a python type (in contrast to the 'more mathy' SageMath Set with a capital S). For many 'non-mathy' computing purposes, what matters about a set is the speed of being able to find things in the set without making it expensive (in computer power) to add and remove things, and the best way of doing this (invisible to the programmer actually using the set) is to base the set on a hash table. In practical terms what this means is that the ordering that Sage uses to actually display a set is related to the hash values it has given to the elements in the set which may be totally unrelated to what you or I would think of as any obvious ordering based on the magnitude of the values in the set, or the order in which we put them in, etc. Remember, you don't need to know anything about hash values and the 'under-the-hood' construction of sets for this course - this explanation is just to give a bit more background.

Using sets to find the words with 15 or more characters in P&P



Note that there are much more convenient methods to read text files that have been structured into a certain form. You are purposely being keept much closer to the raw data here. Starting directly with convenient high-level methods is not a good way to appreciate wrangling data closer to the source. Furthermore, it is easier to pick up the high-level methods later on.