Showing posts with label thinkpython. Show all posts
Showing posts with label thinkpython. Show all posts

Tuesday, March 27, 2012

exercise 10.2 - chop


"""===========================
exercise 10.2
==========================="""

def chop (a_list):
    del a_list[0] #remove first element
    del a_list[-1] #remove last element
    
test = [1,2,3,4,5,]
chop(test)
print test


test2 = [6,7,8,9,10]
def middle(a_list):
    new_list = a_list[1:-1]
    return new_list

practice = middle(test2)
print practice

exercise 10.1


"""===========================
exercise 10.1
==========================="""

def cumul_sum(original):
    new = []
    running_total = 0
    
    for number in original:
        running_total = running_total + number
        new.append(running_total)
    
    return new

old_list = [1,2,3]
print old_list
new_list = cumul_sum(old_list)
print new_list

exercise 9.7 - puzzler_1


"""================
exercise 9.7
==============="""

def puzzler_1 (word):

    index = 0
    consecutive_dbl_ltr = 0
    
    while index < len(word)-1:
        current_char = word[index]
        next_char = word[index+1]
        if current_char == next_char:
            consecutive_dbl_ltr += 1
            index = index + 2
        else:
            consecutive_dbl_ltr = 0
            index += 1
        if consecutive_dbl_ltr == 3:
            return True
    #end while loop
    return False
# end puzzler_1 (word)

#print puzzler_1("ddeeff")
#print puzzler_1("pocahontas")
#print puzzler_1("abcddeeffghij")

fin = open('words.txt')

for line in fin:
    word = line.strip()
    if puzzler_1(word):
        print word

exercise 9.6 - is_abecedarian


"""=============================
exercise 9.6
============================="""

def is_abecedarian(word):
    prev_char_ord = 0
    
    for char in word.lower():
        if prev_char_ord <= ord(char):
            prev_char_ord = ord(char)
        else:
            return False
    return True

#print is_abecedarian("abcDEfg")
#print is_abecedarian("xylophone")
#print is_abecedarian("eeeeeee")

fin = open('words.txt')

for line in fin:
    word = line.strip()
    if is_abecedarian(word):
        print word
        abcd = abcd + 1

print "number of abecedarian words = ",abcd

exercise 9.5 - uses_all


"""=============================
exercise 9.5
============================="""

def uses_all (word, use_all_chars):
    for char in use_all_chars:
        if char.lower() not in word.lower():
            if char != " ": #ignore space character
                return False
    return True
    
#print uses_all("Ho ho ho","acefhlo")
#print uses_all("Flo ace hoe","acefhlo")

fin = open('words.txt')

use_all_vowels = "aeiou"
use_all_vowels_and_y = "aeiouy"

for line in fin:
    word = line.strip()
    if uses_all(word,use_all_vowels):
        print word
        vowels = vowels + 1
    if uses_all(word,use_all_vowels_and_y):
        print word
        vowels_and_y = vowels_and_y + 1
    total_words = total_words + 1

print "number of words with aeiou = ",vowels
print "number of words with aeiouy = ",vowels_and_y

exercise 9.4 - uses_only


"""=============================
exercise 9.4
============================="""

def uses_only (word, only_chars):
    for char in word:
        if char.lower() not in only_chars.lower():
            if char != " ": #ignore space character
                return False
    return True
    
print uses_only("Ho ho ho","acefhlo")
print uses_only("Flo ace hoe","acefhlo")

exercise 9.3 - avoids


"""=====================
exercise 9.3
====================="""

def avoids(word, forbidden_chars):
    letter = ""
    forbidden_char = ""
    
    for letter in word:
        if letter.lower() in forbidden_chars.lower():
            return False
    
    return True
# end def avoids ()

avoid_chars = raw_input()
total_words = 0

fin = open('words.txt')

for line in fin:
    word = line.strip()
    if avoids(word,avoid_chars):
        print word
        words_that_avoid = words_that_avoid + 1
    total_words = total_words + 1

total_unavoided = total_words - words_that_avoid

print total_unavoided

Monday, March 26, 2012

exercise 9.2 - has_no_e


"""=====================
exercise 9.2
====================="""

def has_no_e(word):
    char = ""
    for char in word:
        if (char == "E") or (char == "e"):
            return False
    return True

fin = open('words.txt')

total_words = 0
words_without_e = 0
percent_without_e = 0.0

for line in fin:
    word = line.strip()
    if has_no_e(word):
        print word
        words_without_e = words_without_e + 1
    total_words = total_words + 1

percent_without_e = ( words_without_e / total_words ) * 100

exercise 9.1


"""=====================
exercise 9.1
====================="""

fin = open('words.txt')

for line in fin:
    word = line.strip()
    if len(word) > 20:
        print word

exercise 8.12 - rotate_word


"""=======================
exercise 8.12
======================"""

def rotate_word (word, num_shift):
    new_letter = ""
    new_word = ""
    word_lower = word.lower()
    
    for letter in word_lower:
        #rotate letter
        new_ltr_position = ord(letter)+num_shift
        
        # rotate z-->a or z<--a
        if new_ltr_position < ord('a'): #rotate z<--a
            new_ltr_position = new_ltr_position + 26
        elif new_ltr_position > ord('z'): #rotate z-->a
            new_ltr_position = new_ltr_position - 26
        
        #build new word
        new_letter = chr(new_ltr_position)
        new_word = new_word + new_letter

    return new_word
    
print rotate_word("melon",-10)
print rotate_word("cheer",7)

exercise 8.9 - is_palindrome


"""======================
exercise 8.9
======================"""
def is_palindrome_v2(word):
    if word == word[::-1]: 
        return True 
    else: 
        return False

print is_palindrome_v2('duh')
print is_palindrome_v2('boob')

exercise 8.8 - is_reverse


"""======================
exercise 8.8
======================"""
def is_reverse(word1, word2):
    if len(word1) != len(word2):
        return False
        
    i = 0
    j = len(word2)-1
    
    while j >= 0:
        print i, j,
        print word1[i], word2[j]
        if word1[i] != word2[j]:
            return False
        i = i+1
        j = j-1
        
    return True
    
print is_reverse('stop','pots')

exercise 8.6 - find


"""=========================
exercise 8.6
========================="""

def find(word, letter, start):
    index = start
    while index < len(word):
        if word[index] == letter:
            return index
        index = index + 1
    return -1

def count_v2 (word, letter, start):
    
    how_many = 0
    index = find(word, letter, start)
    
    if index == -1:
        how_many = 0
    else:
        while index > -1:
            how_many = how_many + 1
            index = index+1
            index = find(word, letter, index)
    print how_many
    
count_v2 ('banana', 'x', 0)    
count_v2 ('banana', 'a', 4)
count_v2 ('banana', 'a', 2)
count_v2 ('banana', 'a', 0)

exercise 8.5 - count


"""=========================
exercise 8.5
========================="""

def count (word, letter):
    how_many = 0
    for char in word:
        if char == letter:
            how_many = how_many + 1
    print how_many, "count version 1"
    
count ('banana', 'a')

exercise 8.4 - find


"""=========================
exercise 8.4
========================="""

def find(word, letter, start):
    index = start
    while index < len(word):
        if word[index] == letter:
            return index
        index = index + 1
    return -1
    
print find('stirring','i',0)
print find('stirring','i',2)
print find('stirring','i',3)

exercise 8.2 - Quack


"""=========================
exercise 8.2
========================="""

prefixes = 'JKLMNOPQ'

for letter in prefixes:
    if (letter == 'O') or (letter == 'Q'):
        suffix = 'uack'
    else:
        suffix = 'ack'
    print letter + suffix

exercise 8.1 - reverse_string

"""=======================
exercise 8.1
======================="""

def reverse_string (word):
    limit = len(word) * -1
    index = -1
    while index >= limit:
        letter = word[index]
        print letter
        index = index - 1

reverse_string("word")

Sunday, March 18, 2012

exercise 7.4 - eval_loop


"""====================
exercise 7.4
===================="""

import math

def eval_loop():
    #initialize variables
    input = ""
    last_input = ""
    
    #get user input from interpreter
    #until user types 'done'
    while True:
        print "your input, please :)"
        print "to end, type 'done'"
        input = raw_input()
        if input == 'done':
            return result
            break
        else:
            result = eval(input)
            print result
# end eval_loop()

return_result = eval_loop()
print "returned result = ", return_result

exercise 7.3 - test_square_root


"""===========================
exercise 7.3
==========================="""
import math

def approx_equal(a, b, limit):
    if abs(a-b) < limit:
        return True
    else:
        return False


def square_root (a):
    x = a / 2.0
    epsilon = 0.001
    while True:
        #print x
        y = (x + a/x) / 2.0
        if approx_equal (y, x, epsilon):
            break
        x = y
    return x
    
def test_square_root(a):
    ex_sqrt = square_root(a)
    py_sqrt = math.sqrt(a)
    diff = abs(ex_sqrt-py_sqrt)
    print a, ex_sqrt, py_sqrt , diff
    
test_square_root(1.0)
test_square_root(2.0)
test_square_root(3.0)

exercise 7.2 - square_root



"""===========================
exercise 7.2
==========================="""

def approx_equal(a, b, limit):
    if abs(a-b) < limit:
        return True
    else:
        return False


def square_root (a):
    x = a / 2.0
    epsilon = 0.001
    while True:
        print x
        y = (x + a/x) / 2
        if approx_equal (y, x, epsilon):
            break
        x = y
    return x
    
print square_root(25)
print square_root(2)
print square_root(49)