Use of recursion for repetitive algorithms #TC1014

--Originally published at Learning With Python LWP

Recursion means “defining something in terms of itself” usually at some smaller scale, perhaps multiple times, to achieve your objective. For example, we might say “A human being is someone whose mother is a human being”, or “a directory is a structure that holds files and (smaller) directories”, or “a family tree starts with a couple who have children, each with their own family sub-trees”.

Programming languages generally support recursion, which means that, in order to solve a problem, functions can call themselves to solve smaller subproblems.


Use of loops with “for” #TC1014

--Originally published at Learning With Python LWP

It has the ability to iterate over the items of any sequence, such as a list or a string.

Syntax

for iterating_var in sequence:
   statements(s)

If a sequence contains an expression list, it is evaluated first. Then, the first item in the sequence is assigned to the iterating variable iterating_var. Next, the statements block is executed. Each item in the list is assigned to iterating_var, and the statement(s) block is executed until the entire sequence is exhausted.


WSQ 13 Cars #TC1014

--Originally published at Learning With Python LWP

What To Do

File input/output is our access to permanent stores of data that last beyond the run time of our application.

Write a program that opens and reads the file 93cars.dat.txt and produces the following data:

  • average gas mileage in city (City MPG)
  • average gas mileage on highway (Highway MPG)
  • average midrange price of the vehicles in the set.

You can find the data set at the following link from the Journal of Statistics Education.18337066_1541165832582960_587709461_n


WSQ 11 #TC1014

--Originally published at Learning With Python LWP

What To Do

Write a function called find_bananas which receives a single parameter called filename (a string) and returns a positive integer which is the number of times the word (string) “banana”  (or “BANANA” ) is found in the file. The banana can be any case (‘BaNana’ or ‘BANANA’ or ‘banana’, etc) and they can be “stuck together” like “banAnaBANANA” (that counts as two). Create your own test file (plain text) to check your work.18338920_1541181232581420_664806977_o


#WSQ10

--Originally published at Python fundamentals

Instructions

In this assignment you will write a function to calculate the square root of a number using the Babylonian method. You can search for that method, it will be easy to find.

The function should receive a number and return floating point number. Obviously you should test your function, so create a main program that asks the user a value, calculates the square root and displays that.

Procedure

To find the square root  of our given number we are going to create a funciton with a while loop, this loop will be execute untill the square root calculated using the babylonian method reaches a precision of  a thousandths decimals.

If you want even more details about this exercise you can read it here on another blog post that i made.

WSQ11-08Babylonian


#WSQ11

--Originally published at Python fundamentals

Instrunctions

You will find the instructions on Kencourses blog

 

Procedure

first exercise:

In the “distance” function we will create a function that takes 4 paramethers and return us the formula of distance between 2 points.

We are not going to use them on this point but, for the rest of the #WSQ11 we are going to use the math module and the string module, i will point it out when the time to use them comes, nevertheless im not repeating how to import both in the same file. So keep atention and see the picture because this is the way to do it.

wsq11-011.png

Second exercise:

In order to make the second one we will create 2 for loops, one in wich the i variable is going to be increasing untill the value is the same as a. On the second one our i variable will be decreasing  untill the value is 0.

WSQ11-02

third exercise:

We will create a function that using an if will determine if the factorial of the number its going to be find it using an algorithm or by just returning 1. (Which is the case for 0 and 1 factorial).

If the algorithm its required we are going to set the formula on a while loop and stops the loop if our counter reach our given number.

WSQ11-03

fourth exercise:

To calculate the main of a list we will create a for loop that is adding each one of the elements of our list in a variable to finally divide this value by the number of elelements (wich is found it using a counter that counts on every iteration).

WSQ11-04

fifth exercise:

To find the samaller number between 4 values, i created a function that determines the smaller number between two values, it wasn’t the most eficient

wsq11-05a.png
wsq11-05b.png
Continue reading "#WSQ11"

#quiz09

--Originally published at Python fundamentals

Instructions

Write a function that receives four parameters: x1, y1, x2, y2 which are all floating point values.

The function is called distance and returns (float) the distance between x1,y1 and x2,y2 on the cartesian coordinate plane.

Procedure

We will just type the formula to find the distance between two points in the return of a function (we will use the math module to calculate the square root)

quiz09

Sources: http://www.mathportal.org/calculators/analytic-geometry/distance-and-midpoint-calculator.php


WSQ08 “I am 196”

--Originally published at Python fundamentals

Instrunctions

Your job is to create a program that asks the user for two pieces of data:

  • The lower bound of the sequence
  • The upper bound of the sequence

Then you check the values from the lower bound (inclusive) to the upper bound (inclusive) and make a report of them. During the analysis of each number, if a Lychrel number is found it should be reported immediately with something like “Found a Lychrel number: 196”.

The report must show:
  • The range of numbers analysed (lower to upper bound)
  • The number of natural palindromes (no addition to inverse needed)
  • The number of non-Lycherels encountered (become palindromes)
  • The number of Lycherel number candidates (that did not converge to palindrome)

Since you will not be able to prove that a number is Lycherel (since you cannot computer forever to check), our definition for a Lycherel candidate will be if a number does not converge after 30 iterations of applying the addition to the inverse.

Procedure

We will create a function that using a for loop and a palindrome funcion, (wich we are going to import) will determine if a number its a natural palindrome or not.

Then in the for loop we will use a while loop that will be execute 30 times, we will put two ifs in this while loop, one that will tell us if the numer after 30 iteration or less, results being palindrome and another one that will tell us if it doesn’t happen.

wsq08(2)

wsq08


Quiz 11

--Originally published at Python

El quiz 11, hasta el momento el quiz mas dificil de todos. Mas que nada por el largo. Empezemos con lo basico, las instrucciones.

Aqui esta el link para las instrucciones con ejemplos:

https://kenscourses.com/tc1014winter2017/wp-content/uploads/2017/03/TC101_FinalExamQuestions.pdf

1: Escribe el función distancia cual recibe 4 números (x1, y1, x2, y2) cuales representan dos puntos en espacio (x1,y1) y (x2,y2). El método debe regresar la distancia entre los dos puntos. Recuerda que el valor cuadrada del hipotenusa del triangulo es igual que la suma de las cuadradas de los otro dos lados del triangulo (the hypotenuse squared is equal to the sum of the squares of the other two sides).

2. (5 puntos) Escribe un función que se llama triangulo cual recibe un parámetro size y imprime un triangulo derecho como el siguiente. El renglón mas grande debe llevar size numero de “T”. SOLO imprime los “T”s y los endlines. Nota que no hay characteres (espacios) a la derecha de los T’s. Debe usar un ciclo “for” para controlar el repetición. Ejemplo es si size era 6

3. Escribe la función factorial cual recibe un entero “x” y regresa el valor de x! Recuerda que 0! = 1, 1! = 1, 2! = 2, 3!= 6, 4! = 24, etc. Para los de Python: NO PUEDES usar el factorial como parte del module “math”

4. Escribe una función que se llama promedio_lista que recibe un parámetro (una lista (Python) o arreglo/Vector de C++) de valores float y regresa como float el promedio de los números en la lista.

5. Escribe una función que se llama smallest_of_four cual recibe cuatro valores float como parametros y regresa el minimo (más pequeño) de los valores. Ojo: puede recibir unos valores iguales.

6. Escribe una función que se llama fibonacci cual recibe un número n

10 ganon
Continue reading "Quiz 11"

#quiz06

--Originally published at Python fundamentals

Instructions

Return to the 46 exercises page and solve the exercises 6 up to 10.

Procedure

Exercise 6:

Define a function sum() and a function multiply() that sums and multiplies (respectively) all the numbers in a list of numbers. For example, sum([1, 2, 3, 4]) should return 10, and multiply([1, 2, 3, 4]) should return 24

We will create 2 funcitons, one for addition and other for multiplication, in the first one we will create a loop that will go through ach one of the numbers on the list and add into a new variable know as total.

In the second one, we will do the same but instead of addition we will use substraction.

exercise6.png

Exercise 7:

Define a function reverse() that computes the reversal of a string. For example, reverse("I am testing") should return the string "gnitset ma I".

We will create a function that uses a for loop to go through each one of the characters of a string and add it to a new string callled “word” in an inverse order.

exercise7.png

Exercise 8:

Define a function is_palindrome() that recognizes palindromes (i.e. words that look the same written backwards). For example, is_palindrome("radar") should return True.

We will use our current reverse function to find the reversal of a string, if the reversal its the same as the original string, then palindorme its true, we will do this second part in another function called palindrome.

Exercise8

Exercise 9:

Write a function is_member() that takes a value (i.e. a number, string, etc) x and a list of values a, and returns True if x is a member of a, False otherwise. (Note that this is exactly what the in operator does, but for the sake of the exercise you should pretend Python did not have this

Exercise9
Exercise10
Continue reading "#quiz06"