[Tutor] question about looping.

2006-10-06 Thread Doug Potter
Hi,

I at trying to create a bunch of text files in a single directory on a 
Linux system,
something like this.

import os

routers = ['adnc-6321', 'adnp-2341', 'adnw-2632']

for i in routers:
os.system('/bin/touch' %s) % i

of course this dosn't work.

Is there a simple way to get this done?

Thanks for your time.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Luke, thanks a lot , here is the perfect code (as per ur suggestion)

2006-10-06 Thread Asrarahmed Kadri
Thanks for the detailed explanation. I read it and understood a bit. Rest in the leisure time.
 
Enjoy the recipes..
Regards,
Asrar 
On 10/5/06, Kent Johnson <[EMAIL PROTECTED]> wrote:
Asrarahmed Kadri wrote:> What is this??? I cannot understand a single character.. Explain this in
> length.>> *list1 = [ [ locals()["_[1]"][i-1][j-1]+locals()["_[1]"][i-1][j] if> (j !=> 0 and j != i) else 1 for j in range(i+1) ] for i in> range(num_of_lines) ]
OK, I guess I asked for that. Remember, I did say this was hideous, Iwould never use this for anything other than a newsgroup posting.Here is your original code, more or less:list1 = []for i in range(5):
flag = 0tmp = []for j in range(i+1):if flag == 0 or j == i:tmp.append(1)flag = 1else:tmp.append(list1[i-1][j-1]+list1[i-1][j])
list1.append(tmp)First let's get rid of flag, it isn't needed:list1 = []for i in range(5):tmp = []for j in range(i+1):if j == 0 or j == i:tmp.append(1)
else:tmp.append(list1[i-1][j-1]+list1[i-1][j])list1.append(tmp)Now replace the inner if/else with a conditional _expression_ inside thecall to append(). A conditional _expression_ has the form (a if b else c)
where b is the condition being tested and a and c are the two values.The if/else becomes this monster:tmp.append(list1[i-1][j-1]+list1[i-1][j] if (j!=0 and j!=i) else 1)I inverted the condition so I could put the more common case first. Now
the whole program looks like this:list1 = []for i in range(5):tmp = []for j in range(i+1):tmp.append(list1[i-1][j-1]+list1[i-1][j] if (j!=0 and j!=i) else 1)list1.append
(tmp)The inner loop is now ready to be replaced with a list comprehension. Ingeneral, a loop of the formtmp = []for i in x:  tmp.append(f(i))can be replaced with the equivalent list comprehension
tmp = [ f(i) for i in x ]With this change the program is down to this:list1 = []for i in range(5):tmp = [ list1[i-1][j-1]+list1[i-1][j] if (j!=0 and j!=i) else 1 forj in range(i+1) ]
list1.append(tmp)This is again in the form of a loop that can be replaced by a listcomprehension, this time to create list1. The problem is that the_expression_ in the list comprehension has to refer to the list being
built, and this list is not normally available because the name has notyet been bound. This is where the cookbook hack comes in play - within alist comprehension, the list being built can be referenced aslocals()["_[1]"]. Refer to the cookbook recipe for details.
So within the list comp,list1[i-1][j-1] becomes locals()["_[1]"][i-1][j-1] andlist1[i-1][j] becomes locals()["_[1]"][i-1][j].This brings us to the final form:list1 = [ [ locals()["_[1]"][i-1][j-1]+locals()["_[1]"][i-1][j] if (j!=0
and j!=i) else 1 for j in range(i+1) ] for i in range(5) ]or, with slightly nicer formatting:list1 = [[ locals()["_[1]"][i-1][j-1]+locals()["_[1]"][i-1][j] if (j!=0 andj!=i) else 1
for j in range(i+1)] for i in range(5)]Kent___Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor-- To HIM you shall return. 
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] question about looping.

2006-10-06 Thread Kent Johnson
Doug Potter wrote:
> Hi,
> 
> I at trying to create a bunch of text files in a single directory on a 
> Linux system,
> something like this.
> 
> import os
> 
> routers = ['adnc-6321', 'adnp-2341', 'adnw-2632']
> 
> for i in routers:
> os.system('/bin/touch' %s) % i

I think you're close, just a little out of order. Think about it this way:
- first you need to create a string containing the command, using the 
string formatting operations.
'/bin/touch %s' % i
will do that. Note the %s is part of the string, and the % i is part of 
the formatting expression.

- next you pass the formatted string to os.system(). So the whole 
formatting expression has to go inside the parentheses - the value of 
the expression is passed to os.system():
os.system('/bin/touch %s' % i)

You could also do this without calling out to the system - just open a 
file for writing and close it again:
open(i, 'w').close()

Kent

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Trying tio emulate "diff" command of UNIX - please help

2006-10-06 Thread Asrarahmed Kadri

# This program emulates the diff command of UNIX
import sysfrom stringCompare import stringcmp   # this is a module which has stringcmp function that compares two strings
fname1 = raw_input("Enter a file name to be read:\t")
fname2 = raw_input("Enter a file name to be read:\t")
 
fd1 = open(fname1,"r")fd2 = open(fname2,"r")
done = 0line_counter = 0
while not done:    aLine1 = fd1.readline()    aLine2 = fd2.readline()        if (aLine1 == "" or aLine2 == ""):  # test whether you have reached the end of file    done = 1
        else:        line_counter += 1 # get the line number    string1 = aLine1.split() # split the line into a list containing words    string2 = aLine2.split
()        len1 = len(string1)    len2 = len(string2)    if len1 > len2:    t = len1    else:    t = len2    i = 0    while (i < t):    cmp_res = stringcmp(string1[i],string2[i])
    if cmp_res != 0:    column = i    done = 1    print "The difference is lies in the ", line_counter ,"line and column ", column
 
 
 
Can someone help me with what is wrong in this code; when I am running it gets stuck.
 
thanks in anticipation.
Regards,
Asrar
 
 
 
 
-- To HIM you shall return. 
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Trying tio emulate "diff" command of UNIX - please help

2006-10-06 Thread Senthil_OR



Hi, 
 
Your program does not emulate the diff command of 
Unix.
Please do a diff in unix and experience 
yourselves.
 
Where is cmp_res = stringcmp(string1[i],string2[i]) 
stringcmp() function 
written?
 
Moreover, if you Python Documentation install 
(or python.org accessible) search for difflib and Differ Example.
That should 
give you a good start.
 
Thanks,
-- 
Senthil
 


From: [EMAIL PROTECTED] 
[mailto:[EMAIL PROTECTED] On Behalf Of Asrarahmed 
KadriSent: Friday, October 06, 2006 6:09 PMTo: 
tutor@python.orgSubject: [Tutor] Trying tio emulate "diff" command of 
UNIX - please help


# This program emulates the diff command of UNIX
import sysfrom stringCompare import stringcmp   # this is a 
module which has stringcmp function that compares two strings
fname1 = raw_input("Enter a file name to be read:\t")
fname2 = raw_input("Enter a file name to be read:\t")
 
fd1 = open(fname1,"r")fd2 = open(fname2,"r")
done = 0line_counter = 0
while not done:    aLine1 = 
fd1.readline()    aLine2 = 
fd2.readline()        if (aLine1 == "" or 
aLine2 == ""):  # test whether you have reached the end of 
file    done = 1 
        
else:    
    line_counter += 
1 # 
get the line number    string1 = 
aLine1.split() # split the line 
into a list containing words    
string2 = aLine2.split ()    
    len1 = len(string1)    len2 = 
len(string2)    if len1 > 
len2:    t = 
len1    else:    t 
= len2    i = 0    while (i < 
t):    cmp_res = 
stringcmp(string1[i],string2[i])     
if cmp_res != 
0:    column 
= i    done = 
1    
print "The difference is lies in the ", line_counter ,"line and column ", 
column
 
 
 
Can someone help me with what is wrong in this code; when I am running it 
gets stuck.
 
thanks in anticipation.
Regards,
Asrar
 
 
 
 
-- To HIM you shall return. 
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] question about looping.

2006-10-06 Thread Carlos Hanson
Doug Potter wrote:
> Hi,
> 
> I at trying to create a bunch of text files in a single directory on a 
> Linux system,
> something like this.
> 
> import os
> 
> routers = ['adnc-6321', 'adnp-2341', 'adnw-2632']
> 
> for i in routers:
> os.system('/bin/touch' %s) % i
> 
> of course this dosn't work.

try using the following:

for i in routers:
os.system('/bin/touch %s' % i)

> Is there a simple way to get this done?

You can also use the builtin file object:

for i in routers:
f = file(i, 'w')
f.close()

> Thanks for your time.
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor

-- 
Carlos Hanson
Web Specialist
Tigard-Tualatin School District
503.431.4053
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Trying tio emulate "diff" command of UNIX - please help

2006-10-06 Thread Alan Gauld
Some general thoughts:

> import sys
> from stringCompare import stringcmp   # this is a module which has 
> stringcmp
>
> fname1 = raw_input("Enter a file name to be read:\t")
> fname2 = raw_input("Enter a file name to be read:\t")
>
> fd1 = open(fname1,"r")
> fd2 = open(fname2,"r")
>
>
> done = False

Use Boolean value instead of 1/0

> line_counter = 0
> while not done:
>aLine1 = fd1.readline()
>aLine2 = fd2.readline()
>
>if (aLine1 == "" or aLine2 == ""):  # test whether you have 
> reached the
> end of file
>done = 1

assign directly to done, using a boolean test:

done = not (aLine1 and aLine2)

and miss out the if/else test.

>line_counter += 1 # get the line number
>string1 = aLine1.split() # split the line into a
> list containing words
>string2 = aLine2.split()

Not sure why you are splitting the lines into words.
You call them columns but they are really words of
varying length. Why not just compare the lines as a whole?

  if aLine1 != aLine2:
 print "The difference lies in line", line_counter

Then you can find the first characters that differ:

 diff = [t1==t2 for t1,t2 in zip(line1,line2)].index(False)
 print "and start at character", diff

It's not exactly equivalent to your code of course but it seems to me
to be more accurate...

If you must use words, apply the spolit only when you know its needed:

 words1 = aLine1.split()
 words2 = aLine2.split()
 diff = [w1==w2 for w1,w2 in zip(words1,words2)].index(False)
 print "and start at word",diff

HTH,


-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld 


___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Trying tio emulate "diff" command of UNIX - please help

2006-10-06 Thread Asrarahmed Kadri
Thanks Alan, but can you please explain me what this line does:
diff = [t1==t2 for t1,t2 in zip(line1,line2)].index(False) 
 
On 10/6/06, Alan Gauld <[EMAIL PROTECTED]> wrote:
Some general thoughts:> import sys> from stringCompare import stringcmp   # this is a module which has
> stringcmp>> fname1 = raw_input("Enter a file name to be read:\t")> fname2 = raw_input("Enter a file name to be read:\t")>> fd1 = open(fname1,"r")
> fd2 = open(fname2,"r")>>> done = FalseUse Boolean value instead of 1/0> line_counter = 0> while not done:>aLine1 = fd1.readline()>aLine2 = 
fd2.readline()>>if (aLine1 == "" or aLine2 == ""):  # test whether you have> reached the> end of file>done = 1assign directly to done, using a boolean test:
done = not (aLine1 and aLine2)and miss out the if/else test.>line_counter += 1 # get the line number>string1 = aLine1.split() # split the line into a
> list containing words>string2 = aLine2.split()Not sure why you are splitting the lines into words.You call them columns but they are really words ofvarying length. Why not just compare the lines as a whole?
if aLine1 != aLine2:print "The difference lies in line", line_counterThen you can find the first characters that differ:diff = [t1==t2 for t1,t2 in zip(line1,line2)].index(False)
print "and start at character", diffIt's not exactly equivalent to your code of course but it seems to meto be more accurate...If you must use words, apply the spolit only when you know its needed:
words1 = aLine1.split()words2 = aLine2.split()diff = [w1==w2 for w1,w2 in zip(words1,words2)].index(False)print "and start at word",diffHTH,--Alan Gauld
Author of the Learn to Program web sitehttp://www.freenetpages.co.uk/hp/alan.gauld___Tutor maillist  -  
Tutor@python.orghttp://mail.python.org/mailman/listinfo/tutor-- To HIM you shall return. 
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Share variables between py scripts

2006-10-06 Thread Bennett, Joe
Can anyone direct me to some documentation on how to take variables
from one py script, execute and pass them to another script? Then I
need to get data back from the executed script? I've been searching
Google and I see information, but I am in need of some examples...
 
 
Thanks!
-Joehttp://www.damtravel.com

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Help: how to detect which key is pressed

2006-10-06 Thread Asrarahmed Kadri
 
 
I am writing a simple program and in that I want to add some sort of interactiveness.
I have designed a menu which gives the user an option to select one out of the following four keys: d, l, n or e.
Can any one tell me how to determine which key has been pressed by the user.
 
Thanks.
Regards,
 
Asrar-- To HIM you shall return. 
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Share variables between py scripts

2006-10-06 Thread Eric Walstad
Bennett, Joe wrote:
> Can anyone direct me to some documentation on how to take variables from 
> one py script, execute and pass them to another script? Then I need to 
> get data back from the executed script? I've been searching Google and I 
> see information, but I am in need of some examples...
>  
>  
> Thanks!
> 
> 
> -Joe

Hi Joe,

If possible, just "run" your script (B) from within the second script 
(A).  I'd rephrase that as "in module a, import and use variables, 
functions and/or classes from module b":

# Script B (script_b.py) #

my_b_variable = ''

def my_b_function(var):
 return "Hello World: %s" % var

class MyBClass:
 # an empty class
 pass

 End Script B #

# Script A (script_a.py) #
from script_b import my_b_variable, my_b_function, MyBClass

def my_a_function(var):
 my_a_variable = MyBClass()
 # or
 my_a_variable = my_b_variable
 # or
 my_a_variable = my_b_function(var)
 # etc
 return my_A_variable

if __name__ == '__main__':
 # this A script is being called from the command line
 # do whatever you like in here, like run a function:
 import sys
 command_line_arg = sys.argv[1]
 print my_A_function(command_line_arg)

 End Script A #

$ python script_a.py foo
Hello World: foo

I hope that wasn't too remedial for you and that it's helpful.  Search 
the docs for 'functions' and 'import' for more info.

Best,

Eric.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] when I create an instance of a class that inherits from Python dictionary, my data disappears

2006-10-06 Thread tpc247
hi all, I would like to create a class that specializes Python
dictionary.  I would like an instance of this class to store
objects representing html form data, and I would like to have an
instance of this Data_Set class be able to use the Python dictionary
method pop to remove objects as I see fit.  I defined the
following:

class Data_Set(dict):
    def __init__(self, dict_of_datum_objects, required=None):
    self.keys = dict_of_datum_objects.keys
    self.values = dict_of_datum_objects.values
    self.required = required

For some reason, whenever I create an instance of this class with data,
all I get is an empty dictionary.  As soon as I redefine my class
to no longer inherit from Python dictionary, then I get expected
behavior, but now I don't have benefit of Python dictionary methods
such as pop and has_key:

sdso = Data_Set({'full_name':'full_name_obj', 'address_line_1':'address_line_1_obj'})
>>> sdso
{}
>>> class Data_Set:
    def __init__(self, dict_of_datum, required=None):
    self.keys = dict_of_datum.keys
    self.values = dict_of_datum.values
    self.items = dict_of_datum.items
    self.required = required

    
>>> sdso = Data_Set({'full_name':'full_name_obj', 'address_line_1':'address_line_1_obj'})
>>> sdso
<__main__.Data_Set instance at 0x419690ac>
>>> sdso.keys()
['full_name', 'address_line_1']
>>> sdso.pop('full_name')

Traceback (most recent call last):
  File "", line 1, in -toplevel-
    sdso.pop('full_name')
AttributeError: Data_Set instance has no attribute 'pop'

Am I doing something wrong ?
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Trying tio emulate "diff" command of UNIX - please help

2006-10-06 Thread ALAN GAULD

> Thanks Alan, but can you please explain me what this line
> does:
> diff = [t1==t2 for t1,t2 in zip(line1,line2)].index(False)
> 

I'll unfold it somewhat:

mix = zip(a,b)   

produces a list of tuples:
[(a1,b1)(a2,b2),(a3,b3)]

t1 == t2 

produces a boolean result either True or False

for t1,t2 in mix

unpacks each tuple from the zipped list

Putting it back together in long hand

mix = zip(aLine1,aLine2)
results = []
for t1,t2 in mix:
   if t1 == t2:
  results.append(True)
   else: results.append(False)

diff = results.index(False)

finds the index of the first instance of False 
in results

Lets look at it as a comprehension again:

diff = [t1==t2 for t1,t2 in zip(aLine1,aLine2)].index(False)

Does that make sense now? Can you see the various 
bits at work?

Alan G.




___ 
To help you stay safe and secure online, we've developed the all new Yahoo! 
Security Centre. http://uk.security.yahoo.com
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Help: how to detect which key is pressed

2006-10-06 Thread Luke Paireepinart
Asrarahmed Kadri wrote:
>  
>  
> I am writing a simple program and in that I want to add some sort of 
> interactiveness.
> I have designed a menu which gives the user an option to select one 
> out of the following four keys: d, l, n or e.
> Can any one tell me how to determine which key has been pressed by the 
> user.
Asrarahmed:
Please refer to:
http://www.freenetpages.co.uk/hp/alan.gauld/
for information on how to do this.
specifically,
http://www.freenetpages.co.uk/hp/alan.gauld/tutinput.htm

You should work through this tutorial, not just the specific section on 
User Input, but the whole site.
It will cover the most common questions that people new to Python have.

Good Luck,
-Luke
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] when I create an instance of a class that inherits from Python dictionary, my data disappears

2006-10-06 Thread Bob Gailer
[EMAIL PROTECTED] wrote:
> hi all, I would like to create a class that specializes Python 
> dictionary.  I would like an instance of this class to store objects 
> representing html form data, and I would like to have an instance of 
> this Data_Set class be able to use the Python dictionary method pop to 
> remove objects as I see fit.  I defined the following:
>
> class Data_Set(dict):
> def __init__(self, dict_of_datum_objects, required=None):
> self.keys = dict_of_datum_objects.keys
> self.values = dict_of_datum_objects.values
> self.required = required
>
> For some reason, whenever I create an instance of this class with 
> data, all I get is an empty dictionary.  As soon as I redefine my 
> class to no longer inherit from Python dictionary, then I get expected 
> behavior, but now I don't have benefit of Python dictionary methods 
> such as pop and has_key:
>
> sdso = Data_Set({'full_name':'full_name_obj', 
> 'address_line_1':'address_line_1_obj'})
> >>> sdso
> {}
> >>> class Data_Set:
> def __init__(self, dict_of_datum, required=None):
> self.keys = dict_of_datum.keys
> self.values = dict_of_datum.values
> self.items = dict_of_datum.items
> self.required = required
>
> 
> >>> sdso = Data_Set({'full_name':'full_name_obj', 
> 'address_line_1':'address_line_1_obj'})
> >>> sdso
> <__main__.Data_Set instance at 0x419690ac>
> >>> sdso.keys()
> ['full_name', 'address_line_1']
> >>> sdso.pop('full_name')
>
> Traceback (most recent call last):
>   File "", line 1, in -toplevel-
> sdso.pop('full_name')
> AttributeError: Data_Set instance has no attribute 'pop'
>
> Am I doing something wrong ?
Err, yes. You are assuming that assigning to self.keys and self.values 
creates dictionary entries. All that actually does is assign the 2 lists 
to 2 attributes.

Try instead self.update(dict_of_datum_objects).

-- 
Bob Gailer
just up the road in El Cerrito
510-978-4454

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor