[Tutor] Polyfit works like this

2009-12-02 Thread Eike Welk
On Tuesday 01 December 2009, questions anon wrote:
> I would now like to add a line of best fit. I think the command is
> polyfit()??
> But I can't seem to get it to work

These are the steps to make polyval work. I typed it into 
an 'ipython -pylab' session; I hope I included all relevant lines and 
I removed some of the output:

#this is the input data
In [13]:d_x = [0, 0.1, 0.3, 0.5, 0.7, 1, 1.2, 1.5, 1.8, 2]
In [14]:d_y = [0.1, 0.11, 0.15, 0.3, 0.5, 0.8, 1, 1.2, 1.1, 1.2]

#show input data
In [15]:plot(d_x,d_y, label='data')

#make 2nd degree polynom, and plot smoothly with 50 points
In [17]:pol2 = polyfit(d_x, d_y, 2)
In [18]:p_x = linspace(0, 2, 50)
In [19]:p2_y = polyval(pol2, p_x)
In [20]:plot(p_x,p2_y, label='pol 2nd')

#also create line and plot it too (would not need 50 points)
In [21]:pol1 = polyfit(d_x, d_y, 1)
In [22]:p1_y = polyval(pol1, p_x)
In [24]:plot(p_x,p1_y, label='line')

#create legend so you can recognize the curves
In [25]:legend()


Eike.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Fwd: Moving from Python 2 to Python 3: A 4 page "cheat sheet"

2009-12-02 Thread Kent Johnson
Forwarded from python-announce. A helpful summary of the differences
between Python 2 and 3 (though some of the differences were introduced
well before Python 3).

Kent

-- Forwarded message --
From: Mark Summerfield 
To: comp-lang-python-annou...@moderators.isc.org
Date: Tue, 1 Dec 2009 06:05:09 -0800 (PST)
Subject: Moving from Python 2 to Python 3: A 4 page "cheat sheet"
I've produced a 4 page document that provides a very concise summary
of Python 2<->3 differences plus the most commonly used new Python 3
features. It is aimed at existing Python 2 programmers who want to
start writing Python 3 programs and want to use Python 3 idioms rather
than those from Python 2 where the idioms differ.

It uses Python 3.1 syntax since that looks like being the standard for
a few years in view of the language moratorium.

The document is U.S. Letter size but will also print fine on A4
printers.

It is available as a free PDF download (no registration or anything)
from InformIT's website. Here's the direct link:
http://ptgmedia.pearsoncmg.com/imprint_downloads/informit/promotions/python/python2python3.pdf

And of course, if you want more on Python 3, there's always the
documentation---or my book:-)
"Programming in Python 3 (Second Edition)" ISBN-10: 0321680561.
--
Mark Summerfield, www.qtrac.eu
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Moving from Python 2 to Python 3: A 4 page "cheatsheet"

2009-12-02 Thread Alan Gauld


"Kent Johnson"  wrote


Forwarded from python-announce. A helpful summary of the differences
between Python 2 and 3 (though some of the differences were introduced
well before Python 3).



It is available as a free PDF download (no registration or anything)
from InformIT's website. Here's the direct link:
http://ptgmedia.pearsoncmg.com/imprint_downloads/informit/promotions/python/python2python3.pdf



It didn't work for me I always got forwarded to the Book "home page" on 
InformIT


Alan G 



___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] pygame help with livewires

2009-12-02 Thread Skylar Struble
ok so its working and drops a normal cow and randomly a green cow but
i want it to be able to tell when you collide with the green cow cause
its gonna be a powerup.

heres the code for my program.

# Pizza Panic
# Player must catch falling pizzas before they hit the ground

from livewires import games, color
import random
hscorefile = open("hscores.txt", 'r')
score = 0
level = 1
pizzascore = 2
stl = 15
lstl = 15
pizza_speed = 1
cook_speed = 4
pizza_drop = 0.5
level_up_drop = 1
highscore = int(hscorefile.read(1))
hscorefile.close()
games.init(screen_width = 640, screen_height = 480, fps = 50)

class Pan(games.Sprite):
"""
A pan controlled by player to catch falling pizzas.
"""
global score
image = games.load_image("pan.bmp")

def __init__(self):
""" Initialize Pan object and create Text object for score. """
global level
global hs
global score
super(Pan, self).__init__(image = Pan.image, x =
games.mouse.x, bottom = games.screen.height)

self.score = games.Text(value = 0, size = 25, color = color.black,
   top = 5, right = games.screen.width - 10)
games.screen.add(self.score)
self.leveltxt = games.Text(value = "level:", size = 25, color
= color.black,
top = 5, right = games.screen.width - 580)
games.screen.add(self.leveltxt)
self.level = games.Text(value = level, size = 25, color = color.black,
top = 5, right = games.screen.width - 566)
games.screen.add(self.level)
self.hs = games.Text(value = "Highscore:" + str(highscore),
size = 25, color = color.black,
top = 5, right = games.screen.width - 320)
games.screen.add(self.hs)

def update(self):
""" Move to mouse x position. """
self.x = games.mouse.x

if self.left < 0:
self.left = 0

if self.right > games.screen.width:
self.right = games.screen.width

self.check_catch()

def check_catch(self):
""" Check if catch pizzas. """
global pizza_drop
global level
global score
global score_to_level
global cook_speed
global pizza_speed
global stl
global lstl
global pizzascore
stl = (lstl *2.5)
for pizza in self.overlapping_sprites:
self.score.value = self.score.value + pizzascore
score = self.score.value
if self.score.value >= stl:
lstl = stl
pizza_drop += 0.2
self.level.value += 1
pizza_speed += .25
pizzascore = pizzascore * 2
cook_speed += 5
level = level + 1
lvlup_message = games.Message(value = "Level " + str(level),
size = 90,
color = color.red,
x = games.screen.width/2,
y = games.screen.height/2,
lifetime = 2 * games.screen.fps)
games.screen.add(lvlup_message)
self.score.right = games.screen.width - 10
pizza.handle_caught()
class Pizza(games.Sprite):
"""
A pizza which falls to the ground.
"""
global pizza_speed
speed = 1.5
image = games.load_image("pizza.bmp")

def __init__(self, x, y = 90):
""" Initialize a Pizza object. """
super(Pizza, self).__init__(image = Pizza.image,
x = x, y = y,
dy = pizza_speed)

def update(self):
""" Check if bottom edge has reached screen bottom. """
if self.bottom > games.screen.height:
self.end_game()
self.destroy()

def handle_caught(self):
""" Destroy self if caught. """
self.destroy()

def end_game(self):
global highscore
global score
global name
""" End the game. """
if score > highscore:
hsfile = open("hscores.txt", "w")
hsfile.write(str(score))
hsfile.close()
hs_message = games.Message(value ="New highscore of " + str(score),
size = 45,
color = color.red,
x = games.screen.width/2,
y = games.screen.height/2,
lifetime = 1 * games.screen.fps,
after_death = games.screen.quit)
games.screen.add(hs_message)
else:
end_message = games.Message(value = "game over",
size = 45,
color = color.red,
x = games.screen.width/2,
y = 

Re: [Tutor] Moving from Python 2 to Python 3: A 4 page "cheatsheet"

2009-12-02 Thread Kent Johnson
On Wed, Dec 2, 2009 at 8:56 AM, Alan Gauld  wrote:
>
> "Kent Johnson"  wrote
>
>> Forwarded from python-announce. A helpful summary of the differences
>> between Python 2 and 3 (though some of the differences were introduced
>> well before Python 3).
>
>> It is available as a free PDF download (no registration or anything)
>> from InformIT's website. Here's the direct link:
>>
>> http://ptgmedia.pearsoncmg.com/imprint_downloads/informit/promotions/python/python2python3.pdf
>
>
> It didn't work for me I always got forwarded to the Book "home page" on
> InformIT

Strange. Worked for me yesterday and again just now.

Kent
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Moving from Python 2 to Python 3: A 4 page "cheatsheet"

2009-12-02 Thread Joerg Woelke
* Alan Gauld  [091202 15:07]:
> >http://ptgmedia.pearsoncmg.com/imprint_downloads/informit/promotions/python/python2python3.pdf
> 
> 
> It didn't work for me I always got forwarded to the Book "home page"
> on InformIT
Worked for me with wget(1).

-- 
You are capable of planning your future.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Moving from Python 2 to Python 3: A 4 page "cheatsheet"

2009-12-02 Thread Wayne Werner
On Wed, Dec 2, 2009 at 8:13 AM, Joerg Woelke  wrote:

>  Alan Gauld  [091202 15:07]:
> > >
> http://ptgmedia.pearsoncmg.com/imprint_downloads/informit/promotions/python/python2python3.pdf
> >
> >
> > It didn't work for me I always got forwarded to the Book "home page"
> > on InformIT
> Worked for me with wget(1).
>


And for me with Google Chrome on Ubuntu...
-Wayne
-- 
To be considered stupid and to be told so is more painful than being called
gluttonous, mendacious, violent, lascivious, lazy, cowardly: every weakness,
every vice, has found its defenders, its rhetoric, its ennoblement and
exaltation, but stupidity hasn’t. - Primo Levi
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Moving from Python 2 to Python 3: A 4 page "cheatsheet"

2009-12-02 Thread Eddie
Thanks

2009/12/3 Wayne Werner 

>
>
> On Wed, Dec 2, 2009 at 8:13 AM, Joerg Woelke  wrote:
>
>>  Alan Gauld  [091202 15:07]:
>> > >
>> http://ptgmedia.pearsoncmg.com/imprint_downloads/informit/promotions/python/python2python3.pdf
>> >
>> >
>> > It didn't work for me I always got forwarded to the Book "home page"
>> > on InformIT
>> Worked for me with wget(1).
>>
>
>
> And for me with Google Chrome on Ubuntu...
> -Wayne
> --
> To be considered stupid and to be told so is more painful than being called
> gluttonous, mendacious, violent, lascivious, lazy, cowardly: every weakness,
> every vice, has found its defenders, its rhetoric, its ennoblement and
> exaltation, but stupidity hasn’t. - Primo Levi
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] working with bit arrays

2009-12-02 Thread Robert Berman
Hi,

I am trying to represent a number as a list of bits: for example the bit
representation of the integer 8. I did find a number of articles
pertaining to a module called bitarray but I was unable to
download/install that package. I am using Linux on Ubuntu 9.10; Python
2.6.2. 

I am almost certain there is a relatively easy way to convert an integer
that can be represented by 32 bits into an array of bits that I can
iterate over looking for switched on bits or switched off bits. 

Any information such as recipes or past articles in this list providing
methods to create and manipulate  bit arrays would be most appreciated.

Robert



___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] working with bit arrays

2009-12-02 Thread Wayne Werner
On Wed, Dec 2, 2009 at 12:08 PM, Robert Berman  wrote:

>  Hi,
>
> I am trying to represent a number as a list of bits: for example the bit
> representation of the integer 8. I did find a number of articles pertaining
> to a module called bitarray but I was unable to download/install that
> package. I am using Linux on Ubuntu 9.10; Python 2.6.2.
>
> I am almost certain there is a relatively easy way to convert an integer
> that can be represented by 32 bits into an array of bits that I can iterate
> over looking for switched on bits or switched off bits.
>
> Any information such as recipes or past articles in this list providing
> methods to create and manipulate  bit arrays would be most appreciated.
>

Python 2.6+ (as far as I know) has the bin() function:

Python 2.6.2 (r262:71605, Apr 14 2009, 22:40:02) [MSC v.1500 32 bit (Intel)]
on
win32
Type "help", "copyright", "credits" or "license" for more information.
>>> bin(8)
'0b1000'
>>>

And larger:

>>> bin(999)
'0b10101001011010010110001110100101001100111'

You can convert them to integers to use ^ (XOR) or & (AND) and other binary
operations on them:
http://docs.python.org/reference/expressions.html#binary-bitwise-operations

>>> a = int('01001', 2)
>>> b = int('1', 2)
>>> a & b == b
True
>>> a = int('01110', 2)
>>> a & b == b
False

There may be some other way to check, but that's probably the easiest I know
of.

HTH,
Wayne
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] working with bit arrays

2009-12-02 Thread Robert Berman
Wayne,

Thank you very much.

Robert

On Wed, 2009-12-02 at 12:48 -0600, Wayne Werner wrote:
> On Wed, Dec 2, 2009 at 12:08 PM, Robert Berman 
> wrote:
> 
> Hi,
> 
> I am trying to represent a number as a list of bits: for
> example the bit representation of the integer 8. I did find a
> number of articles pertaining to a module called bitarray but
> I was unable to download/install that package. I am using
> Linux on Ubuntu 9.10; Python 2.6.2. 
> 
> I am almost certain there is a relatively easy way to convert
> an integer that can be represented by 32 bits into an array of
> bits that I can iterate over looking for switched on bits or
> switched off bits. 
> 
> Any information such as recipes or past articles in this list
> providing methods to create and manipulate  bit arrays would
> be most appreciated.
> 
> 
> 
> Python 2.6+ (as far as I know) has the bin() function:
> 
> 
> Python 2.6.2 (r262:71605, Apr 14 2009, 22:40:02) [MSC v.1500 32 bit
> (Intel)] on
> win32
> Type "help", "copyright", "credits" or "license" for more information.
> >>> bin(8)
> '0b1000'
> >>>
> 
> 
> And larger:
> 
> 
> >>> bin(999)
> '0b10101001011010010110001110100101001100111'
> 
> 
> You can convert them to integers to use ^ (XOR) or & (AND) and other
> binary operations on
> them: 
> http://docs.python.org/reference/expressions.html#binary-bitwise-operations
> 
> 
> >>> a = int('01001', 2)
> >>> b = int('1', 2)
> >>> a & b == b
> True
> >>> a = int('01110', 2)
> >>> a & b == b
> False
> 
> 
> There may be some other way to check, but that's probably the easiest
> I know of.
> 
> 
> HTH,
> Wayne
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] working with bit arrays

2009-12-02 Thread Chris Fuller

My approach has been to store it as an array and then build the integer as 
needed.  This code requires Python 2.5 or later.

def bits2int(l):
   return sum([2**i if j else 0 for i,j in enumerate(l)])

To convert the other way:

def int2bits(m, n):
   return [int(bool(m&(1<>= inc

   return i

floating point is so messy and slow :)

Cheers

On Wednesday 02 December 2009 12:08, Robert Berman wrote:
> Hi,
>
> I am trying to represent a number as a list of bits: for example the bit
> representation of the integer 8. I did find a number of articles
> pertaining to a module called bitarray but I was unable to
> download/install that package. I am using Linux on Ubuntu 9.10; Python
> 2.6.2.
>
> I am almost certain there is a relatively easy way to convert an integer
> that can be represented by 32 bits into an array of bits that I can
> iterate over looking for switched on bits or switched off bits.
>
> Any information such as recipes or past articles in this list providing
> methods to create and manipulate  bit arrays would be most appreciated.
>
> Robert
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Tutor Digest, Vol 70, Issue 5

2009-12-02 Thread aivars
,
>                                        x = games.screen.width/2,
>                                        y = games.screen.height/2,
>                                        lifetime = 1 * games.screen.fps,
>                                        after_death = games.screen.quit)
>            games.screen.add(hs_message)
>        else:
>            end_message = games.Message(value = "game over",
>                                        size = 45,
>                                        color = color.red,
>                                        x = games.screen.width/2,
>                                        y = games.screen.height/2,
>                                        lifetime = 0 * games.screen.fps,
>                                        after_death = games.screen.quit)
>            games.screen.add(end_message)
>
>
> class power_pizza1(games.Sprite):
>    """
>    A pizza which falls to the ground.
>    """
>    global pizza_speed
>    speed = 1.5
>    image = games.load_image("power_pizza1.bmp")
>
>    def __init__(self, x, y = 90):
>        """ Initialize a Pizza object. """
>        super(power_pizza1, self).__init__(image = power_pizza1.image,
> x = x, y = y, dy = pizza_speed)
>
>
>    def update(self):
>        """ Check if bottom edge has reached screen bottom. """
>        if self.bottom > games.screen.height:
>            self.destroy()
>
>    def handle_caught(self):
>        """ Destroy self if caught. """
>        self.destroy()
> class Chef(games.Sprite):
>    """
>    A chef which moves left and right, dropping pizzas.
>    """
>    global cook_speed
>    image = games.load_image("chef.bmp")
>
>    def __init__(self, y = 55, speed = 1000, odds_change = 55):
>        """ Initialize the Chef object. """
>        super(Chef, self).__init__(image = Chef.image,
>                                   x = games.screen.width / 2,
>                                   y = y,
>                                   dx = cook_speed)
>
>        self.odds_change = odds_change
>        self.time_til_drop = 0
>
>
>    def update(self):
>        """ Determine if direction needs to be reversed. """
>        if self.left < 0 or self.right > games.screen.width:
>            self.dx = -self.dx
>        elif random.randrange(self.odds_change) == 0:
>           self.dx = -self.dx
>
>        self.check_drop()
>
>
>    def check_drop(self):
>        rpp = 5
>        """ Decrease countdown or drop pizza and reset countdown. """
>        global pizza_drop
>        if self.time_til_drop > 0:
>            self.time_til_drop -= pizza_drop
>        else:
>            new_pizza = Pizza(x = random.randrange(40, 600))
>            rpp = random.randrange(1, 5)
>            if rpp == 3:
>                power_pizza = power_pizza1 (x = random.randrange(40, 600))
>                games.screen.add(power_pizza)
>            else:
>                games.screen.add(new_pizza)
>
>            # set buffer to approx 30% of pizza height, regardless of
> pizza speed
>            self.time_til_drop = int(new_pizza.height * 1.3 / Pizza.speed) + 1
>
>
> def main():
>    """ Play the game. """
>    wall_image = games.load_image("wall.jpg", transparent = False)
>    games.screen.background = wall_image
>
>    the_chef = Chef()
>    games.screen.add(the_chef)
>
>    the_pan = Pan()
>    games.screen.add(the_pan)
>
>    games.mouse.is_visible = False
>
>    games.screen.event_grab = True
>    games.screen.mainloop()
>
> # start it up!
> main()
>
>
> --
>
> Message: 4
> Date: Wed, 2 Dec 2009 10:13:25 -0500
> From: Kent Johnson 
> To: Alan Gauld 
> Cc: tutor@python.org
> Subject: Re: [Tutor] Moving from Python 2 to Python 3: A 4 page
>        "cheatsheet"
> Message-ID:
>        <1c2a2c590912020713l72b85952ka4d5b8f3d1e2a...@mail.gmail.com>
> Content-Type: text/plain; charset=ISO-8859-1
>
> On Wed, Dec 2, 2009 at 8:56 AM, Alan Gauld  wrote:
>>
>> "Kent Johnson"  wrote
>>
>>> Forwarded from python-announce. A helpful summary of the differences
>>> between Python 2 and 3 (though some of the differences were introduced
>>> well before Python 3).
>>
>>> It is available as a free PDF download (no registration or anything)
>>> 

Re: [Tutor] working with bit arrays

2009-12-02 Thread Kent Johnson
On Wed, Dec 2, 2009 at 1:08 PM, Robert Berman  wrote:
> Hi,
>
> I am trying to represent a number as a list of bits: for example the bit
> representation of the integer 8. I did find a number of articles pertaining
> to a module called bitarray but I was unable to download/install that
> package. I am using Linux on Ubuntu 9.10; Python 2.6.2.
>
> I am almost certain there is a relatively easy way to convert an integer
> that can be represented by 32 bits into an array of bits that I can iterate
> over looking for switched on bits or switched off bits.

If all you want to do is test bits, you can do that directly using
bit-wise logical operators & and |. There is no need to convert to a
different representation. For example

In [1]: 0xff & 4
Out[1]: 4

In [2]: 0xf0 & 4
Out[2]: 0

Kent
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Moving from Python 2 to Python 3

2009-12-02 Thread Kent Johnson
I don't know that you will reach Mark through this list, I forwarded
his post from another list. There is some info on the book web site:
http://www.qtrac.eu/py3book.html

When replying to a digest, please
- change the subject line to something relevant
- don't quote the entire digest in your reply.

Kent

On Wed, Dec 2, 2009 at 2:15 PM, aivars  wrote:
> Mark,
> I have the first edition of your book. What is the difference between
> two editions?
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Moving from Python 2 to Python 3

2009-12-02 Thread wesley chun
>> I have the first edition of your book. What is the difference between
>> two editions?

i believe the 1st ed is 3.0 and the 2nd ed is 3.1 but haven't
confirmed with him yet.

-- wesley
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
"Core Python Programming", Prentice Hall, (c)2007,2001
"Python Fundamentals", Prentice Hall, (c)2009
http://corepython.com

wesley.j.chun :: wescpy-at-gmail.com
python training and technical consulting
cyberweb.consulting : silicon valley, ca
http://cyberwebconsulting.com
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] working with bit arrays

2009-12-02 Thread Alan Plum
On Mi, 2009-12-02 at 13:08 -0500, Robert Berman wrote:
> Hi,
> 
> I am trying to represent a number as a list of bits: for example the
> bit representation of the integer 8. I did find a number of articles
> pertaining to a module called bitarray but I was unable to
> download/install that package. I am using Linux on Ubuntu 9.10; Python
> 2.6.2. 
> 
> I am almost certain there is a relatively easy way to convert an
> integer that can be represented by 32 bits into an array of bits that
> I can iterate over looking for switched on bits or switched off bits. 

If all you want is to treat integers as lists of bits, you could create
a wrapper class around an integer and implement the __getitem__ and
__setitem__ methods to make it behave like a list. Using the bitwise
operators, you could make the setter actually modify the bit in question
(you'd probably have to either make sure you only receive 1 or 0 as
value or you could simply use booleans instead).

For a challenge you could try to extend the built-in integer type this
way.

I'm not sure why you'd need to be able to address bits directly like
that, though. Normally the bitwise &, |, << and >> should suffice for
all intents and purposes.

Making an ACTUAL lists of ACTUAL integers representing the bits would be
overkill, though. We're talking several bytes worth of nulls to
represent a single bit. I'm all for late optimisation, but this just
doesn't feel right.


Cheers,

Alan

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] working with bit arrays

2009-12-02 Thread GilJohnson
As`Kent Johnson pointed out, you don't need to convert anything to strings, etc.
An integer _is_ a bit array, and individual bits can be tested using the bitwise
operators. For your example, if A is an integer you can test bit 8 with:
if A & (1 << 8): dosomething
There is a simple example on the Python wiki at
http://wiki.python.org/moin/BitArrays
It uses an array of 32-bit integers as a bit array.
The advantage of using 'bitarray' or one of the other packages on the Python
Package Index is that they have implemented all of the slicing, etc. of Python
lists, strings, etc. Using an array of 32 bit integers, you have to go to some
trouble to slice out, say, bits 20 to 40.
HTH,
Gil


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] working with bit arrays

2009-12-02 Thread Alan Gauld


"Robert Berman"  wrote


I am trying to represent a number as a list of bits: for example the bit
representation of the integer 8.



Numbers are already represented as arrays of bits, thats how
they are stored.


I am almost certain there is a relatively easy way to convert an integer
that can be represented by 32 bits into an array of bits that I can
iterate over looking for switched on bits or switched off bits.


You can do that using bitmasks. For example to extract the 4th bit
use

bit4 = value & 0x08# 0x08 = 1000

For bit 2 use

bit2 = value & 0x02   # 0x02 = 0010

You can iterate over each bit using

for index in range(number_of_bits):
 print "bit", index + 1, "is", int(bool(value & (2**index)))# 
int(bool()) prints 1/0


Or am I missing something?

--
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/ 



___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Moving from Python 2 to Python 3

2009-12-02 Thread Alan Gauld


"wesley chun"  wrote 


i believe the 1st ed is 3.0 and the 2nd ed is 3.1 but haven't
confirmed with him yet.


I bought the 1st edition which is definitely 3.0.
It was quite good I thought.

I doubt I'll buy another edition just for the 3.1 uplift, but if he 
covers the new themed widgets in tkinter I might change 
my mind! :-)


Alan G.

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] working with bit arrays

2009-12-02 Thread Emile van Sebille

On 12/2/2009 4:10 PM GilJohnson said...


Using an array of 32 bit integers, you have to go to some
trouble to slice out, say, bits 20 to 40.


I think I agree -- if in fact it's not impossible.  Tell me that's a 
typo or take a moment to explain what I'm misunderstanding...


Emile


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] working with bit arrays

2009-12-02 Thread Robert Berman
Emille,

I do think he meant bit 20 to 32 rather than 20 to 40. Unless, of
course, he's dealing with a 64 bit word.

I am delighted with all the help I have received on this topic and I am
gleefully learning anding and oring, but not too much on the EOR side.

Thanks again for all the assistance.

Robert

On Wed, 2009-12-02 at 17:17 -0800, Emile van Sebille wrote:

> On 12/2/2009 4:10 PM GilJohnson said...
> 
> > Using an array of 32 bit integers, you have to go to some
> > trouble to slice out, say, bits 20 to 40.
> 
> I think I agree -- if in fact it's not impossible.  Tell me that's a 
> typo or take a moment to explain what I'm misunderstanding...
> 
> Emile
> 
> 
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Do you use unit testing?

2009-12-02 Thread Kent Johnson
Uncle Bob Martin has written a great post about TDD:
http://blog.objectmentor.com/articles/2009/10/06/echoes-from-the-stone-age

"Look, TDD is not my religion, it is one of my disciplines. It’s like
dual entry bookkeeping for accountants, or sterile procedure for
surgeons. Professionals adopt such disciplines because they understand
the theory behind them, and have directly experienced the benefits of
using them."

The rest of the post is good too!

Kent
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] working with bit arrays

2009-12-02 Thread Dave Angel

Robert Berman wrote:

Emille,

I do think he meant bit 20 to 32 rather than 20 to 40. Unless, of
course, he's dealing with a 64 bit word.

  
You posted out of order (top--osted).  So I am forced to put my response 
elsewhere.

I am delighted with all the help I have received on this topic and I am
gleefully learning anding and oring, but not too much on the EOR side.

Thanks again for all the assistance.

Robert

On Wed, 2009-12-02 at 17:17 -0800, Emile van Sebille wrote:

  

On 12/2/2009 4:10 PM GilJohnson said...



Using an array of 32 bit integers, you have to go to some
trouble to slice out, say, bits 20 to 40.
  
I think I agree -- if in fact it's not impossible.  Tell me that's a 
typo or take a moment to explain what I'm misunderstanding...


Emile



Once you have an *array* of integers, you have much more than 32 bits to 
work with.  For example, with an array of size 10, you now have 320 bits 
to work with.  He's just pointing out that it's a little bit awkward to 
address a group of bits that are not all in the same int.  So bits 5-20 
would be easy, while bits 29-40 would be much harder.


DaveA

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor