Thursday, March 31, 2011

Mar 31

Starting todays with lists are mutable:
list are mutable program and example
This is a very easy concept to understand because really I this sorta when I was working with List Operators from my previous post. Basically how the list are mutable when you had to add 2 and 4 from my example in the above program, you basically did the same thing I did for list operators just all in this is that you inputed the numbers between multiple numbers instead of just putting them at the end or at the beginning.
List deletion:
list deletion program
Well really this method is pretty easy to understand due to all you have to do is put in a input to delete something within the list. Which from the program, del is asking you to do is delete the variable that is one in the list. Which happens to be two.
Objects and Values:
Objects and values program
When the objects and values you are listing aren't in a list then like from the program above you'd true for both a == b and a is b because they are equal. On the other hand you get false for a is b and you get true a == b because a == b is that a and b equal but for a is b, they aren't the same. They are two distinct lists of their own.
Aliasing:
aliasing program 
This program  basically says that variable a equals [1, 2, 3] and then variable b equals variable a so there for they are the same. When you input b[0] = 5, its changing what variable a = into [5, 2, 3]. This is because like I said, variable a and b are the same.
Cloning:
Cloning program
Frankly people believe cloning is pretty hard even though I believe this is pretty easy. Really the clone of this program is both b and d. This is due to the fact that they follow everything that a and c tell them to do because they equal what a and c [:] equals. So you can put as much as you want for b or d to change a and c, but they will always come out with their original values but will only change when assigned to a new value. 

Tuesday, March 29, 2011

Contiue onwards onto March 29th

This is me continuing on chapter 9 with list length:
List length program with example.

When it comes to list membership its very easy to understand. Like:
list membership 
From the program that ask that if pestilence was in horsemen, which it is outlined to be inside horsemen. Then it asks if debauchery was in horsemen which would obviously come out to false. To get this program to come out to be true you would have to say : 'debauchery' not in horsemen. This then comes out to being true.
list membership update with examples.
Onto to list operators:
list operator program
In list operators, its fairly easy to understand that withing the [] you can basically add anything to it. Basically all you have to do is just assign a variable to the numbers/ letters in the [], just with the letter you need [' '] with the word/ letters being insides the ' ' between them. But as you seen from my program I experiment with making the variables by trying to get them to equal the other variables outcomes. By for example:
g = f + c
then getting i to = g + a thus getting the following outcome:
['eye', 'i', 1, 2, 3, 4, 5, 6, 1, 2, 3]
Me assigning i to equal the outcomes of the other variables allowed me to get a even bigger outcome then just assigning i to equal just 2 of the other variables. I basically just wanted to make the outcome of this to be more complex.
List slices aren't to difficult ether, their just mixing slicing and list into one program:
list slice with original program and example.
Range is easy to understand:
range
I only had difficulties on range when it was coming to understand the negative step size:
examples
I don't get this because there is 3 numbers and I no that the start much be higher then the stop but I don't know what the middle number is suppose to mean.

Friday, March 25, 2011

Mar. 25

I really didn't get to finish the game I was trying to create. When working on it, I got stuck on the part when I had to change distance to hit and then put in the code and make it pass the doctest. Every time I tried i always got 2 out of 4 fail. I really didn't know that making a game would have been this difficult.

def hit(bx, by, r, px, py, h):
"""
>>> hit(760, 100, 10, 780, 100, 100)
False
>>> hit(770, 100, 10, 780, 100, 100)
True
>>> hit(770, 200, 10, 780, 100, 100)
True
>>> hit(770, 210, 10, 780, 100, 100)
False
"""
The above was what I had to make pass the doctest. From my program that I'll be adding as the last part of todays blog message, I had put return (h <= by) and (bx <= r) and had to fit somewhere into the program that it would return true. Also with (h <=by) I had to make sure it told that the ball was between the bottom and the top of the paddle, and then for (bx <= r) I had to make sure that the horizontal location of the ball is less than or equal to the radius away from the front of the paddle.
http://dl.dropbox.com/u/24004516/pong2.py
The above link is my program.
So as Mr. Elkner said, come Monday hes gonna help me with this program. Also my homework for the weekend is to get a notebook for Monday.

Wednesday, March 23, 2011

Mar. 23

http://dl.dropbox.com/u/24004516/catch.py
The above link turns the circle thats acting as a mitt into a square, I'm thinking bout changing the dimensions more on the square cause it seems a bit small.

Tuesday, March 22, 2011

Mar. 22

http://dl.dropbox.com/u/24004516/scores.py
The above link is my continue onto the pitch game.
http://dl.dropbox.com/u/24004516/catch.py
The above link shows that the computer wins no matter what, even if you catch the ball. Whats weird is it tells me too add:
Text("Computer Wins!", (340, 290), size=32)
sleep(2)
after:
if ball_ x > 810:
But every time I moved the text up after if ball_x, it always came up as an error. The error was:
IndentationError: expected an indented block
http://dl.dropbox.com/u/24004516/catch.py
The above is the fixed version of catch. I was finally able to figure out that the IndentationError was because I didn't indent both Text... and sleep(2).
http://dl.dropbox.com/u/24004516/catch.py
The above program is the finished catch.py program. After finishing the program the first time, it ended up not working. After finding a few errors I was able to make the program to work thus showing ether player as the winner or computer as the winner after getting 5 points.

Friday, March 18, 2011

Mar 18

from gasp import *

number = random_between(1, 1000)
guesses = 1
guess = input("Guess the number between 1 and 1000: ")

while guess != number:
if guess > number:
print "Too high!"
else:
print "Too low!"
guess = input("Guess the number between 1 and 1000: ")
guess += 1

print "\n\nCongratulations, you get it in %d guesses!\n\n" % guesses
When I inputed the above program i had to guess a few times in order to find the number that was randomly picked, which i got 719 as my number between 1 - 1000. 
from gasp import *

number = random_between(1, 1000)
guesses = 0

while True:
guess = input("Guess the number between 1 and 1000: ")
guesses += 1
if guess > number:
print "Too high!"
elif guess < number:
print "Too low!"
else:
print "\n\nCongratulations, you got it in %d guesses!\n\n" % guesses
break
This is an update of the first program that will give the accurate results of how many guesses it took you to guess the right number. This I say is a very cool program cause it functions as a person as to picking a random number and asking you to find the right number and pops out the amount of times you had too guess in order to get the right number. 
from gasp import *

def distance(x1, y1, x2, y2):
return ((x2 - x1)**2 + (y2 - y1)**2)**0.5
begin_graphics(800, 600, title="Catch", background=color.RED)
set_speed(120)

ball1_x = 10
ball1_y = 300
ball1 = Circle((ball1_x, ball1_y), 10, filled=True)
ball1_dx = 4

ball2_x = 790
ball2_y = 300
ball2 = Circle((ball2_x, ball2_y), 10)
ball2_dx = -4

while ball1_x < 810:
ball1_x += ball1_dx
ball2_x += ball2_dx
move_to(ball1, (ball1_x, ball1_y))
move_to(ball2, (ball2_x, ball2_y))
if distance(ball1_x, ball1_y, ball2_x, ball2_y) <= 20:
remove_from_screen(ball1)
remove_from_screen(ball2)
break
update_when('next_tick')
sleep(1)
end_graphics()
The game being created from this program I'm starting to see is starting to get more and more complicated. This simple game is pretty easy to understand. 
from gasp import *

def distance(x1, y1, x2, y2):
return((x2 - x1)**2 + (y2 - y1)**2)**0.5
begin_graphics(800, 600, title="Catch", background=color.RED)
set_speed(120)

ball_x = 10
ball_y = 300
ball = Circle((ball_x, ball_y), 10, filled=True)
dx = 4
dy = random_between(-4, 4)

mitt_x = 780
mitt_y = 300
mitt = Circle((mitt_x, mitt_y), 20)

while True:
# move the ball
if ball_y >= 590 or ball_y <= 10:
dy *= -1
ball_x += dx
if ball_x > 810:     # the ball has gone off the screen
break
ball_y += dy
move_to(ball, (ball_x, ball_y))
# check on the mitt
if key_pressed('k') and mitt_y <= 580:
mitt_y += 5
elif key_pressed('j') and mitt_y >= 20:
mitt_y -= 5
if key_pressed('escape'):
break 
move_to(mitt, (mitt_x, mitt_y))
if distance(ball_x, ball_y, mitt_x, mitt_y) <= 30:   # ball is caught
remove_from_screen(ball)
break 
update_when('next_tick')
end_graphics()
When running the above program, I got the following error:
Exception in thread QueueFeederThread (most likely raised during interpreter shutdown):
Traceback (most recent call last):
  File "/usr/lib/python2.6/threading.py", line 532, in __bootstrap_inner
  File "/usr/lib/python2.6/threading.py", line 484, in run
  File "/usr/lib/python2.6/multiprocessing/queues.py", line 242, in _feed <class 'cPickle.PicklingError'>: Can't pickle gasp.api.Circle: import of module gasp.api failed
I believe this is a error off of gasp but I can't tell. 

Thursday, March 17, 2011

Mar. 17

fruit = 'rampage'
"""
>>> type(fruit)
<type 'str'>
>>> len(fruit)
7
>>> fruit[:3]
'ram'
"""

if __name__ == '__main__':
import doctest
doctest.testmod()
This program I had to do to make it pass the doctest.
from gasp import *

begin_graphics(800, 600, title="Catch", background=color.YELLOW)
set_speed(120)

ball_x = 10
ball_y = 300
ball = Circle((ball_x, ball_y), 10, filled=True)
dx = 4
dy = 1

while ball_x < 810:
ball_x += dx
ball_y += dy
move_to(ball, (ball_x, ball_y))
update_when('next_tick')

end_graphics()
The above program makes a ball appear then fly across the screen until it hits the side of the window and disappears. The background also to this graphic is then yellow. I can manipulate the color of the background by just changing the color, I can also change the speed of the ball flying across the screen.
>>> from gasp import *
>>> i = 0
>>> while i < 10:
...     print random_between(-5, 5)
...     i += 1
... 
5
2
-4
5
-5
-5
4
-5
4
-1
The above program is called a more or less random integer. This program will random choose 10 numbers between -5 and 5, so really your results to this program varies. 
from gasp import *

begin_graphics(800, 600, title="Catch", background=color.RED)
set_speed(120)

ball_x = 10
ball_y = 300
ball = Circle((ball_x, ball_y), 10, filled=True)
dx = 4
dy = random_between(-4, 4)

while ball_x < 810:
ball_x += dx
ball_y += dy
move_to(ball, (ball_x, ball_y))
update_when('next_tick')

end_graphics()
The above program has been modified to appear with a background of red and then I changed the dy = 1 to dy = random_between(-4, 4) which will cause a random number to be chosen to be used for the direction of the ball

Wednesday, March 16, 2011

Mar. 16

This program is easy to understand:

>>> i = 1
>>> print "i\ti**2\ti**3\ti**5\ti**10\ti**20"
i i**2 i**3 i**5 i**10 i**20
>>> while i <= 10:
...     print i, '\t', i**2, '\t', i**3, '\t', i**5, '\t', i**10, '\t', i**20
...     i += 1
...
1 1 1 1 1 1
2 4 8 32 1024 1048576
3 9 27 243 59049 3486784401
4 16 64 1024 1048576 1099511627776
5 25 125 3125 9765625 95367431640625
6 36 216 7776 60466176 3656158440062976
7 49 343 16807 282475249 79792266297612001
8 64 512 32768 1073741824 1152921504606846976
9 81 729 59049 3486784401 12157665459056928801
10 100 1000 100000 10000000000 100000000000000000000
Well from the program it tells the out put to be put into a table('\t'). From this then it puts the equation into the correct line. 
>>> i = 1
>>> print "%-4s%-5s%-^s%-*s%-13s%-15s" % \
...     ('i', 'i**2', 'i**3', 'i**5', 'i**10', 'i**20')
>>> while i <= 10:
...     print "%-4d%-5d%-6d%-8d%-13d%-15d%" % (i, i**2, i**3, i**5, i**10, i**20)
...     i += 1
... 
i    i**2   i**3   i**5   i**10    i**20
1   1    1     1       1            1              
2   4    8     32      1024         1048576        
3   9    27    243     59049        3486784401     
4   16   64    1024    1048576      1099511627776  
5   25   125   3125    9765625      95367431640625 
6   36   216   7776    60466176     3656158440062976
7   49   343   16807   282475249    79792266297612001
8   64   512   32768   1073741824   1152921504606846976
9   81   729   59049   3486784401   12157665459056928801
10  100  1000  100000  10000000000  100000000000000000000
The change on this program is that it outputted with i, i**2, i**3, i**5, i**10, and i**20
>>> 'Python'[1]
'y'
>>> "Strings are sequences of characters."[5]
'g'
>>> len("wonderful")
9
>>> 'Mystery'[:4]
'Myst'
>>> 'p' in 'Pinapple'
True
>>> 'apple' in 'Pinapple'
True
>>> 'pear' in 'Pinapple'
False
>>> 'apple' > 'pinapple'
False
>>> 'pinapple' < 'Peach'
False
(This was me recapping on stuff i did during chapter.)

Friday, March 11, 2011

Mar. 11

>>> import string
>>> string.find("bob", "b", 1, 2)
-1
With this input off of the string module, I was confused as to how did the program get an output of -1. I'm just confused with that part of the program
>>> '2**10 = 1024 and 4 * 5 = 20.000000'
'2**10 = 1024 and 4 * 5 = 20.000000'
>>> "His name is %s." % "Arthur"
'His name is Arthur.'
>>> name = "Alice"
>>> age = 10
>>> "I am %s and I am %d years old." % (name, age)
'I am Alice and I am 10 years old.'
>>> n1 = 4
>>> n2 = 5
>>> "2**10 = %d and %d * %d =  %f" % (2**10, n1, n2, n1 * n2)
'2**10 = 1024 and 4 * 5 =  20.000000'
With the % input, you can have it stand for different things such as from the program the first %s = name and then the second %d = age..

Thursday, March 10, 2011

Mar. 10

When working with the string module, I realized that the expression dir means directory.
>>>import string
>>>dir(string)

['Formatter', 'Template', '_TemplateMetaclass', '__builtins__', '__doc__', '__file__', '__name__', '__package__', '_float', '_idmap', '_idmapL', '_int', '_long', '_multimap', '_re', 'ascii_letters', 'ascii_lowercase', 'ascii_uppercase', 'atof', 'atof_error', 'atoi', 'atoi_error', 'atol', 'atol_error', 'capitalize', 'capwords', 'center', 'count', 'digits', 'expandtabs', 'find', 'hexdigits', 'index', 'index_error', 'join', 'joinfields', 'letters', 'ljust', 'lower', 'lowercase', 'lstrip', 'maketrans', 'octdigits', 'printable', 'punctuation', 'replace', 'rfind', 'rindex', 'rjust', 'rsplit', 'rstrip', 'split', 'splitfields', 'strip', 'swapcase', 'translate', 'upper', 'uppercase', 'whitespace', 'zfill']
The above is the full list of the items in the string module.
When i ask to see all the digits I get from the string module I get:
>>> print string.digits
0123456789
Not surprising you get all the digits. 
>>> string.find("banana", "na")
2
The out come of this program is 2 because in the word "banana", you will find 2 occurrence of "na". >>> >>>print string.lowercase
abcdefghijklmnopqrstuvwxyz
>>> print string.uppercase
ABCDEFGHIJKLMNOPQRSTUVWXYZ
>>> print string.digits
0123456789
When working with the string module, I've noticed that it has many possible outputs to the program. Basically this program has self explanatory, such as lowercase, uppercase, and digits. 
>>> print string.whitespace
When you put this into the terminal you get just a few open lines of blank space.

Wednesday, March 9, 2011

Mar. 9

Working with the in command, I've noticed that it basically tells what it does. For example:

>>> 'p' in 'apple'
True
>>>
>>> 'i' in 'apple'
False
>>> 'ap' in 'apple'
True
>>> 'pa' in 'apple'
False
This program will only come out to saying its True only if the letter your asking for is inside the word you plug in. Like for apple, you already know you'd find a-p-p-l-e in the word. So if you ask the program if q or like if w is in the word, it will come out False.
>>>'apple' in 'apple'
True
You get this because well you'd find apple when you look in the word apple. This is basically self explanatory. 
>>> def remove_vowels(s):
...     vowels = "aeiouAEIOU"
...     s_without_vowels = ""
...     for letter in s:
...             if letter not in vowels:
...                     s_without_vowels += letter
...     return s_without_vowels
... 
With this program, you must first assign a word to a variable.
a = 'apple'
Once you have the variable you just plug the variable into the program and get:
'ppl'
So the program basically just deletes all the vowels in the word and just spits out what ever is left. 
>>> fruit = "banana"
>>> count = 0
>>> for char in fruit:
...     if char == 'a':
...             count += 1
...     print count
... 
0
1
1
2
2
3
This program just outputs how many times you input 'a'. So as the program inputs 'banana' into its system, it starts with b which is 0, then the a which now is 1, then the n which stays as one saying thats there has been an a before. Then another a which now is 2. Then another n which will stay 2 as previously stated. Then the 3rd and final a which is now called 3, thus getting the above results. 

Tuesday, March 8, 2011

Mar. 8

To re-enforce what I've learned on string slices. An example to help me out is:
>>>s = "Andrew"
>>>print s[:]
Andrew
>>>print s[1:2]
n
>>>print s[1:5]
ndre
>>>print s[:-1]
Andre
>>>print s[-1:]
w
And so on......
This technique is really easy to understand. I just had to keep in mind the basic principle that instead of starting to count at one, you start at zero.
With immutable strings, the following program is easy to understand.

>>> greeting = "Hello, world!"
>>> newGreeting = 'J' + greeting[1:]
>>> print newGreeting
Jello, world!
When you want to change the out put of "Hello, world!" to "Jello, world!" all you'd do like the program shows is put new before your variable, then in order to change the letter of the text you'd have to put the exact point to change. Like it says to change from greeting change it would print everything after the first letter, which is H. The [1:] would print every other letter after the H, so then when  you add the 'J' you get the output of "Jello, world!" But if i first started out with trying to change the first word on in greeting by just asking for greeting[0] = 'J' then id get the error of : TypeError: 'str' object does not support item assignment.

Friday, March 4, 2011

Mar. 4

Starting on chapter 7 with compound data types. 
When I put into the terminal:
>>> fruit = "banana" 
>>> letter = fruit[1]
>>> print letter 
I would get a, I really expected to get like f or b but reading on I was able to find out that with computer programing, you start off by counting at 0. So instead, if i used fruit[0] then id get b instead of a. I then after realizing that it would print a, that instead of printing letters from fruit, it would print from banana, which I should have realized when I first put in fruit = "banana". 
Here area all the letters and the fruit[n] you can use in order to finish typing out banana:
fruit[0]
b
fruit[1]
a
fruit[2]
n
fruit[3]
a
fruit[4]
n
fruit[5]
a
The next step to chapter 7 was length, which the abbreviation for length on python is len. 
>>>fruit = "banana"
>>>len(fruit)
so for this program, length would be used as to tell how many letters long the word was. You would get an output of 6 for this program. 
example:
Instead of using fruit, I used word for this program. 
>>> word = "pneumonoultramicroscopicsilicovolcanoconiosis"
>>> len(word)
45
The word used was the longest word that can be found in a major dictionary. This word as the program exclaims has 45 letters/ length of the word is 45 characters. 
In order to get the program to say the letter from the end of the word you would put in(this is back with the banana program:
>>> length = len(fruit)
>>> last = fruit[length-1]
>>>last
'a'
Then if you change fruit[length-1] to fruit[length-2] you would get 'n' and so on and so forth. 
A transversal program like the following puts on its own line a letter of "banana":
 index = 0
>>> while index < len(fruit):
...     letter = fruit[index]
...     print letter
...     index += 1
... 
b
a
n
a
n
a
You can also get the same results using:
>>> for char in fruit:
...     print char
... 
b
a
n
a
n
a
The following program is used to assign the prefix with the suffix of a word and have them in alphabetic order:
 >>> prefixes = "JKLMNOPQ"
>>> suffix = "ack"
>>> 
>>> for letter in prefixes:
...     print letter + suffix
... 
Jack
Kack
Lack
Mack
Nack
Oack
Pack
Qack
>>> 
Even though Oach and Qack are missed spelled do to they having more letters in the word. Correction is Ouack and Quack
Working with a program that produces just the letters out of a word, I've used the [:] code:
>>> fruit = "banana"
>>> fruit[:3]
'ban'
>>> fruit[3:]
'ana'
When using the [:], this allows me to choose which letters I want displayed. For instance from the program above I used fruit[:3] to get the first 3 letters of "banana", and then used fruit[3:] for the last 3. Basically the side the number is on depends on what it will display but one side must be blank to show the numbers you want to display instead of setting a guide to another area to stop at(I don't know if I'm explaining this clearly, please comment if it makes sense to you, if not I'll update this when I get feedback.). 

Thursday, March 3, 2011

This is a rewritten sequence program:
>>> def sequence(n):
...     while n != 1:
...             print n, 
...             if n % 2 == 0:
...                     n = n / 2
...             else:
...                     n = n * 3 + 1
... 
>>> sequence(3)
3 10 5 16 8 4 2
The program above also so the program working. 
This is the num_digits program that I've failed to put on here. This program also has three examples of the program working and getting an output.
>>> def num_digits(n):
...     count = 0
...     while n:
...             count = count + 1
...             n = n / 10
...     return count
... 
>>> num_digits(710)
3
>>> num_digits(999999999999999)
15
>>> num_digits(111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111)
96
>>> 
This program is basically self explanatory, it basically just counts the number places in the number. 
This is the num_zero_and_five_digits. This program counts the number of zeros and number of fives in the number:
>>> def num_zero_and_five_digits(n):
...     count = 0
...     while n:
...             digit = n % 10
...             if digit == 0 or digit == 5:
...                     count = count + 1
...             n = n / 10
...     return count
... 
>>> num_zero_and_five_digits(1055030250)
7

Wednesday, March 2, 2011

Mar. 2

Sorry I messed up on writing Newton's algorithm, the program is:

>>> def sqrt(n):
...     approx = n/2.0
...     better = (approx + n/approx)/2.0
...     while better != approx:
...         approx = better
...         better = (approx + n/approx)/2.0
...     return approx
...
These are the questions for chapter 6


Tuesday, March 1, 2011

Mar. 1

This program is basically a program that shows ab = ba as a table.

def print_multples(n):
i = 1
while i <= 6:
print n * i, '\t',
i += 1
print
def print_mult_table(high):
    i = 1
    while i <= high:
        print_multiples(i)
        i += 1
So for example, if we plug in print_mult_table(7) we get the following table:
1   2   3   4   5   6   7
2   4   6   8   10   12  14
3   9   12  15  18  21
4   8   12   16  20  24  28
5   10   15   20   25   30   35
6   8   12  18   24   30   36   42
7   14   21   28   35  42  49
(sorry this time i didn't try to equal up the sides of the table)
This program makes it where the table will have a downwards slope as the number rises. This table also takes away the numbers 2-7 from the top row, then each row it adds another number. Here is the table so you understand what I mean:

1
2 4
3 6 9
4 8 12 16
5 10 15 20 25
6 12 18 24 30 36
7 14 21 28 35 42 49
I then started to work on Newton's method which the program was:
def sqrt(n): approx = n/2.0 better = (approx + n/approx)/2.0 while better != approx: approx = better better = (approx + n/approx)/2.0 return approx
I then plugged in sqrt(25) and got an out-put of 5.0:
>>> sqrt(25) 5.0