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

- On 4. oktober 2018
- By Read More

## 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.

isleap(year) - Return 1 for leap years, 0 for non-leap years.

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')

Slightly altering this we can find the longest unhyphenated word, 'disappointment', which has 14 characters.

- On 6. oktober 2018
- By Read More

## Java Programming Tutorial

Hints: Product of 1 to 13 (=6227020800) is outside the range of int [-2147483648, 2147483647], but within the range of long.

Exercise CheckerBoard (nested-loop): Write a program called CheckerBoard that displays the following n×n (n=7) checkerboard pattern using two nested for-loops.

Exercise TimeTable (nested-loop): Write a program called TimeTable to produce the multiplication table of 1 to 9 as shown using two nested for-loops: Modify the program to print the multiplication table of 1 to 12.

On the opposite diagonal, row + col = size + 1, where row and col begin from 1.

Use the graphic debugger of Eclipse/NetBeans to debug the program by single-step through the program and tabulating the values of i and factorial at the statement marked by (*).

Exercise FileScanner (File Input): Write a program called FileScanner to read an int, a double, and a String form a text file called "in.txt", and produce the following output: You need to create a text file called "in.txt"

Exercise CircleComputation (User Input): Write a program called CircleComputation, which prompts user for a radius (in double) and compute the area and circumference of the circle rounded to 2 decimal places.

For example, Hints: To repeat until input is -1 (called sentinel value), use the following pattern: Exercise ReverseString: Write a program called ReverseString, which prompts user for a String, and prints the reverse of the String.

Exercise CheckVowelsDigits: Write a program called CheckVowelsDigits, which prompts the user for a String, counts the number of vowels (a, e, i, o, u, A, E, I, O, U) and digits (0-9) contained in the string, and prints the counts and the percentages (with 2 decimal digits). For example, Hints:

Your output shall look like: Hints: For a n-bit binary number bn-1bn-2...b1b0, bi∈{0,1}, the equivalent decimal number is bn-1×2n-1+bn-2×2n-2+ ...+b1×21+b0×20.

To convert a char c (of digit '0' to '9') to int (0 to 9), simply subtract by char '0', e.g., '5'-'0' gives int 5.

Your output shall look like: Hints: For a n-digit hexadecimal number hn-1hn-2...h1h0, hi∈{0,…,9,A,…,F}, the equivalent decimal number is hn-1×16n-1+hn-2×16n-2+ ...+h1×161+h0×160.

However, you do not need a big nested-if statement of 16 cases (or 22 considering the upper and lower letters). Extract the individual character from the hexadecimal string, says c.

If char c is between '0' to '9', you can get the integer offset via c-'0'. If c is between 'a' to 'f' or 'A' to 'F', the integer offset is c-'a'+10 or c-'A'+10.

Exercise GradesAverage (Array): Write a program called GradesAverage, which prompts user for the number of students, reads it from the keyboard, and saves it in an int variable called numStudents.

It then prompts user for the grades of each of the students and saves them in an int array called grades. Your program shall check that the grade is between 0 and 100.

Exercise (Method): Write a boolean method called hasEight(), which takes an int as input and returns true if the number contains the digit 8 (e.g., 18, 808).

The signature of the method is as follows: Write a program called MagicSum, which prompts user for numbers, and produce the sum of numbers containing the digit 8.

A sample output of the program is as follows: Hints: To repeat until input is -1 (called sentinel value): Hints: You can either convert the int to String and use the String's charAt() to inspect each char;

The method's signature is as follows: Also write a test driver to test this method (you should test on empty array, one-element array, and n-element array).

You need to write another version for double[], e.g., The above is known as method overloading, where the same method name can have many versions, differentiated by its parameter list.

The method's signature is as follows: Also write a test driver to test this method (you should test on empty array, one-element array, and n-element array).

Exercise (Array and Method): Write a boolean method called equals(), which takes two arrays of int and returns true if the two arrays are exactly the same (i.e., same length and same contents).

Exercise GradesStatistics (Method): Write a program called GradesStatistics, which reads in n grades (of int between 0 and 100, inclusive) and displays the average, minimum, maximum, median and standard deviation.

The formula for calculating standard deviation is: Hints: Take note that besides readGrade() that relies on global variable grades, all the methods are self-contained general utilities that operate on any given array.

Exercise (Array and Method): Write a program called PrintChart that prompts the user to input n non-negative integers and draws the corresponding horizontal bar chart.

A sample session is as follows: Exercise Arithmetic (Command-line arguments): Write a program called Arithmetic that takes three command-line arguments: two integers followed by an arithmetic operator (+, -, * or /).

The signatures of the methods are: Compare the values computed using the series with the JDK methods Math.sin(), Math.cos() at x=0, π/6, π/4, π/3, π/2 using various numbers of terms.

Exercise FibonacciInt (Overflow) : Write a program called FibonacciInt to list all the Fibonacci numbers, which can be expressed as an int (i.e., 32-bit signed integer in the range of [-2147483648, 2147483647]).

Your output shall look like: Modify your program (called FactorialInt), to list all the factorials, that can be expressed as an int (i.e., 32-bit signed integer in the range of [-2147483648, 2147483647]).

Exercise Fibonacci (Overflow): Write a program called FibonacciInt to list all the Fibonacci numbers, which can be expressed as an int (i.e., 32-bit signed integer in the range of [-2147483648, 2147483647]). The output shall look like: Hints: The maximum 32-bit int is kept in constant Integer.MAX_VALUE.

The method has the following header: Write a program called NumberConversion, which prompts the user for an input number, an input radix, and an output radix, and display the converted number.

To produce an int between 0 and 99, use: Exercise WordGuess: Write a program called WordGuess to guess a word by trying to guess the individual characters.

Your program shall look like: Hints: Exercise DateUtil: Complete the following methods in a class called DateUtil: To find the day of the week (Reference: Wiki "Determination of the day of the week"): For example: 2012, Feb, 17 The skeleton of the program is as follows: You can compare the day obtained with the Java's Calendar class as follows: The calendar we used today is known as Gregorian calendar, which came into effect in October 15, 1582 in some countries and later in other countries.

In Gregorian calendar, a leap year is a year that is divisible by 4 but not divisible by 100, or it is divisible by 400, i.e., the Gregorian calendar omits century years which are not divisible by 400.

Hence, the full definition is: For example, suppose n = 5: Exercise (Factorial) (Recursive): Write a recursive method called factorial() to compute the factorial of the given integer.

The recursive algorithm is: Compare your code with the iteractive version of the factorial(): Hints: Notes: Exercise (Fibonacci) (Recursive): Write a recursive method to compute the Fibonacci sequence of n, defined as follows: Compare the recursive version with the iteractive version written earlier.

JDK provides searching and sorting utilities in the Arrays class (in package java.util), such as Arrays.sort() and Arrays.binarySearch() - you don't have to write your searching and sorting in your production program.

For example, suppose that we want to search for the item 18 in the list {11 14 16 18 20 25 28 30 34 40 45}: Write a recursive function called binarySearch() as follows: Use the following pesudocode implementation: Also write an overloaded method which uses the above to search the entire array: Exercise (Bubble Sort): (Reference: Wikipedia "Bubble Sort") The principle is to scan the elements from left-to-right, and whenever two adjacent elements are out-of-order, they are swapped.

Write a method to sort an int array (in place) with the following signature: Use the following pesudocode implementation: Exercise (Selection Sort): (Reference: Wikipedia "Selection Sort") This algorithm divides the lists into two parts: the left-sublist of items already sorted, and the right-sublist for the remaining items.

The algorithm proceeds by finding the smallest (or largest) items from the right-unsorted-sublist, swapping it with the leftmost element of the right-unsorted-sublist, and increase the left-sorted-sublist by one.

For example, given the list {9 6 4 1 5}: Write a method to sort an int array (in place) with the following signature: Exercise (Insertion Sort): (Reference: Wikipedia "Insertion Sort") Similar to the selection sort, but extract the leftmost element from the right-unsorted-sublist, and insert into the correct location of the left-sorted-sublist.

For example, given {9 6 4 1 5 2 7}: Write a method to sort an int array (in place) with the following signature: Exercise (Recursive Quick Sort): (Reference: Wikipedia "Quick Sort") Quicksort is a recursive divide and conqueralgorithm.

The steps are: For example, given {20 11 18 14 15 9 32 5 26} Write a recursive function called quickSort() as follows: Hints: See Binary Search.

Exercise (Merge Sort): (Reference: Wikipedia "Merge Sort") [TODO] Exercise (Heap Sort): (Reference: Wikipedia "Heap Sort") [TODO] Exercise (Perfect and Deficient Numbers): A positive integer is called a perfect number if the sum of all its factors (excluding the number itself, i.e., proper divisor) is equal to its value.

Using the methods, write a program called PerfectNumberList that prompts user for an upper bound (a positive integer), and lists all the perfect numbers less than or equal to this upper bound.

The output shall look like: Hints: To check if a number n is a prime, the simplest way is try dividing n by 2 to √n.

Exercise (Prime Factors): Write a method isProductOfPrimeFactors(int posInt) that takes a positive integer, and return true if the product of all its prime factors (excluding 1 and the number itself) is equal to its value.

Assume that a and b are positive integers, and a≥b, the Euclid algorithm is based on these two properties: For example, The pseudocode for the Euclid algorithm is as follows: Write a method called gcd() with the following signature: Your methods shall handle arbitrary values of a and b, and check for validity.

- On 6. oktober 2018
- By Read More

## Check divisibility by 7

(adsbygoogle = window.adsbygoogle ||

// A Program to check whether a number is divisible by 7 #include <stdio.h> int isDivisibleBy7( int num ) {

// Recur for ( num / 10 - 2 * num % 10 )

return isDivisibleBy7( num / 10 - 2 * ( num - num / 10 * 10 ) );

// Function to check whether a number is divisible by 7 static boolean isDivisibleBy7(int num) { // If number is negative, make it positive if( num <

return isDivisibleBy7( num / 10 - 2 * ( num - num / 10 * 10 ) );

Python program to check whether a number is divisible by 7 # Function to check whether a number is divisible by 7 def isDivisibleBy7(num) : # If number is negative, make it positive if num <

0 : return isDivisibleBy7( -num ) # Base cases if( num == 0 or num == 7 ) : return True if(

return isDivisibleBy7( num / 10 - 2 * ( num - num / 10 * 10 ) ) # Driver program num = 616 if(isDivisibleBy7(num))

class GFG { // Function to check whether a // number is divisible by 7 static bool isDivisibleBy7(int num) { // If number is negative,

// PHP Program to check whether // a number is divisible by 7 // Function to check whether a // number is divisible by 7 function isDivisibleBy7( $num ) {

After observing that 7 divides 21, we can perform the following: after multiplying by 2, this becomes and then Eliminating the multiple of 21 gives and multiplying by -1 gives There are other interesting methods to check divisibility by 7 and other numbers.

- On 17. september 2021

**Excel - Allow only Text or only Numbers Entered into a Cell in Excel - Custom Formulas**

(spreadsheet available at teachmsoffice.com soon) This tutorial shows you how to limit the entry of data into a cell to only those ..

**Theory Of Computation 7,DFA of binary no which is divisible by 3**

In this video I have discussed about how to construct minimal DFA which accepts set of all strings over {0,1} which when interpreted as a binary number is ...

**FlowChart to Get the Sum of Two Numbers**

FlowChart to Get the Sum of Two Numbers Beginners Tutorial for Programmers Here's the link to download the IDE

**MIPS Tutorial 19 Getting User's Input integers**

Learn how to get an integer number from the user!

**Can You Solve This?**

Can you figure out the rule? Did you see the exponents pattern? Why do you make people look stupid? How .

**Java Programming Tutorial - 15 - Use Methods with Parameters**

Facebook - GitHub - Google+ .

**Java Programming Tutorial - 32 - Arrays in Methods**

Facebook - GitHub - Google+ .

**Boolean function example (C++ programming tutorial)**

Check out for more free engineering tutorials and math lessons! C++ Programming Tutorial: Boolean function example

**Simple Python for loop, using range and user input, converting string to int**

Looping through range(10) and printing the count as we go along for i in range(10): print(i) The output is numbers ranging from 0 to 9 OUTPUT: 0 1 2 3 4 5 6 7 8 ...

**Deterministic Finite Automata ( DFA ) with (Type 1: Strings ending with)Examples**

This is the first video of the new video series "Theoretical Computer Science(TCS)" guys :) Hope you guys get a clear understanding of this subject Thank you ...