Python Practice With Project Euler
I recently learned Python through the website Codecademy. This is a great way to learn a new language with many exercises to do and projects at the end of each lesson, but I needed more. So I looked back to Project Euler. I have tried some of the challenges featured on Project Euler using C and C++ for some challenges this works very well others however I run into issues with precision/overflow to counteract this I could research how variable precision works, then implement it in C/C++ and then finally get to the original problem. This would be a great opportunity to learn variable precision or I could get familiar with a new language in this case I chose to become more familiar with Python.
One of the problems I did was challenge number 4: Find the largest palindrome made from the product of two 3-digit numbers. Here is my solution.
def is_num_palindrome(num): string = str(num) if string == string[::-1]: return True else: return False def find_palindrome_product(): list = [] for i in range(100,1000): for j in range(i,1000): num = i * j if is_num_palindrome(num) == True: list.append(i * j) return max(list)
I then have to just call find_palindrome_product
and it will give me a list of all the palindrome numbers that can be made from multiplying 3 digits together. This one can be done in C/C++ but python makes the solution compact and elegant such as being able to convert the number to a string and then check if it is a palindrome in one line.
I also did challenge number 5 which is: What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?
def smallest_multiple(): i = 21 while True: for j in reversed(xrange(1,20)): if i % j != 0: break else: return i i += 1
This solution took me a few tries, I had the solution from the beginning but it took a while to run so I tried optimizing it a bit. My optimization was start the loop that checks if it is evenly divisible from 20 and work down to 1 because odds are it will fail at the upper range rather than the lower range. This helped the speed out a bit. I am going to continue to do challenges on Project Euler I hope to become much more familiar with Python by the end of it.