Goal setting – Django

I believe that goal setting is an important part of succeeding, and I also am a firm believer that writing down the goal is one way to increase the likelyhood of reaching it.

Today I decided to learn Django, the Python framework. I made a commitment to spend 1/2 to 1 hour each day, six days a week, for the next 6 months. At the completion of six months, I’ll relay the understanding and abilities I have with Django. The picture above is of the goal I wrote on a sheet of paper.

Update: October 12, 2011

Hello on this Wednesday afternoon. I trust everyone is doing well. The purpose of this next paragraph is to relay the information I learned about Django during the past six months.

The only thing I did was go through the first seven chapters of the tutorial on djangobook.com. I learned how to set up a data base and make a basic web application. I took the time to figure out each step in the tutorial and set up the necessary files on my laptop. Without remembering the specifics of the tutorial, I can tell you that the first seven chapters go over views, URL configs, templates, models, the Django admin site, and forms. Having done that much, I think I would be ready to start re-designing one of my websites using Django. Setting up Django and Python on my web server would be the greatest challenge. From there the tutorials would at least be a reference point. Sorry I don’t have anything more specific, all I know is that experience is the best teacher, and that the tutorial is a great place to start.

###

Advertisements

Project Euler – Problem # 28 – Solved with Python

Problem:

Starting with the number 1 and moving to the right in a clockwise direction a 5 by 5 spiral is formed as follows:

It can be verified that the sum of the numbers on the diagonals is 101.

What is the sum of the numbers on the diagonals in a 1001 by 1001 spiral formed in the same way?

One Possible Solution:

def add_diagonal(passed):
    """Calculate sum of individual diagonal"""
    summer = 1
    adder = 0
    tallyer = 0
    for i in range(0, 500):
        if i < 1:
            adder = passed
        else:
            adder = adder + 8
        summer = summer + adder
        tallyer = tallyer + summer
    return tallyer
        
def main():
    """Main program:
    Finds sum of each diagonal
    and adds 1 for the center"""
    lr = add_diagonal(2)
    print "lr = ", lr
    ll = add_diagonal(4)
    print "ll = ", ll
    ul = add_diagonal(6)
    print "ul = ", ul
    ur = add_diagonal(8)
    print "ur = ", ur
    tally = lr + ll + ul + ur + 1
    print "tally = ", tally

if __name__ == '__main__':
    main()

English to Pig Latin Translator

Problem:

Your objective is to write a Python program that takes a single English word as input and converts it to Pig Latin. The translation rules are as follows.

  1. If a word has no letters, don’t translate it.
  2. Assume all words are lowercase and there are no punctuation marks.
  3. Separate each word into two parts. The first part is called the prefix and extends from the beginning of the word up to, but not including, the first vowel. (The letter ’y’ will be considered a consonant.) The rest of the word is called the stem.
  4. The Pig Latin text is formed by reversing the order of the prefix and stem and adding the letters “ay” to the end. For example, “sandwich” is composed of the prefix “s” and the stem “andwich” and would translate to “andwichsay.”
  5. If the word contains no consonants, let the prefix be empty and the word be the stem. The word ending should be “yay” instead of merely “ay.” For example, “i” would be “iyay”.
  6. Make sure to handle the consonant cluster “qu” properly. For example, the word “question” should be “estion-quay” in Pig Latin and not “uestion-qay”

One Possible Solution:

def word_index(x):
    """ Returns index in word where stem starts """
    counter = 0
    for i in x:
        counter += 1
        if (i == "a" or i == "e" or i == "i" or i == "o" \
           or i == "u") and counter != 1:
            return counter - 1
        else:
            pass
        if counter == len(x):
            return 10000

def reverse_word(x, y):
    """ Reverse prefix and stem of the word x """
    yy = x[:y]
    zz = x[y:]
   
    if (y == 10000) and ((yy != "a") and (yy != "e") and (yy != "i") and \
                         (yy != "o") and (yy != "u")):
        print "Pig Latin: ", x + 'ay'
        return
    elif x[:2] == "qu":
        yyy = x[:2]
        zzz = x[2:]
        xyz = zzz + yyy + 'ay'
        print "Pig Latin: ", xyz
        return
    elif ((yy == "a") or (yy == "e") or (yy == "i") or \
          (yy == "o") or (yy == "u")):
        y2 = yy + 'yay'
        print "Pig Latin: ", y2
        return
    else:
        yz = zz + yy + 'ay'
        print "Pig Latin: ", yz

def main():
    """ Main program """
    x = raw_input("English: ")
    y = word_index(x)
    yy = reverse_word(x, y)

if __name__ == '__main__':
    main()

Original Assignment

Project Euler – Problem # 26 – Solved with Python

Problem:

A unit fraction contains 1 in the numerator. The decimal representation of the unit fractions with denominators 2 to 10 are given:

  • 1/2 = 0.5
  • 1/3 = 0.(3)
  • 1/4 = 0.25
  • 1/5 = 0.2
  • 1/6 = 0.1(6)
  • 1/7 = 0.(142857)
  • 1/8 = 0.125
  • 1/9 = 0.(1)
  • 1/10 = 0.1

Where 0.1(6) means 0.166666…, and has a 1-digit recurring cycle. It can be seen that 1/7 has a 6-digit recurring cycle.

Find the value of d < 1000 for which 1/d contains the longest recurring cycle in its decimal fraction part.

One Possible Solution:

from decimal import *

def find_fraction(i):
    """Finds the fraction of x to the .prec place"""
    getcontext().prec = 1500
    x = Decimal(1) / Decimal(i)
    #print "i = %s x = %s" % (i, x) 
    return x

def find_period(x1):
    """Find period for repeating"""
    L = (str(x1))
    length = len(L)
    l_one, l_two, l_three = 0, 0, 0
    #print "L = ", L
    if L[2:3] != '0':
        index = L[2:6]
        l_one = 1
    elif L[2:3] == '0' and L[3:4] != '0':
        index = L[3:7]
        l_two = 1
    elif L[2:3] == '0' and L[3:4] == '0':
        index = L[4:8]
        l_three = 1
    else:
        print "There may be an error in your program"
    max_period = 0
    for v in range(3, length):
        if l_one == 1:
            indexi = L[v:(v + 4)]
        elif l_two == 1:
            indexi = L[(v + 1):(v + 5)]
        elif l_three == 1:
            indexi = L[(v + 2):(v + 6)]
        else:
            print "There has been an error"
        if index == indexi:
            #print "index = ", index
            #print "indexi = ", indexi
            #print "They are equal"
            #print "L[i] = ", (v-2)
            max_period = v
            break
    return max_period

def main():
    """Main program"""
    place_holder = 0
    for i in range(1, 1001):
        x1 = find_fraction(i)
        y1 = find_period(x1)
        #print "max_period = ", y1
        if y1 > place_holder:
            place_holder = y1
            max_number = i
    print "max_number = ", max_number

if __name__ == '__main__':
    main()

Project Euler – Problem # 25 – Solved with Python

It doesn’t take long for the Fibonacci sequence to get really large. This program asks for a stopping number, then loops through those numbers until it gets one of length 1000 digits or more. At only 4782 the Fibonacci number problem is solved.

Problem:

The Fibonacci sequence is defined by the recurrence relation:

Fn = Fn1 + Fn2, where F1 = 1 and F2 = 1.

Hence the first 12 terms will be:

  • F1 = 1
  • F2 = 1
  • F3 = 2
  • F4 = 3
  • F5 = 5
  • F6 = 8
  • F7 = 13
  • F8 = 21
  • F9 = 34
  • F10 = 55
  • F11 = 89
  • F12 = 144

The 12th term, F12, is the first term to contain three digits.

What is the first term in the Fibonacci sequence to contain 1000 digits?

One Possible Solution:

def find_fibonacci(n):
    """Find fibonacci"""
    a, b = 0, 1
    for i in range(0, n):
        x = str(a)
        if len(x) == 1000:
            print a
            print "F(n) = ", i
            break
        a, b, = b, a + b

def main():
    """Main program"""
    n = input("\nHow many numbers of the sequence would you like? ")
    find_fibonacci(n)
    
if __name__ == '__main__':
    main()

Project Euler

Project Euler – Problem # 24 – Solved with Python

This problem was made easy with the permutations fucntion.

Problem:

A permutation is an ordered arrangement of objects. For example, 3124 is one possible permutation of the digits 1, 2, 3 and 4. If all of the permutations are listed numerically or alphabetically, we call it lexicographic order. The lexicographic permutations of 0, 1 and 2 are:

012 021 102 120 201 210

What is the millionth lexicographic permutation of the digits 0, 1, 2, 3, 4, 5, 6, 7, 8 and 9?

One Possible Solution:

import itertools
x = itertools.permutations('0123456789', 10)
counter = 0
for i in x:
    counter += 1
    if counter == 1000000:
        print i
    else:
        pass

Project Euler – Problem # 23 – Solved with Python

I first approached this problem with lists…. The test programs were running 15 + minutes , so I tried dictionaries, this gave too much data representation. So I settled with python sets. You can add to a set to build it, they are unique, (don’t have to worry about duplicates), and best of all they can be compared to one another. It worked really smoothly with sets. Note: program still takes about 55 seconds to run.

Problem:

A perfect number is a number for which the sum of its proper divisors is exactly equal to the number. For example, the sum of the proper divisors of 28 would be 1 + 2 + 4 + 7 + 14 = 28, which means that 28 is a perfect number.

A number n is called deficient if the sum of its proper divisors is less than n and it is called abundant if this sum exceeds n.

As 12 is the smallest abundant number, 1 + 2 + 3 + 4 + 6 = 16, the smallest number that can be written as the sum of two abundant numbers is 24. By mathematical analysis, it can be shown that all integers greater than 28123 can be written as the sum of two abundant numbers. However, this upper limit cannot be reduced any further by analysis even though it is known that the greatest number that cannot be expressed as the sum of two abundant numbers is less than this limit.

Find the sum of all the positive integers which cannot be written as the sum of two abundant numbers.

One Possible Solution:

import time

def factor(number):
    """Factor a number"""
    L = []
    for i in range(1, ((number / 2) + 1)):
        if number % i == 0:
            L.append(i)
    return L

def sum_factors(x):
    """Sum factors"""
    return sum(x)

def find_abundant_Set():
    """Find abundant Set"""
    abundant_Set = set()
    for m in range(0, 28123):
        x = factor(m)
        y = sum_factors(x)
        if m < y:
            abundant_Set.add(m)
        else:
            pass
    return set(sorted(abundant_Set))

def find_abundant_sums(xy):
    """Find abundant sums"""
    abundant_Set_a = set()
    for x in xy:
        for y in xy:
            zzz = x + y
            if zzz < 28123:
                abundant_Set_a.add(zzz)
            else:
                pass
    return set(sorted(abundant_Set_a))

def set_of_all_integers():
    """Set if all integers"""
    all_integers = set()
    for x in range(0, 28123):
        all_integers.add(x)
    return set(sorted(all_integers))
        
def find_missing_abundant_sums(yz, zz):
    """Find missing abundant sums"""
    all_positive_int = set()
    all_positive_int = zz - yz
    return set(all_positive_int)

def main():
    """Main program"""
    start_time = time.clock()
    xy = find_abundant_Set()
    yz = find_abundant_sums(xy)
    zz = set_of_all_integers()
    xz = find_missing_abundant_sums(yz, zz)
    tally = sum(xz)
    print "Tally = ", tally
    run_time = time.clock() - start_time
    print "Run time = ", run_time
            
if __name__ == '__main__':
    main()

Project Euler – Problem # 22 – Solved with Python

The hardest part about this problem was reading the file (names.txt) into the program for proper file manipulation.

Problem:

Using names.txt (right click and ‘Save Link/Target As…’), a 46K text file containing over five-thousand first names, begin by sorting it into alphabetical order. Then working out the alphabetical value for each name, multiply this value by its alphabetical position in the list to obtain a name score.

For example, when the list is sorted into alphabetical order, COLIN, which is worth 3 + 15 + 12 + 9 + 14 = 53, is the 938th name in the list. So, COLIN would obtain a score of 938 53 = 49714.

What is the total of all the name scores in the file?

One Possible Solution:

f = open('names.txt', 'rU')
names = []

names = sorted(f.read().replace('"', '').split(','), key=str)

letv = {'A':1,'B':2,'C':3,'D':4,'E':5,'F':6,'G':7,'H':8,'I':9,'J':10, \
        'K':11,'L':12,'M':13,'N':14,'O':15,'P':16,'Q':17,'R':18,'S':19, \
        'T':20,'U':21,'V':22,'W':23,'X':24,'Y':25,'Z':26}

def letter_counter(letter):
    """Letter counter"""
    lc = letv[letter]
    return lc
   
def main():
    """Main program"""
    x = len(names)
    z = 0
    for i in range(0,(x)):
        x2 = 0
        y = 0
        for letter in names[i]:
            x1 = letter_counter(letter)
            x2 = x2 + x1
        y = x2 * (i + 1)
        z = z + y
    print "z = ", z
            
if __name__ == '__main__':
    main()

Project Euler – Problem # 21 – Solved with Python

Problem:

Let d(n) be defined as the sum of proper divisors of n (numbers less than n which divide evenly into n).
If d(a) = b and d(b) = a, where a != b, then a and b are an amicable pair and each of a and b are called amicable numbers.

For example, the proper divisors of 220 are 1, 2, 4, 5, 10, 11, 20, 22, 44, 55 and 110; therefore d(220) = 284. The proper divisors of 284 are 1, 2, 4, 71 and 142; so d(284) = 220.

Evaluate the sum of all the amicable numbers under 10000.

One Possible Solution:

def factor(number):
    """Factor a numer"""
    L = []
    for i in range(1, ((number / 2) + 1)):
        if number%i == 0:
            L.append(i)
    return L

def get_total(x):
    """Total the elements in list L"""
    total = sum(x)
    return total

def main():
    """Main program"""
    tally = 0 
    for y in range(1, 10001):
        x = factor(y) # A list
        x1 = get_total(x)
        x3 = factor(x1) # A list
        x4 = get_total(x3)
        if (y == x4) and (y != x1):
            tally = tally + y
            print "tally = %s y = %s" % (tally, y)
    print "Final Tally = %s" % tally
            
if __name__ == '__main__':
    main()