Python

Project Euler, Problem 2

I've got problem #2 in the bag.

Problem #2 goes like this:
Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:

1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...

Find the sum of all the even-valued terms in the sequence which do not exceed four million.

And my code goes as follows:
Haskell:

  1. --fibinaci :: (Num a) => a -> a -> [a]
  2. fibinaci a b
  3. | sum' > 4000000 = []
  4. | otherwise = sum' : fibinaci b sum'
  5. where sum' = a + b
  6.  
  7. problem2 = sum $ filter (even) (fibinaci 0 1)

Python:
  1. #!/usr/bin/python
  2.  
  3. def fibinaci_list( in_list, input1, input2):
  4. flip = True
  5. while ( input1 + input2 < 4000000):
  6. if( flip == True):
  7. input1 = input1 + input2
  8. in_list.append(input1)
  9. flip = False
  10. else:
  11. input2 = input1 + input2
  12. in_list.append(input2)
  13. flip = True
  14.  
  15. def even(n):
  16. if n % 2 == 0:
  17. return True
  18. else:
  19. return False
  20.  
  21.  
  22. def main():
  23. first_list = []
  24. fibinaci_list(first_list, 0, 1)
  25. second_list = filter(even, first_list)
  26. print "%s" % (sum(second_list))
  27.  
  28. if __name__ == "__main__":
  29. main()

And finally, Perl:
  1. #!/usr/bin/perl
  2.  
  3. my $total = 0;
  4. my $count1 = 0;
  5. my $count2 = 1;
  6. my $flip = 1;
  7.  
  8. while( $count2 + $count1 < 4000000)
  9. {
  10. if ( $flip == 1)
  11. {
  12. $count1 += $count2;
  13. if ( $count1 % 2 == 0)
  14. {
  15. $total += $count1;
  16. }
  17. $flip = 0;
  18. }
  19. else
  20. {
  21. $count2 += $count1;
  22. if ( $count2 % 2 == 0)
  23. {
  24. $total += $count2;
  25. }
  26. $flip = 1;
  27. }
  28. }
  29.  
  30. print $total;

Originally, I tried to copy the Python algorithm to Perl, using an array instead of a list. That didn't work. The program would always fail due to out of memory errors. To solve this problem I changed the program to work without using arrays and just took the whole fibinaci function out and put it into main.

As always, constructive comments for the code are welcomed.

Project Euler: Problem 1

So I'll admit it, I'm more than acceptably late to this party. OJ started working on these problems years ago, while I was still coding away on other stuff at school. Now that I'm not in school and needing a challenge I'm doing the best I can to tackle the problems at Project Euler. Since I'm also trying to pick up Haskell, this makes for a good way to learn the language. This isn't my first time using a Functional Programming language. But the last time I tried, it was forced upon me at school with inadequate assistance and the whole experience left a bad taste in my mouth. I'm glad that getting over the bad experience and learning something new at the same time.

I've started keeping a github repo with my solutions for the various problems. If anyone is interested in commenting on my code please do so. I welcome all constructive criticism.

To start this thing off; problem one reads,
“If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. Find the sum of all the multiples of 3 or 5 below 1000.”

Being this one was simple. I coded it up in Haskell, Python, and Perl.
Haskell:

  1. problem1 = sum $ filter (\x -> mod x 3 == 0 || mod x 5 == 0) [1..1000]
  2. problem1' = sum $ filter (\x -> mod x 3 == 0 || mod x 5 == 0) [1..999]

Python:
  1. #!/usr/bin/python
  2.  
  3. def threeorfive(n):
  4. if ( n % 3 == 0 or n % 5 == 0):
  5. return True
  6. else:
  7. return False
  8.  
  9. def main():
  10. first_list = range(1,1000)
  11. second_list = filter(threeorfive, first_list)
  12. print "%s" % (sum(second_list))
  13.  
  14. if __name__ == "__main__":
  15. main()

Perl:
  1. #!/usr/bin/perl
  2.  
  3. my $count = 0;
  4. my $total = 0;
  5.  
  6. while ( $count < 1000)
  7. {
  8. if ( $count % 3 == 0 or $count % 5 == 0)
  9. {
  10. $total += $count;
  11. }
  12.  
  13. $count++;
  14. }
  15.  
  16. print $total;

One thing that is nice about doing this in different languages, is that you get to become aware of the differences between some of those languages. For instance in Python the range function works a little differently than I expected. I was expecting an inclusive range function, one in which the 10 is included in the list. But that is now how Python's range works. It gives me 10 numbers, starting with 1, the end result is a list ending in 9. It's not a big deal and easily fixable, but just not something I was expecting. That is why the Haskell code has to functions in it. Just to verify that the Python code was correct.

I'll be posting more answers as I complete them. So expect to see some random posts with Euler solutions in them.

Websites by Email

I'd just like to share with you these forty-seven lines of python code that amaze me. Not because they do anything special, but because they represent something that is pretty important to programming languages, modules, or libraries (depending on the language). Let's take a quick gander at the code:

  1. #!/usr/bin/python
  2. """
  3. #
  4. # This is a simple script to grab the contents of a a website,
  5. # encoded into a MIME message, and email it
  6. """
  7. import sys
  8. import smtplib
  9. import pycurl
  10. from cStringIO import StringIO
  11. from email.mime.text import MIMEText
  12. from email.mime.multipart import MIMEMultipart
  13.  
  14. data_buf = StringIO()
  15. curl = pycurl.Curl()
  16.  
  17. # Setup pycurl to grab the data
  18. curl.setopt(pycurl.URL, sys.argv[1])
  19. curl.setopt(pycurl.WRITEFUNCTION, data_buf.write )
  20. curl.perform()
  21. curl.close()
  22.  
  23. # Begin creating email
  24. #create html & text parts of the email
  25. part1 = MIMEText(data_buf.getvalue(), 'html')
  26. part2 = MIMEText(data_buf.getvalue(), 'text')
  27.  
  28. # next 5 lines put it all together
  29. msg = MIMEMultipart('alternative')
  30. msg['Subject'] = 'Website by Email'
  31.  
  32. msg.attach(part1)
  33. msg.attach(part2)
  34.  
  35. # email away
  36. # this code was copied from:
  37. # <a href="http://www.mkyong.com/python/how-do-send-email-in-python-via-smtplib/<br />
  38. #" title="http://www.mkyong.com/python/how-do-send-email-in-python-via-smtplib/<br />
  39. #">http://www.mkyong.com/python/how-do-send-email-in-python-via-smtplib/<br />
  40. #</a> Geshi keeps adding extra lines here, I'm not sure why
  41. to = 'add_your_own'
  42. gmail_user = 'add_your_own'
  43. gmail_pwd = 'add_your_own'
  44. smtpserver = smtplib.SMTP("smtp.gmail.com", 587)
  45. smtpserver.ehlo()
  46. smtpserver.starttls()
  47. smtpserver.login(gmail_user, gmail_pwd)
  48. smtpserver.sendmail(gmail_user, to, msg.as_string())
  49. print 'done!'
  50. smtpserver.quit()

This little script started out as a work assignment (which I have modified to make it more general). The task was to grab the contents of a particular website and email them. Not terribly complicated, but also not one I was thinking would be accomplished with twenty-eight lines of actual code.

Let's take a second to review which modules are being used above:

The code used by PycURL to grab the website, and deposit the data into the string.

StringIO module, to hold the contents of the website. (I wasn't able to get a regular string to work here. If you know how, please tell me.)

The MIME module for reformatting the website contents.

The SMTPlib module, for having all the code in it to properly communicate with a SMTP server, including TLS for encryption, to send said email through the web.

It wasn't until doing this project that I fully realized the importance of modules. It was these four modules that saved me uncountable hours of coding, testing, and debugging. Even if I had written out the functionality I needed from scratch, what I would have written would not have anywhere near the functionality that these other modules provided. In correlation to this, I wonder if there is some kind of connection between how popular a lanugage is and how easily extendable it is. I have no way to prove this of course, but both Perl & Python could be good examples (and also happen to be the languages I'm most familiar with). Both languages are popular, as shown by the normalized graph by langpop.com, and both are also extremely easy to add extra functionality to. The PycURL, CLyther, and PyCUDA modules are great cases in point. PycURL allows Python to tap into the CURL library. CLyther allows Python to use OpenCL, and PyCUDA allows Python to access the CUDA libraries. It makes my head hurt just to think about the amount of code that it would take to perform these same functions, if written from scratch.

After having this moment of realization, I find I am extremely grateful to all the programmers out there who put in their time to help create modules like these and to help them perform as well as they do. I tip my hat at you all.

Hiding Keyboard Input From the Screen

For my current job I'm in charge of writing a script that requires a person to input their password and me being the semi-security conscious individual that I am knew that regular input for a script like this would be bad, as that would allow for over the shoulder (literally) view of someone's password. This is just unacceptable.

To solve this problem I hit the internets for a way to hide user input in Perl script. And in my travels I came across this old PERL FAQ site. I decided to try out the code and update it, throw it into a little dummy script. This is what I got (minus the dummy script):

  1. sub get_password
  2. {
  3. print "enter your password: ";
  4. system("stty -echo");
  5. chop(my $password=<>);
  6. print "\n";
  7. system("stty echo");
  8.  
  9. return $password;
  10. }

Saved it, ran it, and Holy Missing Characters Batman, it worked. So just as a mental exercise, I wanted to see if I could get it to emulate the password request when you run sudo, and I wrote this up in Python (because I need the practice):

  1. #!/usr/bin/python
  2.  
  3. import os
  4. import getpass
  5.  
  6. def get_password():
  7. #print "Please enter your password:"
  8. os.system("stty -echo")
  9. password = raw_input( getpass.getuser() + "'s password")
  10. os.system("stty echo")
  11. print "\n"
  12.  
  13. return password
  14.  
  15. def main():
  16. local_password = get_password()
  17. print local_password
  18.  
  19. main()

And again... it worked. Of course I finally realized that the reason why it worked is because of the line "stty -echo". Taking that I typed it into a standard terminal and after hitting enter the results were the same. My terminal functioned normally, but without showing me the characters I was typing. After returning my terminal back to normal I decided to read a little more about stty. After digging through the man page for a little while I came across this argument which is an alias for echo:

[-]crterase
echo erase characters as backspace-space-backspace

Thus the reason why I couldn't see anything change is because my terminal is treating all characters I type on the screen as a three part sequence of non alphanumeric characters. Although I find this a little odd; I have to just go with the words of Bugs Bunny on this one, “I don't ask questions. I just have fun.”

Syndicate content