Pages

Project Euler, Python and Notepad++

I have taken an interest in Project Euler lately. This project presents a series of challenging mathematical or computer programming problems that will require more than just mathematical insights to solve. Although mathematics will help you arrive at elegant and efficient methods, the use of a computer and programming skills will be required to solve most problems.

The next thing for me to consider was what is the programming language to use. I thought of C# initially but soon change my mind because it is too heavy weight. I decide to use something light weight and dynamic. With a desire to learn something new, I have made Python to be my choice.

Lately I have also upgraded my Notepad++ to 5.8.5. After the update, I looked at what are the latest plugins I could add on. I have found the Python Script plugin. To my delight, Python was also installed together with this plugin in my Notepad++ folder. So I got Python for free.

Next I have to figure out how to use this plugin. Actually, this plugin is not for general Python application development, it is more for Notepad++ automation using Python scripting. First and foremost, the Python Console is very important. To open the Python Console, click [Plugins], [Python Script] and [Show Console] as illustrated.


You can see from the above screen shot that it was Python 2.6.5. There are quite a few methods to run a Python script from the [Run] menu but what I am going to present here is a different method, running the script within the Python Console.

The Python Script plugin for Notepad++ comes with a few objects defined. One of them is the notepad object. The method getCurrentFilename() returns the full path name of the file being edited. Hence, we can use the command execfile() with notepad.getCurrentFilename() to accomplish what we want. In summary, enter the following command.
execfile(notepad.getCurrentFilename())

You only need to key in the command once. After this, you use the [Up Arrow] key to retrieve the previous command for execution.

The following is three solutions which I have come up for Problem 1.
# Add all the natural numbers below one thousand that are multiples of 3 or 5.

# imperative paradigm
def methodA():
    sum = 0
    for num in range(1000) :
       if num % 3 == 0 or num % 5 == 0:
          sum += num
    print sum

# pythonistic 
def methodB():
    print sum([x for x in range(1000) if x % 3 == 0 or x % 5 == 0])

# functional paradigm
def methodC():
    print sum(filter(lambda x: x % 3 == 0 or x % 5 == 0, range(1000)))
 
print "This is Project Euler Problem 1" 
methodA()
methodB()
methodC()

No comments:

Post a Comment