AI News, Difference between revisions of "How to Think Like a Computer Scientist: Learning with Python 2nd Edition/Solutions"

Difference between revisions of "How to Think Like a Computer Scientist: Learning with Python 2nd Edition/Solutions"

The following section contains answers to the exercises in the Book.

Why does a call to num_digits(-24) result in an infinite loop (hint: -1/10 evaluates to -1)?

The loop will end when n = 0, and per above -1/10 == -1, causing an infinite loop.

Encapsulate: in a function named count_letters, and generalize it so that it accepts the string and the letter as arguments.

Now rewrite the count_letters function so that instead of traversing the string, it repeatedly calls find (the version from Optional parameters), with the optional third parameter to locate new occurences of the letter being counted.

ceil function finds the lowest integeral value greater than or equal to x.

deepcopy would have come handy in exercises you didn't have to solve regarding object reference, thus no answer is excpected here.

The word 'alice' occurs 386 times (not including 12 occurences of 'alice's')

C++ Programming Language

This chapter explains the features, technical details and syntaxes of the C++ programming language.

To be a proficient programmer, you need to master two things: (1) the syntax of the programming language, and (2) the core libraries (i.e., API) associated with the language.

Currently, there are two versions: C++ is a powerful language for high-performance applications, including writing operating systems and their subsystems, games and animation.

For example, to effectively use the C++ Standard Template Library (STL), you need to understand these difficult concepts: pointers, references, operator overloading and template, on top of the object-oriented programming concepts such as classes and objects, inheritance and polymorphism;

The C++ compiler does not issue warning/error message for many obvious programming mistakes, undefined and unspecified behaviors, such as array index out of range, using an uninitialized variable, etc, due to the focus on performance and efficiency rather than the ease of use - it assumes that those who choose to program in C++ are not dummies.

Below is a simple C++ program that illustrates the important programming constructs (sequential flow, while-loop, and if-else) and input/output.

They can be referenced via fully qualified name std::cout and std::endl, or simply as cout and endl with a "using namespace std;"

Instead of using numeric value of zero and non-zero, you can also use EXIT_SUCCESS or EXIT_FAILURE, which is defined in the cstdlib header (i.e., you need to "#include <cstdlib>".

Comments are not programming statements and are ignored by the compiler, but they VERY IMPORTANT for providing documentation and explanation for others to understand your program (and also for yourself three days later).

During program development, instead of deleting a chunk of statements permanently, you could comment-out these statements so that you could get them back later, if needed.

This is because period crashes with decimal point - it is hard for the dumb computer to differentiate between period and decimal point!) For examples, Block: A block (or a compound statement) is a group of statements surrounded by braces { }.

Blocks are used as the body in constructs like function, if-else and loop, which may contain multiple statements but are treated as one unit.

You need to use a white space to separate two keywords or tokens, e.g., Additional white spaces and extra lines are, however, ignored, e.g., Formatting Source Codes: As mentioned, extra white spaces are ignored and have no computational significance.

However, proper indentation (with tabs and blanks) and extra empty lines greatly improves the readability of the program, which is extremely important for others (and yourself three days later) to understand your programs.

preprocessor directive, which begins with a # sign (such as #include, #define), tells the preprocessor to perform a certain action (such as including a header file, or performing text replacement), before compiling the source code into object code.

to include the input/output stream library header into our program, so as to use the IO library function to carry out input/output operations (such as cin and cout).

variable name is a noun, or a noun phrase made up of several words. The first word is in lowercase, while the remaining words are initial-capitalized, with no spaces between words.

it by declaring its name and type, in one of the following syntaxes: Example, Take note that: When a variable is declared, it contains garbage until you assign an initial value.

An expression is a combination of operators (such as addition '+', subtraction '-', multiplication '*', division '/') and operands (variables or literal values), that can be evaluated to yield a single value of a certain type.

The syntax for assignment statement is: The assignment statement should be interpreted this way: The expression on the right-hand-side (RHS) is first evaluated to produce a resultant value (called rvalue or right-value).

Integers: C++ supports these integer types: char, short, int, long, long long (in C++11) in a non-decreasing order of size.

Floating-point Numbers: There are 3 floating point types: float, double and long double, for single, double and long double precision floating point numbers.

In addition, many C++ library functions use a type called size_t, which is equivalent (typedef) to a unsigned int, meant for counting, size or length, with 0 and positive integers.

Similarly, the cfloat header (ported from C's float.h) contain information on limits for floating point numbers, such as minimum number of significant digits (FLT_DIG, DBL_DIG, LDBL_DIG for float, double and long double), number of bits for mantissa (FLT_MANT_DIG, DBL_MANT_DIG, LDBL_MANT_DIG), maximum and minimum exponent values, etc.

In brief, It is important to take note that char '1' is different from int 1, short 1, float 1.0, double 1.0, and String "1".

For example, short 1 is "00000000 00000001", int 1 is "00000000 00000000 00000000 00000001", long long 1 is "00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000001", float 1.0 is "0 01111111 0000000 00000000 00000000", double 1.0 is "0 01111111111 0000 00000000 00000000 00000000 00000000 00000000 00000000", char '1' is "00110001".

Besides the default base 10 integers, you can use a prefix '0' (zero) to denote a value in octal, prefix '0x' for a value in hexadecimal, and prefix '0b' for binary value (in some compilers), e.g., A

printable char literal is written by enclosing the character with a pair of single quotes, e.g., 'z', '$', and '9'.

The commonly-used escape sequences are: Notes: The cctype header (ported from C's ctype.h) provides functions such as isalpha(), isdigit(), isspace(), ispunct(), isalnum(), isupper(), islower() to determine the type of character;

String literal is composed of zero of more characters surrounded by a pair of double quotes, e.g., "Hello, world!", "The sum is ", "".

For example, In an expression, bool values and literals are converted to int 0 for false and 1 (or a non-zero value) for true.

C++ supports the following arithmetic operators for numbers: short, int, long, long long, char (treated as 8-bit signed integer), unsigned short, unsigned int, unsigned long, unsigned long long, unsigned char, float, double and long double.

That is, 1 + 2 + 3 + 4 is treated as (((1+2) + 3) + 4).

However, if the two operands belong to different types, the compiler promotes the value of the smaller type to the larger type (known as implicit type-casting).

For example, Study the output of the following program: In arithmetic operations, the resultant value wraps around if it exceeds its range (i.e., overflow or underflow).

Besides the usual simple assignment operator '=' described earlier, C++ also provides the so-called compound assignment operators as listed: C++ supports these unary arithmetic operators: increment '++' and decrement '--'.

For example, The increment/decrement unary operator can be placed before the operand (prefix operator), or after the operands (postfix operator).

There are two kinds of type casting: When you assign a value of a fundamental (built-in) type to a variable of another fundamental type, C++ automatically converts the value to the receiving type, if the two types are compatible.

C++ provides six comparison operators (or relational operators): In C++, these comparison operations returns a bool value of either false (0) or true (1 or a non-zero value).

The truth tables are as follows: Example: Exercise: Given the year, month (1-12), and day (1-31), write a boolean expression which returns true for dates before October 15, 1582 (Gregorian calendar cut over date).

15) There are three basic flow control constructs - sequential, conditional (or decision), and loop (or iteration), as illustrated below.

Sequential flow is the most common and straight-forward, where programming statements are executed in the order that they are written - from top to bottom in a sequential manner.

Suppose that your program prompts user for a number between 1 to 10, and checks for valid input, do-while with a boolean flag could be more appropriate.

For example, The following diagram illustrates a nested for-loop, i.e., an inner for-loop within an outer for-loop.

Try out the following program, which prints a 8-by-8 checker box pattern using nested loops, as follows: This program contains two nested for-loops.

It seems to be an endless loop (or infinite loop), but it is usually terminated via a break or return statement inside the loop body.

It is also important to write programs that others (and you yourself three days later) can understand, so that the programs can be maintained - I call these programs good programs.

Here are the suggestions: There are generally three classes of programming errors: Here are the common debugging techniques: How to ensure that your program always produces correct result, 100% of the times?

Program testing usually involves a set of representative test cases, which are designed to catch the major classes of errors.

You can declare and (a) initialize a string with a string literal, (b) initialize to an empty string, or (c) initialize with another string object.

header provides so-called I/O manipulators for formatting input and output: [TODO] Suppose that you want to find the average of the marks for a class of 30 students, you certainly do not want to create 30 variables: mark1, mark2, ..., mark30.

You can also initialize the array during declaration with a comma-separated list of values, as follows: You can refer to an element of an array via an index (or subscript) enclosed within the square bracket [ ].

For example, suppose that marks is an int array of 5 elements, then the 5 elements are: marks[0], marks[1], marks[2], marks[3], and marks[4].

You can find the array length using expression sizeof(arrayName)/sizeof(arrayName[0]), where sizeof(arrayName) returns the total bytes of the array and sizeof(arrayName[0]) returns the bytes of first element.

You can process all the elements of an array via a loop, for example, [TODO] C++11 introduces a range-based for loop (or for-each loop) to iterate thru an array, as illustrated in the following example: To compile the program under GNU GCC (g++), you may need to specify option -std=c++0x or -std=c++11: For example, For 2D array (table), the first index is the row number, second index is the column number.

The benefits of using functions are: Two parties are involved in using a function: a caller who calls the function, and the function called.

The function receives these argument(s), performs the programmed operations within the function's body, and returns a piece of result back to the caller.

In the above example, a reusable function called getArea() is defined, which receives a parameter (in double) from the caller, performs the calculation, and return a piece of result (in double) to the caller.

In C++, you need to declare a function prototype (before the function is used), and provide a function definition, with a body containing the programmed operations.

The syntax for function definition is as follows: Inside the function's body, you could use a return statement to return a value (of the returnValueType declared in the function's header) and pass the control back to the caller.

function prototype tells the compiler the function's interface, i.e., the return-type, function name, and the parameter type list (the number and type of parameters).

Suppose that you need a function to perform certain actions (e.g., printing) without a need to return a value to the caller, you can declare its return-value type as void.

Recall that a function receives arguments from its caller, performs the actions defined in the function's body, and return a value (or nothing) to the caller.

When the function is invoked by a caller, the caller must supply so-called actual parameters (or arguments), whose value is then used for the actual computation.

They are also called automatic variables, because they are created and destroyed automatically - no programmer's explicit action needed to allocate and deallocate them.

For boolean function, you should simply return the resultant bool value of the comparison, instead of using a conditional statement, as follow: C++ introduces so-called default arguments for functions.

C++ introduces function overloading (or function polymorphism, which means many forms), which allows you to have multiple versions of the same function name, differentiated by the parameter list (number, type or order of parameters).

To differentiate between different versions of an overloaded function, many compilers (such as GNU GCC) adopt a name mangling or name decoration scheme for naming functions.

Each of the function is identified via a prefix __Z, followed by an integer containing the number of characters of the function name (3 in this case for "fun"), followed by the parameter type list (where i for int and d for double).

That is, you can modify the contents of the caller's array inside the invoked function - there could be side effect in passing arrays into function.

Hence, if you wish to write a function that modifies the contents of an array (e.g., sorting the elements of an array), you need to rely on pass-by-reference to work on the same copy inside and outside the function.

Use const whenever possible for passing references as it prevent you from inadvertently modifying the parameters and protects you against many programming errors.

Pass-by-reference is NOT commonly used for fundamental types (such as int, double) - the above example is purely meant for academic illustration.

But it is used extensively for compound types (such as arrays and objects) to avoid cloning huge data for better performance.

The signatures of some of these functions are: The cstdlib header (ported from C's stdlib.h) provides a function rand(), which generates a pseudo-random integral number between 0 and RAND_MAX (inclusive).

header provides ifstream (input file stream) and ofstream (output file stream) for file input and output.

(It is known as package in UML and Java.) The entity name under a namespace is qualified by the namespace name, followed by :: (known as scope resolution operator), in the form of namespace::entityName.

To reference an identifier under a namespace, you have three options: As mentioned, all the standard C++ library components are packaged inside a namespace called std.

In C++, an entity (variable, function, or class) belongs to the global namespace (identified by :: with no namespace name), if it is not enclose within a namespace declaration.

Character arrays and pointers - part 1

See complete series on pointers in C/C++ here: See part 2 of this lesson ..

Learn Python Programming - 22 - Sum Two (Exercise)

Code Notes -- Enroll in Course -- How to write a sum of two function? Let's take two inputs and return their .

How to split a Java String - 052

In this tutorial we're going to look at how to split a string in Java. We can split the string by character or split the string by words. We'll look at both! We're going to ...

Blend W

Anime Snoop Dogg the cute japanese girl finds a free job posting at a maid cafe serving up delicious snacks and a double cheeseburger with dr dre what you ...

Java Programming Tutorial - 6 - Getting User Input

Facebook - GitHub - Google+ .

Fun with Strings

Experimenting and seeing what we can do with strings.

String Compare Without Library Function

Here in this tutorial i have explained about how to compare the strings without using the library function.

R tutorial: The basic data types in R

In this video you will understand what the basic data types are in R. Want to take the interactive coding exercises and earn a certificate? Join DataCamp today ...

Java Programming Tutorial - 32 - Arrays in Methods

Facebook - GitHub - Google+ .

JavaScript (ES6) - Algorithms - (genAnagrams) - find all possible anagrams of a string

In this video, I code out the following function... genAnagrams - (generate anagrams) is a function that takes a string and returns an array of all the unique ...