Tag Archive for Python

Solving the Even Fibonacci Challenge

The Even Fibonacci Challenge, Problem 2 in the Project Euler Challenge. The modified problem requires adding the even-valued terms in the series which do not exceed a given integer N.

My solution is as follows:

Reading a file in Python

In this article, I will show how to open, read and close a file in Python.

This code sample is for a function that accepts a filename as a parameter, opens the file given by the filename parameter, reads the file line by line ( fd.readline() ), prints the line and finally closes the file. The loop is broken when nothing is read from the file any longer.

An optimisation to the above code (thanks to Dr Jean-Paul Ebejer [x2]) would be:

 

A Binary Search Tree in Python

A Binary Search Tree (BST) is a rooted binary tree where items in the left subtree are less than the value of the root and items in the right subtree are greater than the value of the root. A binary tree is a data structure which consists of either a single node called the root or one where each node in in the binary tree has at most 2 children referred to as the left or right child.

A labeled binary tree of size 9 and height 3, with a root node whose value is 2. The above tree is unbalanced and not sorted. By Derrick Coetzee (Own work) [Public domain], via Wikimedia Commons

Code

The code is split into two classes, one representing an individual node in the BST, and the other the tree with its individual operations. Note that this implementation ignored duplicates.

The Node Class

 

The Tree Class

 

Testing the code

 

The result should appear as follows:

Hope you found this tutorial useful!

Reimporting a Module in Python 3

If you are using a module in a Python Console, and make changes to the Module, you can “re-import” the module as follows:

This will reload the module and make the changes available.

Hope that you’ll find this information useful.