Re: [Tutor] Problem with calling class methods stored in a list

2013-01-11 Thread Peter Otten
Tobias M. wrote:

 Am 10.01.2013 15:15, schrieb Peter Otten:
 Of course handle_1_42() is not exactly the method name one would hope
 for. You could, again, strive for simplicity and add a lookup table that
 maps protocol tuples to function /names/ , but as simplicity doesn't seem
 to be your cup of tea:

 class HandlersType(type):
  def __init__(cls, name, bases, classdict):
  cls.lookup_protocol = lookup = {}
  for k, v in classdict.items():
  if isinstance(v, protocol_method):
  lookup[v.protocol] = getattr(cls, k)

 class protocol_method(classmethod):
  pass

 def protocol(x, y):
  def attach_protocol(f):
  f = protocol_method(f)
  f.protocol = x, y
  return f
  return attach_protocol

 class D:
  __metaclass__ = HandlersType

  @protocol(42, 17)
  def foo(cls):
  print Hi

 D.lookup_protocol[42, 17]()

 ;)

 In my eyes this is anything but simple.
 Correct me if I'm wrong:
 I already use a lookup table in my code, called method_list in my
 first post. The advantage of your above code is that I don't need to
 manually take care of the lookup table and extension by subclassing is
 easier.

You are right; the misunderstanding is that I wasn't advertising the above 
fancy solution (which is buggy, btw).

I have now implemented what I had in mind with the protocol to function name 
mapping, and I think /that/ is reasonably complex. I'm using instance 
methods in the demo, but it should work with class methods as well.

class Error(Exception):
def __init__(self, protocol):
Exception.__init__(self, self.template.format(protocol))

class UnknownProtocolError(Error):
template = Unknown protocol {}

class ProtocolNotSupportedError(Error):
template = Protocol {} not supported

FOO = (42, 17)
BAR = (1, 2)
BAZ = (3, 4)
HAM = (4, 5)
SPAM = (5, 6)

class HandlersBase(object):
protocol_to_methodname = {
FOO: foo,
BAR: bar,
BAZ: baz,
HAM: ham,
}
def get_handler(self, protocol):
try:
methodname = self.protocol_to_methodname[protocol]
except KeyError:
raise UnknownProtocolError(protocol)

method = getattr(self, methodname, None)
if method is None:
raise ProtocolNotSupportedError(protocol)
return method

class A(HandlersBase):
def foo(self): print A.foo
def bar(self): print A.bar
def baz(self): print A.baz

class B(A):
def bar(self): print B.bar
baz = None # hide parent implementation

if __name__ == __main__:

for Class in A, B:
inst = Class()
print ---, Class.__name__, ---
for protocol in FOO, BAR, BAZ, SPAM:
try:
inst.get_handler(protocol)()
except Error as err:
print err


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


[Tutor] OT: brainf**k program

2013-01-11 Thread Albert-Jan Roskam
Not quite PEP8 compliant, but quite nifty: 
http://www.cs.princeton.edu/~ynaamad/misc/bf.htm
The program below interprets the follwing string as Hello World: 
++[+-]++.+.+++..+++.++.+++..+++.--..+..

 
(lambda t:(lambda a:(lambda b:(lambda 
l,e,s:((lambda(Y,o,N,A,t),a,n:e('v',(Y,o,N,A,t))or[e('v',(lambda(Y,o,N,A,t):({'':(lambda(Y,o,N,A,t),a,n:(Y,o,N+1,A+1,t)),'':(lambda(Y,o,N,A,t),a,n:(Y,o,N-1,A+1,t)),'+':(lambda(Y,o,N,A,t),a,n:((Y[:N]+[Y[N]+1]+Y[N+1:],o,N,A+1,t)if
 N=0 
else(Y,o[:-N-1]+[o[-N-1]+1]+o[-N:],N,A+1,t))),'-':(lambda(Y,o,N,A,t),a,n:((Y[:N]+[Y[N]-1]+Y[N+1:],o,N,A+1,t)if
 N=0 
else(Y,o[:-N-1]+[o[-N-1]-1]+o[-N:],N,A+1,t))),'.':(lambda(Y,o,N,A,t),a,n:__import__('sys').stdout.write(chr(Y[N]
 if N=0 else 
o[-N-1]))or(Y,o,N,A+1,t)),',':(lambda(Y,o,N,A,t),a,n:(Y[:N]+[ord(t[0])if 
len(t)else -1]+Y[N+1:]if A=0 else Y,o[:-N-1]+[ord(t[0])if len(t)else 
-1]+o[-N:]if A0 else o,N,A+1,t[1:])),'[':(lambda(Y,o,N,A,t),a,n:(Y,o,N,n[A]+1 
if(Y[N]==0 if N=0 else o[-N-1]==0)else 
A+1,t)),']':(lambda(Y,o,N,A,t),a,n:(Y,o,N,n[A]+1 if(Y[N]=1 if N=0 else 
o[-N-1]=1)else A+1,t))}[a[A]]((Y+[0]*(9+len(Y)) if A=len(Y)-5 else 
Y,o+[0]*(9+len(o)) if -A=len(o)-5 else
 o,N,A,t),a,n)if Alen(a)else False))(l('v')))for i in s.takewhile(lambda 
x:l('v')!=False,s.count())])(([],[],0,0,t),a,dict(e('g',[])or 
e('l',[])or[e('l',l('l')+[i])if 
a[i]=='['else(e('g',l('g')+[(l('l')[-1],i),(i,l('l')[-1])])or 
e('l',l('l')[:-1]))for i in range(len(a))if a[i] in'[]'][:0]or 
l('g'[:0])(b.__getattribute__,b.__setattr__,__import__('itertools')))(lambda:a)or
 
None)(filter(.+[,-].count,open(__import__('sys').argv[1]).read((raw_input())
 


Regards,
Albert-Jan


~~
All right, but apart from the sanitation, the medicine, education, wine, public 
order, irrigation, roads, a 
fresh water system, and public health, what have the Romans ever done for us?
~~ ___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Books for Learning Python

2013-01-11 Thread Chris Rogers
Hello all, I've began my journey into Python (2.7 currently) and I'm
finding it a bit rough using the python.org tutorials.  Although chalked
full of information I find it a bit overwhelming.  Can anyone recommend a
book, or two, or three that would be great material for really learning the
language.  I tend to learn better with a little structure and I feel a good
book would be the best approach for myself.  Any advice would be greatly
appreciated. --Thanks!
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Books for Learning Python

2013-01-11 Thread Femi Banjo

Not Books but have you tried any of the online learning courses?
They're free and look very good from my equally beginner perspective as I 
struggle through them(allow more time than you think :[ )
www.coursera.org
www.edx.org
www.udacity.com

all very good, take you pick!

From: quent...@gmail.com
Date: Fri, 11 Jan 2013 08:10:46 -0600
To: tutor@python.org
Subject: [Tutor] Books for Learning Python

Hello all, I've began my journey into Python (2.7 currently) and I'm finding it 
a bit rough using the python.org tutorials.  Although chalked full of 
information I find it a bit overwhelming.  Can anyone recommend a book, or two, 
or three that would be great material for really learning the language.  I tend 
to learn better with a little structure and I feel a good book would be the 
best approach for myself.  Any advice would be greatly appreciated. --Thanks!

___
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] Books for Learning Python

2013-01-11 Thread jh
There is also this - http://www.codecademy.com/#!/exercises/0

 

 

From: Tutor [mailto:tutor-bounces+xperimental22=gmail@python.org] On
Behalf Of Chris Rogers
Sent: Friday, January 11, 2013 9:11 AM
To: tutor@python.org
Subject: [Tutor] Books for Learning Python

 

Hello all, I've began my journey into Python (2.7 currently) and I'm finding
it a bit rough using the python.org tutorials.  Although chalked full of
information I find it a bit overwhelming.  Can anyone recommend a book, or
two, or three that would be great material for really learning the language.
I tend to learn better with a little structure and I feel a good book would
be the best approach for myself.  Any advice would be greatly appreciated.
--Thanks! 

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


Re: [Tutor] Books for Learning Python

2013-01-11 Thread Alan Gauld

On 11/01/13 14:10, Chris Rogers wrote:

Hello all, I've began my journey into Python (2.7 currently) and I'm
finding it a bit rough using the python.org http://python.org
tutorials.


You don't tell us your starting point.

Are you experienced in programming in other languages or is python your 
first foray into Programming? Are you a professional or hobbyist?


Do you have a scientific or math background?

All of these influence what makes a book suitable.
Some of the tutorials listed on Python.org are also paper books 
(including mine).


Which tutorials have you looked at? The official tutor is good for 
people who can already program. The non-programmes ones are better if 
you can't already program (as you'd expect!). There are also several 
python videos available on sites like showmedo.com


If you can answer the above questions we might be able to recommend some 
books.


--
Alan G
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


[Tutor] help for a beginner

2013-01-11 Thread MDB
Hi,
I am a beginner to progrmming and want to learn basic python. I am a
scientist (with less math background) with absolutely no programming
experience. Are there any web based tutorials/videos/books to learn python.

Any help is deeply appreciated,
thanks
Murail
-- 
Murali Dharan Bashyam, PhD, MNAScI
Staff Scientist and Chief,
Laboratory of Molecular Oncology,
Centre for DNA Fingerprinting and Diagnostics (CDFD),
Tuljaguda complex, Nampally,
Hyderabad 51, INDIA
Ph: 91-40-24749383
Fax: 91-40-24749448
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] help for a beginner

2013-01-11 Thread vishwajeet singh
On Sat, Jan 12, 2013 at 12:28 AM, MDB bashya...@gmail.com wrote:

 Hi,
 I am a beginner to progrmming and want to learn basic python. I am a
 scientist (with less math background) with absolutely no programming
 experience. Are there any web based tutorials/videos/books to learn python.


The best book for beginners in my experience is Python for Absolute
Beginners, I liked it's approach in making learning a bit fun.
A good online resource is http://www.alan-g.me.uk/


 Any help is deeply appreciated,
 thanks
 Murail
 --
 Murali Dharan Bashyam, PhD, MNAScI
 Staff Scientist and Chief,
 Laboratory of Molecular Oncology,
 Centre for DNA Fingerprinting and Diagnostics (CDFD),
 Tuljaguda complex, Nampally,
 Hyderabad 51, INDIA
 Ph: 91-40-24749383
 Fax: 91-40-24749448

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




-- 
Vishwajeet Singh
+91-9657702154 | dextrou...@gmail.com | http://bootstraptoday.com
Twitter: http://twitter.com/vishwajeets | LinkedIn:
http://www.linkedin.com/in/singhvishwajeet
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] help for a beginner

2013-01-11 Thread Graham Dubow
Murail,

Check out Udacity.com and the CS101 course. Great video lectures reinforced
by homework and problems (with answers) that you can do yourself. Also
has a very good forum and active user base to ask questions.

It is a good starting point for a beginner and teaches the basics behind
how to build a simple web crawler using Python.




Cheers,


Graham

On Fri, Jan 11, 2013 at 1:58 PM, MDB bashya...@gmail.com wrote:

 Hi,
 I am a beginner to progrmming and want to learn basic python. I am a
 scientist (with less math background) with absolutely no programming
 experience. Are there any web based tutorials/videos/books to learn python.

 Any help is deeply appreciated,
 thanks
 Murail
 --
 Murali Dharan Bashyam, PhD, MNAScI
 Staff Scientist and Chief,
 Laboratory of Molecular Oncology,
 Centre for DNA Fingerprinting and Diagnostics (CDFD),
 Tuljaguda complex, Nampally,
 Hyderabad 51, INDIA
 Ph: 91-40-24749383
 Fax: 91-40-24749448

 ___
 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] garbage collection/class question

2013-01-11 Thread Jan Riechers

On 10.01.2013 19:50, Mitya Sirenef wrote:

On 01/10/2013 09:06 AM, richard kappler wrote:

class Tree(object):
 height = 0

 def grow(self):
 self.height += 1

You may have a dozen of related functions and you can logically group
them together by making them methods of a class, making it easier to
think about and work on the logic of your program.





Actually one question about those dozens of related instances 
generated by:

greenwoodTree = Tree()
oakTree = Tree()


Both, greenwoodTree and oakTree, are derived from Tree class, thus 
receiving the features and also - if so - holding unique values created 
in there __init__ generator method - self.height, self.color and so 
forth uniquely each.


But do both share the same function memory space from the class Tree?

I am currently trying also to get my head wrapped around OOP in general, 
but not 100% sure so that derived instances use the same functions (also 
memory wise speaking) - or are there several definitions of grow ?


The confusion came somehow when reading about classmethods and 
staticmethods and patterns like Singleton, monostate, borg...
from which I understand only ensure that the self.height properties 
are shared across multiple instances of a given class?


From what I tried out using id() and generating functions in a loop - 
the id(class.function) provided the same result when printed out, 
according to that:

http://stackoverflow.com/questions/121396/accessing-object-memory-address

So I assume the functions are shared across thus one decleration has 
been made in Tree class and all siblings are using that one?


Thank you in advance for clarification.

Jan

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


Re: [Tutor] Books for Learning Python

2013-01-11 Thread Gary L. Gray
On Jan 11, 2013, at 1:39 PM, Alan Gauld alan.ga...@btinternet.com wrote:

 On 11/01/13 14:10, Chris Rogers wrote:
 Hello all, I've began my journey into Python (2.7 currently) and I'm
 finding it a bit rough using the python.org http://python.org
 tutorials.
 
 You don't tell us your starting point.
 
 Are you experienced in programming in other languages or is python your first 
 foray into Programming? Are you a professional or hobbyist?
 
 Do you have a scientific or math background?
 
 All of these influence what makes a book suitable.
 Some of the tutorials listed on Python.org are also paper books (including 
 mine).
 
 Which tutorials have you looked at? The official tutor is good for people who 
 can already program. The non-programmes ones are better if you can't already 
 program (as you'd expect!). There are also several python videos available on 
 sites likeshowmedo.com
 
 If you can answer the above questions we might be able to recommend some 
 books.

I am also looking for some good resources for learning Python. Here is my 
background.

I did a lot of programming in Fortran 77 while working on my Ph.D. in 
engineering mechanics (graduated in 1993). I did some simple programming in 
Matlab and Mathematica in the 90s, but all the coding for my research since 
then has been done by my graduate students. I want to get back into programming 
so that I can create applications and animate the motion of objects for 
undergraduate and graduate dynamics courses I teach. Friends tell me Python is 
a good choice for an object oriented language (about which I know almost 
nothing) that has a readable syntax.

With this in mind, I have two questions:

(1) Will Python allow me to create applications that provide a simple GUI 
interface to something like an integrator for ODEs? Does it have graphics 
libraries that allow one to animate the motion of simple objects (e.g., 
spheres, ellipsoids, parallelepipeds, etc.) based on the results of numerical 
simulations?

(2) If the answers to the above questions are generally yes, where are some 
good places to get started learning Python to achieve my goals?

Thank you.

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


Re: [Tutor] garbage collection/class question

2013-01-11 Thread Dave Angel
On 01/11/2013 02:41 PM, Jan Riechers wrote:
 On 10.01.2013 19:50, Mitya Sirenef wrote:
 On 01/10/2013 09:06 AM, richard kappler wrote:

 class Tree(object):
  height = 0

  def grow(self):
  self.height += 1

 You may have a dozen of related functions and you can logically group
 them together by making them methods of a class, making it easier to
 think about and work on the logic of your program.




 Actually one question about those dozens of related instances
 generated by:
 greenwoodTree = Tree()
 oakTree = Tree()
 

 Both, greenwoodTree and oakTree, are derived from Tree class, 

It's important that we use correct, or at least close terminology.  A
derived class is VERY different from an instance.  greenWoodTree and
oakTree are bound to different instances of Tree.

 thus receiving the features and also - if so - holding unique values
 created in there __init__ generator method

__init__ is not a generator.  it's simply a method.  A method is a
function that's defined inside a class

 - self.height, self.color and so forth uniquely each.

We have to be careful here.  Such data can be attributes of an instance,
or they can be attributes of a class.  Strangely enough, this example
has a self.height and tree.height that are both called height, but
technically distinct values.  I think it's best if you avoid such
things, and use unique names till you've got the fundamentals straight.


 But do both share the same function memory space from the class Tree?


I wouldn't use the term function memory space, but I'll say this much. 
Unless you do something tricky, there is only one method Tree.grow, and
all instances share that same method.  No duplicated memory at all.

 I am currently trying also to get my head wrapped around OOP in
 general, but not 100% sure so that derived instances use the same
 functions (also memory wise speaking) - or are there several
 definitions of grow ?

Not yet.  Creating instances don't duplicate any methods.  You'd have to
do something explicit, and advanced.


 The confusion came somehow when reading about classmethods and
 staticmethods and patterns like Singleton, monostate, borg...
 from which I understand only ensure that the self.height properties
 are shared across multiple instances of a given class?


I'd consider all of those as advanced techniques, and a complete
confusion at your present stage. classmethods and staticmethods affect
the parameters that a method gets, not whether data properties belong to
the class or to the method.

 From what I tried out using id() and generating functions in a loop -
 the id(class.function) provided the same result when printed out,
 according to that:
 http://stackoverflow.com/questions/121396/accessing-object-memory-address

 So I assume the functions are shared across thus one decleration has
 been made in Tree class and all siblings are using that one?


Without showing the code in this loop, I can't comment on what you
observed.  Don't have any idea what you mean by a sibling.  The only
meaning I can think of is that two classes each derived from a common
base class can be considered siblings.  But you don't do any deriving in
this email.


-- 

DaveA

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


[Tutor] Binary/Decimal convertor

2013-01-11 Thread Ghadir Ghasemi
Hi, I made a program called binary/denary convertor. Can anyone tell me about 
how I could stop the user entering a binary number with more than 8 numbers or 
8 bit by repeating the question over and over until they do enter a correct 
binary number( 8-bit or less)
Here is the code. I started off by entering 'len' function.

def add_binary_numbers(num1, num2):
return num1 + num2

num1 = int(input('please enter the first 8 bit binary number: '),2)
if len(num1)  8:
print(please enter an 8 bit binary number)
return int(num1,2)
num2 = int(input('please enter the second 8 bit binary number: '),2)
result = add_binary_numbers(num1, num2)
print('the result is', bin(result)[2:])

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


Re: [Tutor] Books for Learning Python

2013-01-11 Thread lconrad


on line Python courses with labs

google python the hard way

udemy.com  also has python courses

https://developers.google.com/edu/python/

http://www.codecademy.com/tracks/python

google free online python programming classes courses

Len





On Friday 11/01/2013 at 3:18 pm, Gary L. Gray  wrote:
On Jan 11, 2013, at 1:39 PM, Alan Gauld alan.ga...@btinternet.com 
wrote:




On 11/01/13 14:10, Chris Rogers wrote:


Hello all, I've began my journey into Python (2.7 currently) and I'm
finding it a bit rough using the python.org http://python.org
tutorials.


You don't tell us your starting point.

Are you experienced in programming in other languages or is python 
your first foray into Programming? Are you a professional or hobbyist?


Do you have a scientific or math background?

All of these influence what makes a book suitable.
Some of the tutorials listed on Python.org are also paper books 
(including mine).


Which tutorials have you looked at? The official tutor is good for 
people who can already program. The non-programmes ones are better if 
you can't already program (as you'd expect!). There are also several 
python videos available on sites likeshowmedo.com


If you can answer the above questions we might be able to recommend 
some books.


I am also looking for some good resources for learning Python. Here is 
my background.


I did a lot of programming in Fortran 77 while working on my Ph.D. in 
engineering mechanics (graduated in 1993). I did some simple 
programming in Matlab and Mathematica in the 90s, but all the coding 
for my research since then has been done by my graduate students. I 
want to get back into programming so that I can create applications 
and animate the motion of objects for undergraduate and graduate 
dynamics courses I teach. Friends tell me Python is a good choice for 
an object oriented language (about which I know almost nothing) that 
has a readable syntax.


With this in mind, I have two questions:

(1) Will Python allow me to create applications that provide a simple 
GUI interface to something like an integrator for ODEs? Does it have 
graphics libraries that allow one to animate the motion of simple 
objects (e.g., spheres, ellipsoids, parallelepipeds, etc.) based on 
the results of numerical simulations?


(2) If the answers to the above questions are generally yes, where 
are some good places to get started learning Python to achieve my 
goals?


Thank you.

Gary L. Gray
___
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] Binary/Decimal convertor

2013-01-11 Thread David Rock
* Ghadir Ghasemi ghasemm...@leedslearning.net [2013-01-11 21:51]:
 Hi, I made a program called binary/denary convertor. Can anyone tell
 me about how I could stop the user entering a binary number with more
 than 8 numbers or 8 bit by repeating the question over and over until
 they do enter a correct binary number( 8-bit or less) Here is the
 code. I started off by entering 'len' function.
 
 def add_binary_numbers(num1, num2):
 return num1 + num2
 
 num1 = int(input('please enter the first 8 bit binary number: '),2)
 if len(num1)  8:
 print(please enter an 8 bit binary number)
 return int(num1,2)
 num2 = int(input('please enter the second 8 bit binary number: '),2)
 result = add_binary_numbers(num1, num2)
 print('the result is', bin(result)[2:])

It looks like the first thing you need to do is figure out how to use a
loop (eg, while loop, for loop).  I would recommend thinking about some
pseudocode to determine your program's flow and then try to build
something to accomplish that.

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


Re: [Tutor] Binary/Decimal convertor

2013-01-11 Thread Dave Angel
On 01/11/2013 04:51 PM, Ghadir Ghasemi wrote:
 Hi, I made a program called binary/denary convertor. Can anyone tell me about 
 how I could stop the user entering a binary number with more than 8 numbers 
 or 8 bit by repeating the question over and over until they do enter a 
 correct binary number( 8-bit or less)
 Here is the code. I started off by entering 'len' function.

 def add_binary_numbers(num1, num2):
 return num1 + num2

 num1 = int(input('please enter the first 8 bit binary number: '),2)
 if len(num1)  8:
 print(please enter an 8 bit binary number)
 return int(num1,2)
 num2 = int(input('please enter the second 8 bit binary number: '),2)
 result = add_binary_numbers(num1, num2)
 print('the result is', bin(result)[2:])



1.  Specify the Python version.  I'll assume version 3.3
2.  Show whatever error you got.  I'd guess something like the following:

  File stdin, line 1, in module
  TypeError: object of type 'int' has no len()



The len() function operates on strings, lists, and other sequences and
mappings.  But although you had a string at first, you've already
converted it to an int, which has no len() method.  It might be simplest
to compare the value num to 0 and 255.  Alternatively, you could compare
it before doing the int function.

Since you're doing it twice, it probably makes sense to do this in a
function.  Write a function that repeatedly asks the user till it gets a
value in the right range.

The other error that jumps out is that you have a return statement at
top-level, while the statement only makes sense inside a function.  That
problem goes away once you put the input logic inside a function.



-- 

DaveA

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


Re: [Tutor] garbage collection/class question

2013-01-11 Thread Alan Gauld

On 11/01/13 19:41, Jan Riechers wrote:


class Tree(object):
 height = 0

 def grow(self):
 self.height += 1



Actually one question about those dozens of related instances
generated by:
greenwoodTree = Tree()
oakTree = Tree()


Both, greenwoodTree and oakTree, are derived from Tree class,


Ok, a small terminology issue. They are not derived from Tree, they are 
Trees. They are two instances of the same class. Derived is used to 
suggest that they are sub classes of Tree via inheritance, a whole 
different discussion.



receiving the features and also - if so - holding unique values created
in there __init__ generator method - self.height, self.color and so
forth uniquely each.

But do both share the same function memory space from the class Tree?


Yes. each instance holds a reference to its class. The class holds the 
function definitions. That's why you need a self parameter, it tells the 
class method definition which instance is being operated upon.




I am currently trying also to get my head wrapped around OOP in general,
but not 100% sure so that derived instances use the same functions (also
memory wise speaking) - or are there several definitions of grow ?


instances all refer to their class which holds the methods for the class.

Where inheritance is concerned the class then holds a further reference 
to its parent class and Python looks for the earliest method definition 
as it traverses that class hierarchy. In other words if the object class 
doesn't have a method definition to match the message name then it looks 
in the superclass's definition for such a method, and if not there it 
looks in the superclass's superclass and so on until it finds a match. 
It is this search that makes methods different to simple functions.




The confusion came somehow when reading about classmethods and
staticmethods and patterns like Singleton, monostate, borg...
from which I understand only ensure that the self.height properties
are shared across multiple instances of a given class?


Not quite. Class attributes are common across *all* instances of the 
class. Class methods are, like instance methods, stored in the class but 
do not need an instance to exist to call them. In fact class methods can 
be used as factories to create instances. This is a common pattern 
where you want a way to recover stored classes from a database or file 
or over a network connection. For example:



foo = MYClass()   # create a brand new instance in memory
id = foo.store(DB)  # save it in database
del(foo)   # get rid of the object in memory
foo2 =- MYClass.restore(db, id)#  new instance loaded from DB.
bar = MYClass.load(someSocket) #instance read from network port

store() is an instance method that stores the instance data in a 
database. restore() is a class method that resurrects that instance by 
loading it from the database


load() is a class method that reads the data on a network port and 
interprets it as instance data and returns a new instance with those 
values..



 From what I tried out using id() and generating functions in a loop -
the id(class.function) provided the same result when printed out,


Yes, because they are shared.

But note that this is all implementation detail, there are other OOP 
languages that do things differently. Python's approach is the most 
common but not guaranteed. In fact I'm not even sure if it's guaranteed 
across different Python implementations!


--
Alan G
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


[Tutor] Working with output of a subprocess

2013-01-11 Thread 3n2 Solutions
Hello,

Need some help with working with a text file.
Is it possible to get the values associated with each of the parameter in
the below text file format? For example:

1. How can I check what the Min and Max values are?
2. How to check the second column value associated with epoch2?

Your help is greatly appreciated. I'm using Python 2.7 on Windows7.



Examining file: 5521W231.txt

Duration :  0h : 59m
First meas : week   :  86 :   1721
Last  meas : week   :  89 :   1721

Min val   : 15
Max val : 18
3D :   3600  100.0%

summary Total  MissedRate
epoch1:1378   0   0\1000
epoch2:2154   1   0\1000


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


Re: [Tutor] Books for Learning Python

2013-01-11 Thread ALAN GAULD


 I did a lot of programming in Fortran 77 while working on my Ph.D. in 
 engineering mechanics

That's OK, it's not permanent damage. :-)

 (1) Will Python allow me to create applications that provide a simple GUI 
 interface to something like an integrator for ODEs? 

No idea what an ODE is but yes Python can do simple graphics/GUIs. The 
Tkinter GUI library and friends are part of the standard library. Other tookits
exist such as wxPython, pyGTK etc.

 Does it have graphics libraries that allow one to animate the motion of 
 simple 
 objects (e.g., spheres, ellipsoids, parallelepipeds, etc.) based on the 
 results of 
 numerical simulations?

Yes, you can use things like gnuplot for grpahs/chartys or more dynamic you 
can use pyGame to define your own sprites and manoevre them around the screen.
You can also access libraries such as Scipy and R for heavyweight number 
crunching.

Start with the official tutorial, supplement with some of themore basic for 
new concepts like OOP (mine if you like! :-). Once confident with vanila 
python 
look at specialist tutorials for TKinter, PyGame, Scipy, R etc.

Python is well suited to your needs, obnce you have the foundation in place 
(and that should take only 2 or 3 days effort to polish up the rusty bits) the 
new stuff can be learned as needed.

HTH

Alan g.

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


Re: [Tutor] Books for Learning Python

2013-01-11 Thread Francois Dion
On Fri, Jan 11, 2013 at 3:14 PM, Gary L. Gray g...@psu.edu wrote:
 On Jan 11, 2013, at 1:39 PM, Alan Gauld alan.ga...@btinternet.com wrote:
 (1) Will Python allow me to create applications that provide a simple GUI 
 interface to something like an integrator for ODEs? Does it have graphics 
 libraries that allow one to animate the motion of simple objects (e.g., 
 spheres, ellipsoids, parallelepipeds, etc.) based on the results of numerical 
 simulations?

Ordinary Differential Equations, I'm assuming.

Python has tons of math / sci libraries. Matplotlib, scipy, pylab etc.
Under Windows, get Python(X,Y) and you will get an IDE, Python, and
all the modules I've mentionned. A quick google, for those coming from
a matlab background:
http://www.christopheralbert.net/2011/03/equivalent-ode-integrators-in-matlab.html

What OS will you be using?

Francois

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


Re: [Tutor] Working with output of a subprocess

2013-01-11 Thread Dave Angel
On 01/11/2013 05:29 PM, 3n2 Solutions wrote:
 Hello,

 Need some help with working with a text file.
 Is it possible to get the values associated with each of the parameter in
 the below text file format? For example:

There are no intrinsic parameters and values in a text file.  it's free
form characters.  On the other hand, if the format is a standard one,
there may be a library that parses it for you.  For example, configparser.

On the other hand, if you have a spec, you can write a parser.  Your
example doesn't look like any standard, so we'd be guessing.


 1. How can I check what the Min and Max values are?

Assuming that the value of Min is 

 val   : 15

then you could get it by scanning through the file looking for the line that 
begins with the string Min 

   ...
   if line.startswith(Min ):
 result = line[4:]

 2. How to check the second column value associated with epoch2?

Use the same approach to find the value of epoch2:  Then split based on
the colon, and then on whitespace.
parts = line.split(:)
subparts = parts[1].split()


 Your help is greatly appreciated. I'm using Python 2.7 on Windows7.



 Examining file: 5521W231.txt

 Duration :  0h : 59m
 First meas : week   :  86 :   1721
 Last  meas : week   :  89 :   1721

 Min val   : 15
 Max val : 18
 3D :   3600  100.0%

 summary Total  MissedRate
 epoch1:1378   0   0\1000
 epoch2:2154   1   0\1000


 Thanks,
 Tim





-- 

DaveA

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


Re: [Tutor] pexports python27.dll python27.def (pygraphviz 1.1 package )

2013-01-11 Thread somnath chakrabarti
Actually the problem was the access permission for the destination folder.
I changed to my account-specific path and it worked.

Thanks
Somnath


On Fri, Jan 11, 2013 at 7:08 PM, Prasad, Ramit ramit.pra...@jpmorgan.comwrote:

 somnath chakrabarti wrote:
   I have mingw and python 2.7 in a Windows 7 box and trying to install
 PyGraphViz-1.1 using the following CLI
  utility
 
  python setup.py install build --compiler=mingw32
  However, it ends up compiling error with undefined references as follows:
 
  ...
 
 build\temp.win-amd64-2.7\Release\pygraphviz\graphviz_wrap.o:graphviz_wrap.c:(.text+0x5a73):
 undefined reference
  to '_imp__PyInt_FromLong'
  collect2: ld returned 1 exit status
  error: command 'gcc' failed with exit status 1
  I checked in the link (see here) which suggests exporting definitions
 from C:\Windows\System32\python27.dll to
  python27.def and then using dlltool to create libpython27.a and finally
 placing the libpython.a file under
  C:\Python27\libs of the Python distribution for MinGW to interpret
 Python libraries.
  I have the C:\MinGW\bin added to my system path and been trying to do
 the export using
 
  pexports C:\Windows\System32\python27.dll 
 C:\Windows\System32\python27.def
  but each time I am receiving Access is Denied Message.
  I did some searching and found that MS Visual Studio users can avail
 another export option with DUMPBIN but
  since I don't have MSVS installed, I would like to get some alternative
 to get rid of the problem and need to
  use the PyGraphViz-1.1 package. Any suggestions will be very helpful
 
  Somnath Chakrabarti
  MS Student
  CSEE Department
  University of Maryland Baltimore County
  1000 Hilltop Circle
  Baltimore, MD 21250
  M: 443-812-5609
  mail: chak...@umbc.edu
  gmail: chakrabarti.somn...@gmail.com

 Do you *need* to build PygraphViz? Seems like you can download binaries or
 just install from pypi.
 See: http://networkx.lanl.gov/pygraphviz/install.html

 Not sure you will have great luck here, as this list is about learning
 Python.
 You might have better luck in the Google Group [1], on the developer's
 site[2],
 or as a last resort the main Python mailing list.


 [1] http://groups.google.com/group/pygraphviz-discuss
 [2] http://networkx.lanl.gov/trac/wiki/PyGraphviz


 This email is confidential and subject to important disclaimers and
 conditions including on offers for the purchase or sale of
 securities, accuracy and completeness of information, viruses,
 confidentiality, legal privilege, and legal entity disclaimers,
 available at http://www.jpmorgan.com/pages/disclosures/email.




-- 

Somnath Chakrabarti
MS Student
CSEE Department
University of Maryland Baltimore County
1000 Hilltop Circle
Baltimore, MD 21250
M: 443-812-5609
mail: chak...@umbc.edu
gmail: chakrabarti.somn...@gmail.com
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] garbage collection/class question

2013-01-11 Thread Mitya Sirenef

On 01/11/2013 02:41 PM, Jan Riechers wrote:

On 10.01.2013 19:50, Mitya  Sirenef wrote:

 On 01/10/2013 09:06 AM, richard kappler wrote:

 class Tree(object):
 height = 0

 def grow(self):
 self.height += 1

 You may have a dozen of related functions and you can logically group
 them together by making them methods of a class, making it easier to
 think about and work on the logic of your program.




 Actually one question about those dozens of related instances 
generated by:

 greenwoodTree = Tree()
 oakTree = Tree()
 


I just want to clarify, I meant you may have dozens of related functions 
and then
move them all into a single class (i.e. I wasn't talking about 
instances, although you

can of course have dozens of instances, too).

So, let's say, you have:

def f1(): ..
def f2(): ..
def f3(): ..
 

And it occurs to you, since they're all related, it's good to have them 
all in the

same class:

class F(object):
 def f1(self): ..
 def f2(self): ..
 def f3(self): ..


There are already really good answers so I'll just add a few notes below...



 Both, greenwoodTree and oakTree, are derived from Tree class, thus 
receiving the features and also - if so - holding unique values created 
in there __init__ generator method - self.height, self.color and so 
forth uniquely each.


 But do both share the same function memory space from the class Tree?

 I am currently trying also to get my head wrapped around OOP in 
general, but not 100% sure so that derived instances use the same 
functions (also memory wise speaking) - or are there several definitions 
of grow ?



Functions are the same, (called methods), but the self object is
different for each instance, and represents the instance. Consider that
since the logic performed by the method is the same (if it wasn't, you'd
define it as a separate method, right?), there would be no reason to
make a separate method for each instance. As you know from working with
functions, the same function may create different output if its
arguments are different (from another call), but if the arguments are
the same, it will create the same output (I'm ignoring things like
random module).

Well, that's why the first argument for a method is 'self', which is
different for each instance.



 The confusion came somehow when reading about classmethods and 
staticmethods and patterns like Singleton, monostate, borg...
 from which I understand only ensure that the self.height properties 
are shared across multiple instances of a given class?



The core idea of having a class and one or more instances is very
versatile and powerful, all of the other concepts are much less needed
especially as you're starting out. For example, you can have a class
tree and methods and a bunch of tree instances; a classmethod would
allow you to perform an action without making an instance first, but
it's not like it's hard to make an instance -- it's just that in some
cases it's clearer and more straightforward to use a classmethod, like
Alan pointed out, but if you happen to forget about classmethods, you
could easily get by without them. The same applies to Borg pattern, etc.

Learn to be comfortable with classes and instances and you'll be able to
make a wide range of programs.



 From what I tried out using id() and generating functions in a loop - 
the id(class.function) provided the same result when printed out, 
according to that:

 http://stackoverflow.com/questions/121396/accessing-object-memory-address

 So I assume the functions are shared across thus one decleration has 
been made in Tree class and all siblings are using that one?



They are usually called methods if they belong to a class, and yes
they're shared.

HTH, - mitya



--
Lark's Tongue Guide to Python: http://lightbird.net/larks/

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


Re: [Tutor] writing effective unittests

2013-01-11 Thread Prasad, Ramit
Japhy Bartlett wrote:
 TDD is a good principle but usually seems a little too pedantic for real 
 world programming.  Where tests (in my
 experience) get really useful is in making sure that a new change hasn't 
 unexpectedly broken something already
 written.
 

I would argue that TDD is a pedantic for non-real world (i.e. academic) 
programming
and not at all for real world programming. In the academic world, manually 
testing
is fine assuming sufficient manual testing (unless the professor is testing your
testing). It was rare for me to use a project more than once or edit it enough
that to find automated testing (TDD/unit) useful. Now group projects are a 
completely different story.  Of course, this depends on your level of degree 
and subject matter.

In the working world, testing is much more essential
because money (yours or your company's) relies on the code being correct.


~Ramit


This email is confidential and subject to important disclaimers and
conditions including on offers for the purchase or sale of
securities, accuracy and completeness of information, viruses,
confidentiality, legal privilege, and legal entity disclaimers,
available at http://www.jpmorgan.com/pages/disclosures/email.  
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] garbage collection/class question

2013-01-11 Thread Mitya Sirenef

On 01/11/2013 04:32 PM, Dave Angel wrote:

On 01/11/2013 02:41 PM, Jan  Riechers wrote:

 On 10.01.2013 19:50, Mitya Sirenef wrote:
 On 01/10/2013 09:06 AM, richard kappler wrote:

 class Tree(object):
 height = 0

 def grow(self):
 self.height += 1

 You may have a dozen of related functions and you can logically group
 them together by making them methods of a class, making it easier to
 think about and work on the logic of your program.




 Actually one question about those dozens of related instances
 generated by:
 greenwoodTree = Tree()
 oakTree = Tree()
 

 Both, greenwoodTree and oakTree, are derived from Tree class,

 It's important that we use correct, or at least close terminology. A
 derived class is VERY different from an instance. greenWoodTree and
 oakTree are bound to different instances of Tree.

 thus receiving the features and also - if so - holding unique values
 created in there __init__ generator method

 __init__ is not a generator. it's simply a method. A method is a
 function that's defined inside a class

 - self.height, self.color and so forth uniquely each.

 We have to be careful here. Such data can be attributes of an instance,
 or they can be attributes of a class. Strangely enough, this example
 has a self.height and tree.height that are both called height, but
 technically distinct values. I think it's best if you avoid such
 things, and use unique names till you've got the fundamentals straight.


 But do both share the same function memory space from the class Tree?


 I wouldn't use the term function memory space, but I'll say this much.
 Unless you do something tricky, there is only one method Tree.grow, and
 all instances share that same method. No duplicated memory at all.

 I am currently trying also to get my head wrapped around OOP in
 general, but not 100% sure so that derived instances use the same
 functions (also memory wise speaking) - or are there several
 definitions of grow ?

 Not yet. Creating instances don't duplicate any methods. You'd have to
 do something explicit, and advanced.


 The confusion came somehow when reading about classmethods and
 staticmethods and patterns like Singleton, monostate, borg...
 from which I understand only ensure that the self.height properties
 are shared across multiple instances of a given class?


 I'd consider all of those as advanced techniques, and a complete
 confusion at your present stage. classmethods and staticmethods affect
 the parameters that a method gets, not whether data properties belong to
 the class or to the method.

 From what I tried out using id() and generating functions in a loop -
 the id(class.function) provided the same result when printed out,
 according to that:
 
http://stackoverflow.com/questions/121396/accessing-object-memory-address


 So I assume the functions are shared across thus one decleration has
 been made in Tree class and all siblings are using that one?


 Without showing the code in this loop, I can't comment on what you
 observed. Don't have any idea what you mean by a sibling. The only
 meaning I can think of is that two classes each derived from a common
 base class can be considered siblings. But you don't do any deriving in
 this email.



I think it's very intuitive (at least, it was to me when I was
learning), to view it as a common starting point for all instances. In
this example it makes sense that all trees (or a general idea of a tree)
starts with a 0 height, and then each particular tree ends up with a
different height after a while.

 -m



--
Lark's Tongue Guide to Python: http://lightbird.net/larks/

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


Re: [Tutor] run perl script files and capture results

2013-01-11 Thread Prasad, Ramit
eryksun wrote:
[snip]
 1. Using a forward slash in paths is OK for DOS/Windows system calls
 (e.g. opening a file or setting the cwd of a new process), dating back
 to the file system calls in MS-DOS 2.0 (1983). Otherwise a backslash
 is usually required (e.g. shell commands and paths in commandline
 arguments, where forward slash is typically used for options). In this
 case use a raw string or os.path.join. For a raw string, note that a
 trailing backslash is not allowed, e.g. r'C:\Python27\'. Instead you
 could use r'C:\Python27' '\\', among other options:
 
 http://docs.python.org/2/faq/design.html#why-can-t-raw-strings-r-strings-end-with-a-backslash

Why not just use r'C:\Python27\\'? Might be too confusing for
a beginner to remember, I suppose.


~Ramit


This email is confidential and subject to important disclaimers and
conditions including on offers for the purchase or sale of
securities, accuracy and completeness of information, viruses,
confidentiality, legal privilege, and legal entity disclaimers,
available at http://www.jpmorgan.com/pages/disclosures/email.  
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] pexports python27.dll python27.def (pygraphviz 1.1 package )

2013-01-11 Thread Prasad, Ramit
somnath chakrabarti wrote:
  I have mingw and python 2.7 in a Windows 7 box and trying to install 
 PyGraphViz-1.1 using the following CLI
 utility
 
 python setup.py install build --compiler=mingw32
 However, it ends up compiling error with undefined references as follows:
 
 ...
 build\temp.win-amd64-2.7\Release\pygraphviz\graphviz_wrap.o:graphviz_wrap.c:(.text+0x5a73):
  undefined reference
 to '_imp__PyInt_FromLong'
 collect2: ld returned 1 exit status
 error: command 'gcc' failed with exit status 1
 I checked in the link (see here) which suggests exporting definitions from 
 C:\Windows\System32\python27.dll to
 python27.def and then using dlltool to create libpython27.a and finally 
 placing the libpython.a file under
 C:\Python27\libs of the Python distribution for MinGW to interpret Python 
 libraries.
 I have the C:\MinGW\bin added to my system path and been trying to do the 
 export using
 
 pexports C:\Windows\System32\python27.dll  C:\Windows\System32\python27.def
 but each time I am receiving Access is Denied Message.
 I did some searching and found that MS Visual Studio users can avail another 
 export option with DUMPBIN but
 since I don't have MSVS installed, I would like to get some alternative to 
 get rid of the problem and need to
 use the PyGraphViz-1.1 package. Any suggestions will be very helpful
 
 Somnath Chakrabarti
 MS Student
 CSEE Department
 University of Maryland Baltimore County
 1000 Hilltop Circle
 Baltimore, MD 21250
 M: 443-812-5609
 mail: chak...@umbc.edu
 gmail: chakrabarti.somn...@gmail.com

Do you *need* to build PygraphViz? Seems like you can download binaries or just 
install from pypi.
See: http://networkx.lanl.gov/pygraphviz/install.html

Not sure you will have great luck here, as this list is about learning Python. 
You might have better luck in the Google Group [1], on the developer's site[2], 
or as a last resort the main Python mailing list.


[1] http://groups.google.com/group/pygraphviz-discuss
[2] http://networkx.lanl.gov/trac/wiki/PyGraphviz


This email is confidential and subject to important disclaimers and
conditions including on offers for the purchase or sale of
securities, accuracy and completeness of information, viruses,
confidentiality, legal privilege, and legal entity disclaimers,
available at http://www.jpmorgan.com/pages/disclosures/email.  
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] pexports python27.dll python27.def (pygraphviz 1.1 package )

2013-01-11 Thread Prasad, Ramit
somnath chakrabarti wrote:
 Actually I embedded a link to the refer site from where I have been following 
 the procedure. I am new to Python
 too and have been following the book Mining the Social Web by Matthew 
 Russell and thought Tutor mailing list
 would be the right place to post the question. Anyways will try to post in 
 text and more python generic
 questions next time. Thanks for pointing out though!
 :)
 -Somnath

And try and post in-line or after quoting relevant text (and trimming 
irrelevant text). Thanks!


~Ramit


This email is confidential and subject to important disclaimers and
conditions including on offers for the purchase or sale of
securities, accuracy and completeness of information, viruses,
confidentiality, legal privilege, and legal entity disclaimers,
available at http://www.jpmorgan.com/pages/disclosures/email.  
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Binary/Decimal convertor

2013-01-11 Thread Alan Gauld

On 11/01/13 21:51, Ghadir Ghasemi wrote:

Hi, I made a program called binary/denary convertor.



Can anyone tell me about how I could stop the user entering a binary

 number with more than 8 numbers or 8 bit

Why would you want to? Your code can handle much bigger binary numbers, 
why limit the user to 8 bits?



Here is the code. I started off by entering 'len' function.



num1 = int(input('please enter the first 8 bit binary number: '),2)


Here hyou read the number as a string and already convert it to a real 
number in Python. So the conversion from  binary has already happened 
regardless of how long the string was.




if len(num1)  8:
 print(please enter an 8 bit binary number)


You now try to see how long the number is, but numvers don;t have a length.
So to do what you claim you want you need to do the len() check before 
you do the inty() conversion.

Something like:

 num1 = input('please enter the first 8 bit binary number: ')
 if len(num1)  8:
  print(please enter an 8 bit binary number)
 else:
num = int(num,2)

Then put that in while a loop that repeats until the length is =8


return int(num1,2)


And here you return which would terminate your function except you don't 
have a function so it will give a syntax error. And trying to convert a 
num as a binary won't work because its already stored internally as a 
binary number. This only works if you still have the string as described 
above.



num2 = int(input('please enter the second 8 bit binary number: '),2)


And this doesn't do any len() checks


result = add_binary_numbers(num1, num2)
print('the result is', bin(result)[2:])


I'd suggest that you make your add_binary_numbers() function return
the binary string. Otherwise it doesn't add any value over the
standard plus sign...


--
Alan G
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] Working with output of a subprocess

2013-01-11 Thread Alan Gauld

On 11/01/13 22:29, 3n2 Solutions wrote:


Need some help with working with a text file.
Is it possible to get the values associated with each of the parameter
in the below text file format? For example:


Yes, but it's non trivial. You need to parse the text.


1. How can I check what the Min and Max values are?
2. How to check the second column value associated with epoch2?


In both cases you can extract the line using the startswith() string 
method. You can then use a combination of  split() and strip(), lstrip() 
and rstrip() and slicing to extract the substrings you need.

Then convert the strings to numbers as necessary.

I'd probably write value extraction functions for each required 
parameter, given a line of input. Then iterate over the text and all the 
appropriate function based on the startswith() result:


for line in open('myfile.txt'):
if line.startswith('Min'): min = getSingleNumber(line)
elif line startswith('Max'): max = getSingleNumber(line)
elif 
elif line.startswith('epoch2'): epoch2 = getCol2(line)



HTH
--
Alan G
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


[Tutor] a Pygtk question sort of

2013-01-11 Thread richard kappler
Before anybody jumps me about this question being inappropriate for this
list, yes, I know it probably is BUT, the two places where it might be
appropriate are down pretty hard, so this is my only option (I think).

The question is in regards to pygtk I think, and pocketsphinx obliquely.
Appended below is code from the CMU Sphinx website that I wish to ever so
slightly modify, but am not quite sure how to proceed. This code creates a
gui with a button that stops and starts the pocketsphinx speech recognition
engine. When the button reads speak and you push it, the button goes
blank iirc, pocketsphinx listens, performs speech recognition and sends the
resulting text to the gui, changing the button text back to speak and
putting the pocketsphinx engine ostensibly (though not in actuality) on
pause.

I understand how the below code does all of this, including how
pocketsphinx works. Here's the issue: I want to use this code or code like
it (pocketsphinx can be imported and run directly in python but apparently
only to decode wav files, not as a real-time decoder unless you run it
through gst as shown in the appended code as I understand it) in my bot
program, so I don't need the gui, button or any of that. I need
pocketsphinx to work exactly as below, but send the text output back to the
main program or to a different program (chatbot) instead of the gui. Make
sense? I've been pouring over this code off and on for months as I've been
learning, and it's not quite as simple as dump the gui method and the
button. The problem is the button controls the vader (determines begin and
end of utterances) as well. Detailed explanation here:
http://cmusphinx.sourceforge.net/wiki/gstreamer

So can anyone give me some guidance here or point me towards a place to
discuss this? The forums at Python.org are under construction, the
CMUSphinx forums at Sourceforge are down (404) so I'm not quite sure where
to go for help.

regards, Richard

#!/usr/bin/env python

# Copyright (c) 2008 Carnegie Mellon University.
#
# You may modify and redistribute this file under the same terms as
# the CMU Sphinx system.  See
# http://cmusphinx.sourceforge.net/html/LICENSE for more information.

import pygtk
pygtk.require('2.0')
import gtk

import gobject
import pygst
pygst.require('0.10')
gobject.threads_init()
import gst

class DemoApp(object):
GStreamer/PocketSphinx Demo Application
def __init__(self):
Initialize a DemoApp object
self.init_gui()
self.init_gst()

def init_gui(self):
Initialize the GUI components
self.window = gtk.Window()
self.window.connect(delete-event, gtk.main_quit)
self.window.set_default_size(400,200)
self.window.set_border_width(10)
vbox = gtk.VBox()
self.textbuf = gtk.TextBuffer()
self.text = gtk.TextView(self.textbuf)
self.text.set_wrap_mode(gtk.WRAP_WORD)
vbox.pack_start(self.text)
self.button = gtk.ToggleButton(Speak)
self.button.connect('clicked', self.button_clicked)
vbox.pack_start(self.button, False, False, 5)
self.window.add(vbox)
self.window.show_all()

def init_gst(self):
Initialize the speech components
self.pipeline = gst.parse_launch('gconfaudiosrc ! audioconvert
! audioresample '
 + '! vader name=vad
auto-threshold=true '
 + '! pocketsphinx name=asr ! fakesink')
asr = self.pipeline.get_by_name('asr')
asr.connect('partial_result', self.asr_partial_result)
asr.connect('result', self.asr_result)
asr.set_property('configured', True)

bus = self.pipeline.get_bus()
bus.add_signal_watch()
bus.connect('message::application', self.application_message)

self.pipeline.set_state(gst.STATE_PAUSED)

def asr_partial_result(self, asr, text, uttid):
Forward partial result signals on the bus to the main thread.
struct = gst.Structure('partial_result')
struct.set_value('hyp', text)
struct.set_value('uttid', uttid)
asr.post_message(gst.message_new_application(asr, struct))

def asr_result(self, asr, text, uttid):
Forward result signals on the bus to the main thread.
struct = gst.Structure('result')
struct.set_value('hyp', text)
struct.set_value('uttid', uttid)
asr.post_message(gst.message_new_application(asr, struct))

def application_message(self, bus, msg):
Receive application messages from the bus.
msgtype = msg.structure.get_name()
if msgtype == 'partial_result':
self.partial_result(msg.structure['hyp'], msg.structure['uttid'])
elif msgtype == 'result':
self.final_result(msg.structure['hyp'], msg.structure['uttid'])
self.pipeline.set_state(gst.STATE_PAUSED)
self.button.set_active(False)

def partial_result(self, hyp, uttid):

Re: [Tutor] a Pygtk question sort of

2013-01-11 Thread Alan Gauld

On 12/01/13 01:18, richard kappler wrote:

Before anybody jumps me about this question being inappropriate for this
list, yes, I know it probably is BUT, the two places where it might be
appropriate are down pretty hard, so this is my only option (I think).


I'm not sure what you mean by down pretty hard but this definitely 
looks like a question for a pocketsphinx forum...



I want to use this code or code
like it in my bot program, so I don't need the gui, button or any of that. I
need pocketsphinx to work exactly as below, but send the text output
back to the main program or to a different program (chatbot) instead of
the gui. Make sense?


Sadly no.
Can you explain exactly how you intend running pocketspinx?
What is the main program? A Python script? Or some other external 
program? Where does chatbot fit in? Is it just an arbitrary example or 
is there some specific symbiosis going on?



gui method and the button. The problem is the button controls the vader
(determines begin and end of utterances) as well. Detailed explanation


Nope, you lost me again...


So can anyone give me some guidance here or point me towards a place to
discuss this? The forums at Python.org are under construction, the
CMUSphinx forums at Sourceforge are down (404) so I'm not quite sure
where to go for help.


Googling pocketsphinx python threw up at least half a dozen useful 
looking links


You could also try the main python mailing list (or its mirror on
the comp.lang.python newsgroup)

--
Alan G
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] run perl script files and capture results

2013-01-11 Thread Dave Angel
On 01/11/2013 07:33 PM, Prasad, Ramit wrote:
 [snip]
 Why not just use r'C:\Python27\\'? Might be too confusing for
 a beginner to remember, I suppose.



Because that'd have two trailing backslashes.  (in Python 2.7 anyway)


-- 

DaveA

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


[Tutor] Is a link broken?

2013-01-11 Thread Ed Owens
I'm still working through Chun's Core Python Applications.  I got the 
web crawler (Example 9-2) working after I found a ':' typing error.  Now 
I'm trying to convert that to a program that checks for broken links.  
This is not in the book.  The problem I'm having now is knowing whether 
a link is working.


I've written an example that I hope illustrates my problem:

#!/usr/bin/env python

import urllib2

sites = ('http://www.catb.org', 'http://ons-sa.org', 'www.notasite.org')
for site in sites:
try:
page = urllib2.urlopen(site)
print page.geturl(), didn't return error on open
print 'Reported server is', page.info()['Server']
except:
print site, 'generated an error on open'
try:
page.close()
print site, 'successfully closed'
except:
print site, 'generated error on close'


Site 1 is alive, the other two dead.  Yet this code only returns an 
error on site three.  Notice that I checked for a redirection (I think) 
of the site if it opened, and that didn't help with site two.


Is there an unambiguous way to determine if a link has died -- knowing 
nothing about the link in advance?


Ed



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