Re: [Tutor] Python help

2009-04-25 Thread Alan Gauld
"IT_ForMe"  wrote 


cart = {"apple":2.00, "orange":2.50, "banana":1.75}


You set this up but then don't use it.
Also your problem statement said *some* items were
taxable, implying some were not. You might want to 
record whether an item is taxable in the dictionary too.



print cart
apple = 2 
orange = 2.5

banana = 1.75


You don't need these lines since they are replicating 
your dictionary above




totalprice = 0


You don't need this since you will set totalprice in the next line.


totalprice = apple + orange + banana


You should use the dictionary here, and you could apply 
the tax to the taxable items before generating the total.
Also you might like to use a loop to get the total since 
the cart might change the number of items in a real 
world scenario.



print "your subtotal is 'totalprice'"
taxedprice = (totalprice *.07) + totalprice


It might be easier to just multiple by 1.07
Also it would be good to store the tax as a variable in 
case the rate changes.



print "your final price is 'taxedprice'"
prompt = raw_input("are you a student?")
if yes
('taxedprice' / 10) + taxed price = student


you must assign a value to a variable you cannot assign 
a variable to an expression.


Also, I thought the students got a discount? 
This provides a surcharge!



print "your student price is 'student'
else
print "have a nice day"


You also have some faulty syntax in the last if/else 
section which Python will tell you about.


HTH,


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

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


[Tutor] Is it syntactic,semantic or runtime?

2009-04-25 Thread prasad rao
helloI wrote a function to fetch data using urllib and displaying the data
using internet Explorer.
it is not preparing the html file
So opening blank Explorer after complaining th html file not found.
Where is the problem?
Can I display the data read from a site  without preparing
a html file?



def pp():
@@@ import urllib
@@@ import subprocess
@@@ so=urllib.urlopen('http://www.asstr.org')
@@@ data=so.read()
@@@ de=open('C:pp.html','w')
@@@ de.write(data)
@@@ subprocess.Popen(['C:\Program Files\Internet
xplorer\\IEXPLORE','C:pp.html'])





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


Re: [Tutor] Is it syntactic,semantic or runtime?

2009-04-25 Thread Sander Sweers
2009/4/25 prasad rao :

> So opening blank Explorer after complaining th html file not found.
> Where is the problem?

There are typing errors on the below...

> 
> def pp():
> @@@ import urllib
> @@@ import subprocess
> @@@ so=urllib.urlopen('http://www.asstr.org')
> @@@ data=so.read()
> @@@ de=open('C:pp.html','w')

This create a file pp.html in the directory where the script was run
from. I expect you want it in c:\ so it should look like. Notice the
backslash is escaped with a backslash!

  de = open('c:\\pp.html', 'w')

> @@@ de.write(data)
> @@@ subprocess.Popen(['C:\Program Files\Internet
> xplorer\\IEXPLORE','C:pp.html'])

Again the same issue as above plus the path to iexplore.exe is bad.

  subprocess.Popen(['C:\\Program Files\\Internet
Explorer\\iexplore.exe','C:\\pp.html'])

This works for me.

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


[Tutor] output formatting

2009-04-25 Thread Matt Domeier

Hello,

I have a series of lists that I need to output into files with a  
specific format. Specifically, I need to have line breaks after each  
entry of the list, and I need to do away with the ['..'] that  
accompany the data after I transform the list into a string. Can I  
simply append a '\n' to the end of all the list entries in order to  
enact line breaks?


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


Re: [Tutor] output formatting

2009-04-25 Thread W W
On Fri, Apr 24, 2009 at 10:57 PM, Matt Domeier  wrote:

> Hello,
>
> I have a series of lists that I need to output into files with a specific
> format. Specifically, I need to have line breaks after each entry of the
> list, and I need to do away with the ['..'] that accompany the data after I
> transform the list into a string. Can I simply append a '\n' to the end of
> all the list entries in order to enact line breaks?
>

Is this what you're looking for?

In [3]: print '\n'.join(['the quick brown fox', 'jumps over', 'the lazy
dog'])
the quick brown fox
jumps over
the lazy dog

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


Re: [Tutor] Is it syntactic,semantic or runtime?

2009-04-25 Thread Kent Johnson
On Sat, Apr 25, 2009 at 5:38 AM, prasad rao  wrote:
> hello
> I wrote a function to fetch data using urllib and displaying the data
> using internet Explorer.
> it is not preparing the html file
> So opening blank Explorer after complaining th html file not found.
> Where is the problem?
> Can I display the data read from a site  without preparing
> a html file?
> 
> def pp():
> @@@ import urllib
> @@@ import subprocess
> @@@ so=urllib.urlopen('http://www.asstr.org')
> @@@ data=so.read()
> @@@ de=open('C:pp.html','w')
> @@@ de.write(data)

You should close de here so the file is flushed to disk:
de.close()

Kent

> @@@ subprocess.Popen(['C:\Program Files\Internet
> xplorer\\IEXPLORE','C:pp.html'])
>
> 
>
> prasad
> ___
> Tutor maillist  -  tu...@python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] how to compile python3.0

2009-04-25 Thread عماد نوفل
On Fri, Apr 24, 2009 at 11:59 AM, Shaofeng NIu wrote:

> that worked for me,too :) thanks to all the peopel helping me
>
> 2009/4/24 Dayo Adewunmi 
>
>> Shaofeng NIu wrote:
>>
>>> I tried to compile and install python3.0 from source,but after "make",it
>>> shows:
>>>
>>> Python build finished, but the necessary bits to build these modules were
>>> not found:
>>> _dbm   _gdbm  _hashlib   _sqlite3
>>> _ssl   _tkinter   bz2readline
>>>To find the necessary bits, look in setup.py in detect_modules()
>>> for the module's name.
>>>
>>> Could anybody tell me how to install these modules?Thank you!
>>> My OS is Ubuntu 8.10
>>> 
>>>
>>> ___
>>> Tutor maillist  -  Tutor@python.org
>>> http://mail.python.org/mailman/listinfo/tutor
>>>
>>>
>>
>> This worked for me on Ubuntu 8.04:
>>
>> $ sudo apt-get install build-essential libncursesw5-dev libreadline5-dev
>> libssl-dev libgdbm-dev libbz2-dev libc6-dev libsqlite3-dev tk-dev g++ gcc
>>
>> Solution for _dbm
>> $ wget -c http://bugs.python.org/file12234/dbm.diff
>> $ patch -p0 < dbm.diff
>>
>> $ sudo apt-get build-dep python2.5
>> $ make
>> $ sudo make install
>>
>> Regards
>>
>> Dayo
>
> The following is a previous post by Vern Ceder. I thought it might help.

I have Python 3.0/Tkinter/IDLE working fine on Ubuntu 8.10, but it takes a
certain amount of fiddling.

1. Make sure the stock Ubuntu Python 3.0 package is not installed

2. download the Python 3.0 source from python.org

3. install the following packages: build-essential libsqlite3-dev
libreadline5-dev libncurses5-dev zlib1g-dev libbz2-dev libssl-dev
libgdbm-dev tk-dev

4. unpack the Python source and switch to that folder

5. build Python using the standard ./configure, make, make install sequence
- if you want more detail/help on that process, just ask...

I'd be happy to explain this process in more detail if anyone wants...




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


-- 
لا أعرف مظلوما تواطأ الناس علي هضمه ولا زهدوا في إنصافه كالحقيقة.محمد
الغزالي
"No victim has ever been more repressed and alienated than the truth"

Emad Soliman Nawfal
Indiana University, Bloomington

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


Re: [Tutor] Threading...

2009-04-25 Thread Kent Johnson
On Fri, Apr 24, 2009 at 5:26 PM, Spencer Parker  wrote:
> I have a script that I want to test MySQL sonnections with.  The way I have
> the script working is to just create connections, but I realized that it is
> going to wait for the first one to stop before starting a new connection.  I
> want to throw a ton of open connections at it to see what the connection
> limit is and how it reacts when it hits that shelf.  Would the best route
> for this be threading?  or is there another way to go about it?

Threading would be a start, though as Alan says it may not let you
test the limits.

To get started with threading you might want to use one of the thread
pool recipes in the Python cookbook.
http://code.activestate.com/recipes/576576/ (with links to many more)
http://code.activestate.com/recipes/576519/ (has the same interface as
multiprocessing.Pool so you could convert from threads to processes
easily)

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


Re: [Tutor] Is it syntactic,semantic or runtime?

2009-04-25 Thread Alan Gauld


"prasad rao"  wrote

helloI wrote a function to fetch data using urllib and displaying the 
data

using internet Explorer. it is not preparing the html file
So opening blank Explorer after complaining th html file not found.


The specific problem has been addressed but in general it is
wise to manually check these kinds of problems to see where
the problem is and solve that first. Thus in this case you needed
to check:

1) Was the html file being created where you expected with the
data you expected?
2) Could IE launch from the command line if you provided that file
as an argument?

In your case test 1 would fail - no file where you expected, so
the next questions to ask are
1a) Is the file being created someplace else (use search)
1b) If so does it have the data I expect?
1c) Can I open IE with the new location

That would have shown where the file was being created.
And hopefully that IE could open it.

This kind of basic detective work can very quickly identify the
errors in the code, much faster than just peering at the source
will - especially when, as in your case, there are several errors.
And if you have done that kind of investigation and still can't
find the problem then let us know what you have discovered
when you post.

Just some thoughts for the future,

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



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


Re: [Tutor] output formatting

2009-04-25 Thread Dave Angel

Matt Domeier  wrote:


Hello,

I have a series of lists that I need to output into files with a  
specific format. Specifically, I need to have line breaks after each  
entry of the list, and I need to do away with the ['..'] that  
accompany the data after I transform the list into a string. Can I  
simply append a '\n' to the end of all the list entries in order to  
enact line breaks?


Thanks!

  
First point:  you should include source code for what you're doing (cut 
'n paste, don't retype it).  Normally, it should also include sample 
data and/or sample results.


For example, you say you're transforming the list into a string, and 
that ".." accompanies the data.  I have to guess what you're doing, and 
therefore how to fis it.  I'd guess that for some reason you're using

 "..".join(mylist)

which would make a string by concatenating all the strings in the list, 
with ".." between them.  As Wayne has pointed out, you could just 
concatenate them using the "\n" separator instead of the ".."  But 
notice that puts newlines between the elements, but doesn't put one at 
the end.  Since he's using print, that automatically adds a trailing 
newline.   But probably you're not using print.  You didn't say.


But you say you want to put them into *files*, and "with a specific 
format."  It's only a wild guess that the plural was a typo, and that 
the specific format is called a text file.  Much more likely, you want 
to put some of them in one file, formatted a certain way, and some into 
another file, formatted differently.  If that's the case, why not loop 
through the list, doing whatever you really need?  You can always use a 
"\n" as part of the format when doing the call to write(), or whatever 
you're using to do the file I/O.  Or just use writeline(), which 
implicitly adds the newline.



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


Re: [Tutor] Is it syntactic,semantic or runtime?

2009-04-25 Thread prasad rao
hellothanks .After inserting back slashes and
de.close it is working well

thanks for the help

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


[Tutor] Working with lines from file and printing to another keeping sequential order

2009-04-25 Thread Dan Liang
Dear Tutors,


I have a file from which I want to extract lines that end in certain strings
and print to a second file. More specifically, I want to:

1) iterate over each line in the file, and if it ends in "yes", print it.
2) move to the line following the one described in #1 above, and if it ends
in, "no" print it.
3) move to third line, and if it ends in "no", print it.
4) move to fourth line, and if it ends in "no" discard it, but if it ends in
"yes" repeat 1, 2, and 3 above.
5) move to fifth line, and if it ends in "no" discard it, but if it ends in
"yes" repeat 1, 2, 3, and 4 above, and so on.

The goal is to get a ratio of 1 to 2 "yes" to "no" lines from a file in such
a way that keeps the order of the lines in output. An abstraction away from
this so that any ratio of "yes" to "no" lines could be printed while keeping
the order of the original lines would be great.


I am new to Python and could not solve the problem. Your help is
appreciated.

Cheers,

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


Re: [Tutor] Working with lines from file and printing to another keeping sequential order

2009-04-25 Thread bob gailer

Dan Liang wrote:

Dear Tutors,


I have a file from which I want to extract lines that end in certain 
strings and print to a second file. More specifically, I want to:


1) iterate over each line in the file, and if it ends in "yes", print it.
2) move to the line following the one described in #1 above, and if it 
ends in, "no" print it.

3) move to third line, and if it ends in "no", print it.
4) move to fourth line, and if it ends in "no" discard it, but if it 
ends in "yes" repeat 1, 2, and 3 above.
5) move to fifth line, and if it ends in "no" discard it, but if it 
ends in "yes" repeat 1, 2, 3, and 4 above, and so on.


The goal is to get a ratio of 1 to 2 "yes" to "no" lines from a file 
in such a way that keeps the order of the lines in output. An 
abstraction away from this so that any ratio of "yes" to "no" lines 
could be printed while keeping the order of the original lines would 
be great. 


Please show us what code you have written, and in what way it fails to 
meet your expectations.


Your specification is IMHO a nice piece of pseudocode which could 
translate to Python fairly easily!


What do we do at steps 4ff if the line does not end in "yes" or "no"?

If you have not written any code make a stab at it. You could start by 
asking "how in Python does one":

open a file?
iterate (loop)?
get the next line from a file?
test for equality?
examine the end of a string?


--
Bob Gailer
Chapel Hill NC
919-636-4239
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] # what do I do now to kill the the Windows program which has finished its work?

2009-04-25 Thread Ian Campbell

I am converting a Windows ProComm script into Python and  need help.

;  previous Procomm  script here

run "c:\buy.exe" taskId; this runs the c:\buy.exe 
program and assigns the  task identification number to the integer 
variable called "taskId"

pause 1  ; wait one second
while taskexists(taskId)   
 exitTask(taskId)   ; kills the task

endwhile

; we carry on the ProCommcode to completion



How do I do the same in Python?


os.startfile("c:\\buy.exe" , 'OPEN')# THIS WORKS  and returns but 
does not return the taskID


# what do I do now to kill the  the Windows program which has  finished 
its  work?




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


Re: [Tutor] output formatting

2009-04-25 Thread spir
Le Sat, 25 Apr 2009 11:02:47 -0400,
Matt Domeier  s'exprima ainsi:

> Hi Wayne,
> 
> Yes, that should work perfectly, but it is in writing files that I'm  
> having the problem. I'm still very new to python, so I only know to  
> use something like filename.write(str(listname)) to write my list to a  
> file..
> Is there a straightforward method of combining the ease of the print  
> function setup that you suggested with write? Or could I somehow use  
> the print function itself to write to the file (rather than just  
> output to my shell/prompt)?
> 
> Thanks!

I think you're confusing the writing function (file.write() or print) with the 
expression of the text to be written.
You can safely reuse the expression proposed by Wayne inside write():
   filename.write( '\n'.join(['the quick brown fox', 'jumps over', 'the lazy 
dog']) )
The remaining difference is that print will implicitely add an '\n' 
(end-of-line).

Also (but this difference does not apply here), write() expects a string while 
print will silently convert to str whatever you pass it:

f = file("test", 'w')
try:
f.write(1)
except TypeError:
f.write("*** not a str ***")
f.write(str(1))
f.close()

f = file("test", 'r')
print f.read()
f.close()

==>
*** not a str ***
1

Denis

> Quoting W W :
> 
> > On Fri, Apr 24, 2009 at 10:57 PM, Matt Domeier  wrote:
> >
> >> Hello,
> >>
> >> I have a series of lists that I need to output into files with a specific
> >> format. Specifically, I need to have line breaks after each entry of the
> >> list, and I need to do away with the ['..'] that accompany the data
> >> after I transform the list into a string. Can I simply append a '\n' to
> >> the end of all the list entries in order to enact line breaks?
> >>
> >
> > Is this what you're looking for?
> >
> > In [3]: print '\n'.join(['the quick brown fox', 'jumps over', 'the lazy
> > dog'])
> > the quick brown fox
> > jumps over
> > the lazy dog
> >
> > HTH,
> > Wayne
> >
> 
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 


--
la vita e estrany
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] output formatting

2009-04-25 Thread Matt Domeier

Hi Wayne,

Yes, that should work perfectly, but it is in writing files that I'm  
having the problem. I'm still very new to python, so I only know to  
use something like filename.write(str(listname)) to write my list to a  
file..
Is there a straightforward method of combining the ease of the print  
function setup that you suggested with write? Or could I somehow use  
the print function itself to write to the file (rather than just  
output to my shell/prompt)?


Thanks!

Quoting W W :


On Fri, Apr 24, 2009 at 10:57 PM, Matt Domeier  wrote:


Hello,

I have a series of lists that I need to output into files with a specific
format. Specifically, I need to have line breaks after each entry of the
list, and I need to do away with the ['..'] that accompany the data after I
transform the list into a string. Can I simply append a '\n' to the end of
all the list entries in order to enact line breaks?



Is this what you're looking for?

In [3]: print '\n'.join(['the quick brown fox', 'jumps over', 'the lazy
dog'])
the quick brown fox
jumps over
the lazy dog

HTH,
Wayne



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


Re: [Tutor] Working with lines from file and printing to another keeping sequential order

2009-04-25 Thread Dan Liang
Hi Bob and tutors,

Thanks Bob for your response! currently I have the current code, but it does
not work:

ListLines= []
for line in open('test.txt'):
line = line.rstrip()
ListLines.append(line)

for i in range(len(ListLines)):

if ListLines[i].endswith("yes") and ListLines[i+1].endswith("no") and
ListLines[i+1].endswith("no"):
print ListLines[i], ListLines[i+1], ListLines[i+2]
elif ListLines[i].endswith("yes") and ListLines[i+1].endswith("no"):
print ListLines[i], ListLines[i+1]
elif ListLines[i].endswith("yes"):
print ListLines[i]
elif ListLines[i].endswith("no"):
continue
else:
break

I get the following error:
Traceback (most recent call last):
  File "test.py", line 18, in 
if ListLines[i].endswith("yes") and ListLines[i+1].endswith("no") and
ListLines[i+1].endswith("no"):
IndexError: list index out of range

Lines in the file look like following:

word1 word2 word3 word4 yes
word1 word2 word3 word4 no
word1 word2 word3 word4 no
word1 word2 word3 word4 no
word1 word2 word3 word4 yes
word1 word2 word3 word4 no
word1 word2 word3 word4 yes
word1 word2 word3 word4 no
word1 word2 word3 word4 yes
word1 word2 word3 word4 yes
word1 word2 word3 word4 no
word1 word2 word3 word4 no
word1 word2 word3 word4 no
word1 word2 word3 word4 yes
word1 word2 word3 word4 no
word1 word2 word3 word4 yes
word1 word2 word3 word4 yes
word1 word2 word3 word4 no
word1 word2 word3 word4 no
word1 word2 word3 word4 no
word1 word2 word3 word4 no
word1 word2 word3 word4 yes

> What do we do at steps 4ff if the line does not end in "yes" or "no"?

I forgot to mention that I know for sure that the file has ONLY lines that
end in either "yes" or "no".

Any suggestions are appreciated. Also, I feel that my code is not the best
way of solving the problem even if the problem of list indices is solved. Is
my guess right?

Thank you!

-dan

On Sat, Apr 25, 2009 at 10:32 AM, bob gailer  wrote:

> Dan Liang wrote:
>
>> Dear Tutors,
>>
>>
>> I have a file from which I want to extract lines that end in certain
>> strings and print to a second file. More specifically, I want to:
>>
>> 1) iterate over each line in the file, and if it ends in "yes", print it.
>> 2) move to the line following the one described in #1 above, and if it
>> ends in, "no" print it.
>> 3) move to third line, and if it ends in "no", print it.
>> 4) move to fourth line, and if it ends in "no" discard it, but if it ends
>> in "yes" repeat 1, 2, and 3 above.
>> 5) move to fifth line, and if it ends in "no" discard it, but if it ends
>> in "yes" repeat 1, 2, 3, and 4 above, and so on.
>>
>> The goal is to get a ratio of 1 to 2 "yes" to "no" lines from a file in
>> such a way that keeps the order of the lines in output. An abstraction away
>> from this so that any ratio of "yes" to "no" lines could be printed while
>> keeping the order of the original lines would be great.
>>
>
> Please show us what code you have written, and in what way it fails to meet
> your expectations.
>
> Your specification is IMHO a nice piece of pseudocode which could translate
> to Python fairly easily!
>
> What do we do at steps 4ff if the line does not end in "yes" or "no"?
>
> If you have not written any code make a stab at it. You could start by
> asking "how in Python does one":
> open a file?
> iterate (loop)?
> get the next line from a file?
> test for equality?
> examine the end of a string?
>
>
> --
> Bob Gailer
> Chapel Hill NC
> 919-636-4239
>
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Working with lines from file and printing to another keeping sequential order

2009-04-25 Thread Shantanoo Mahajan (शंत नू महा जन)


On 25-Apr-09, at 11:41 PM, Dan Liang wrote:


Hi Bob and tutors,

Thanks Bob for your response! currently I have the current code, but  
it does not work:


ListLines= []
for line in open('test.txt'):
line = line.rstrip()
ListLines.append(line)

for i in range(len(ListLines)):

if ListLines[i].endswith("yes") and ListLines[i 
+1].endswith("no") and ListLines[i+1].endswith("no"):

print ListLines[i], ListLines[i+1], ListLines[i+2]
elif ListLines[i].endswith("yes") and ListLines[i 
+1].endswith("no"):

print ListLines[i], ListLines[i+1]
elif ListLines[i].endswith("yes"):
print ListLines[i]
elif ListLines[i].endswith("no"):
continue
else:
break

I get the following error:
Traceback (most recent call last):
  File "test.py", line 18, in 
if ListLines[i].endswith("yes") and ListLines[i 
+1].endswith("no") and ListLines[i+1].endswith("no"):

IndexError: list index out of range


You need to put check for

i <= len(ListLines)-2


or you can have a look @ try and except (exception handling in python)


Lines in the file look like following:

word1 word2 word3 word4 yes
word1 word2 word3 word4 no
word1 word2 word3 word4 no
word1 word2 word3 word4 no
word1 word2 word3 word4 yes
word1 word2 word3 word4 no
word1 word2 word3 word4 yes
word1 word2 word3 word4 no
word1 word2 word3 word4 yes
word1 word2 word3 word4 yes
word1 word2 word3 word4 no
word1 word2 word3 word4 no
word1 word2 word3 word4 no
word1 word2 word3 word4 yes
word1 word2 word3 word4 no
word1 word2 word3 word4 yes
word1 word2 word3 word4 yes
word1 word2 word3 word4 no
word1 word2 word3 word4 no
word1 word2 word3 word4 no
word1 word2 word3 word4 no
word1 word2 word3 word4 yes

> What do we do at steps 4ff if the line does not end in "yes" or  
"no"?


I forgot to mention that I know for sure that the file has ONLY  
lines that end in either "yes" or "no".


Any suggestions are appreciated. Also, I feel that my code is not  
the best way of solving the problem even if the problem of list  
indices is solved. Is my guess right?





Another suggestion. I would not read all data from file into array  
(memory). If your file is large, you may hit out of memory error.


regards,
shantanoo


Thank you!

-dan

On Sat, Apr 25, 2009 at 10:32 AM, bob gailer   
wrote:

Dan Liang wrote:
Dear Tutors,


I have a file from which I want to extract lines that end in certain  
strings and print to a second file. More specifically, I want to:


1) iterate over each line in the file, and if it ends in "yes",  
print it.
2) move to the line following the one described in #1 above, and if  
it ends in, "no" print it.

3) move to third line, and if it ends in "no", print it.
4) move to fourth line, and if it ends in "no" discard it, but if it  
ends in "yes" repeat 1, 2, and 3 above.
5) move to fifth line, and if it ends in "no" discard it, but if it  
ends in "yes" repeat 1, 2, 3, and 4 above, and so on.


The goal is to get a ratio of 1 to 2 "yes" to "no" lines from a file  
in such a way that keeps the order of the lines in output. An  
abstraction away from this so that any ratio of "yes" to "no" lines  
could be printed while keeping the order of the original lines would  
be great.


Please show us what code you have written, and in what way it fails  
to meet your expectations.


Your specification is IMHO a nice piece of pseudocode which could  
translate to Python fairly easily!


What do we do at steps 4ff if the line does not end in "yes" or "no"?

If you have not written any code make a stab at it. You could start  
by asking "how in Python does one":

open a file?
iterate (loop)?
get the next line from a file?
test for equality?
examine the end of a string?


--
Bob Gailer
Chapel Hill NC
919-636-4239

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


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


Re: [Tutor] # what do I do now to kill the the Windows program which has finished its work?

2009-04-25 Thread Alan Gauld


"Ian Campbell"  wrote

os.startfile("c:\\buy.exe" , 'OPEN')# THIS WORKS  and returns but 
does not return the taskID


Take a look at the subprocess module.

# what do I do now to kill the  the Windows program which has  finished 
its  work?


This is trickier, if the program does not stop itself when it finishes
then you need to look at timers and threads and how to programmatically
terminate a program in Windows. Usually the command line program
will terminate itself when done but if it doesn't you can use time.sleep()
as a delay. You will need to launch the program in a thread. You can
then try killing the thread which may kill the program, or if not, use the
Windows API to kill the program (gets messy). This is easier on Unix
in my experience!

HTH

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



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


Re: [Tutor] python books

2009-04-25 Thread chinmaya
On Mon, Apr 13, 2009 at 11:07 PM, sudhanshu gautam
wrote:

> I am new in python , so need a good books , previously read python Bible
> and swaroop but not satisfied .
>
>
> so tell me good books in pdf format those contents good problems also
>
>
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>


I would say start with python tutorial, its nice decent starting material.
There is no better way to learn language than to practice it as you read.
Most of the tutorials out there are not written for 3.0, so you may want
to install 2.6.
I also recommend Dive Into python, its very beginner friendly, but remember
it does not cover all (not all major) libraries never-the-less its one of
the
best beginner tutorial.

Also install ipython its very powerful. And once you learn the interface
its very easy to find documentation and library references.

Also you can look at 100s of python videos in showmedo.com


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


Re: [Tutor] python books

2009-04-25 Thread Dayo Adewunmi

chinmaya wrote:



On Mon, Apr 13, 2009 at 11:07 PM, sudhanshu gautam 
mailto:sudhanshu9...@gmail.com>> wrote:


I am new in python , so need a good books , previously read python
Bible and swaroop but not satisfied .


so tell me good books in pdf format those contents good problems also


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




I would say start with python tutorial, its nice decent starting 
material.

There is no better way to learn language than to practice it as you read.
Most of the tutorials out there are not written for 3.0, so you may want
to install 2.6.
I also recommend Dive Into python, its very beginner friendly, but 
remember
it does not cover all (not all major) libraries never-the-less its one 
of the

best beginner tutorial.

Also install ipython its very powerful. And once you learn the interface
its very easy to find documentation and library references.

Also you can look at 100s of python videos in showmedo.com 




--
chinmaya sn


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


I'm currently reading Think Python 
http://www.greenteapress.com/thinkpython/thinkpython.html


Regards

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


[Tutor] I may have solved my problem with killing tasks in Windows

2009-04-25 Thread Ian Campbell
I am trying to use this  so maybe  no one has to reply... sorry to  
inconvenience  anyone.
I got it from Google  but  did not copy his name and cannot give my 
thanks to original author,  sorry.


import subprocess
from win32event import WaitForSingleObject, WAIT_TIMEOUT
from win32api import TerminateProcess

def execute_and_wait(args, timeout=None):
   """Execute a command and wait until termination. If timeout elapses 
and still not finished, kill it.

   args: list containing program and arguments, or a single string.
   timeout: maximum time to wait, in ms, or None.
   """

   p = subprocess.Popen(args)
   if timeout:
   ret = WaitForSingleObject(p._handle, timeout)
   if ret==WAIT_TIMEOUT:
   TerminateProcess(p._handle, 1)
   return None
   return p.wait()

ret = execute_and_wait(["notepad", "c:\\BuyLiveHit.ahk"], 5000)
print "ret=",ret


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


Re: [Tutor] # what do I do now to kill the the Windows program which has finished its work?

2009-04-25 Thread Emile van Sebille

Alan Gauld wrote:

then try killing the thread which may kill the program, or if not, use the
Windows API to kill the program (gets messy). This is easier on Unix
in my experience!


Sysinternals created pstools for windows that I generally use for this 
kind of thing, particularly when it gets messy.  :)


Emile

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


Re: [Tutor] I may have solved my problem with killing tasks in Windows

2009-04-25 Thread Alan Gauld
"Ian Campbell"  wrote 

I am trying to use this  so maybe  no one has to reply... sorry to  
inconvenience  anyone.


No inconvenience and I'm glad you posted the solution 
you found.


That is pretty much what I had in mind but I didn't know 
you could get the _handle from the return value in Popen!
That makes it much easier. I would still tend to run the 
execute and wait from a separate thread just in case...



def execute_and_wait(args, timeout=None):
   p = subprocess.Popen(args)
   if timeout:
   ret = WaitForSingleObject(p._handle, timeout)
   if ret==WAIT_TIMEOUT:
   TerminateProcess(p._handle, 1)
   return None
   return p.wait()


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

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


Re: [Tutor] Working with lines from file and printing to another keeping sequential order

2009-04-25 Thread bob gailer

Dan Liang wrote:

Hi Bob and tutors,

Thanks Bob for your response! currently I have the current code, but 
it does not work:


[snip]

Thank you for code, sample data and more complete specs.

Lines in the file look like following:

word1 word2 word3 word4 yes
word1 word2 word3 word4 no
word1 word2 word3 word4 no
word1 word2 word3 word4 no
word1 word2 word3 word4 yes
word1 word2 word3 word4 no
word1 word2 word3 word4 yes
word1 word2 word3 word4 no
word1 word2 word3 word4 yes
word1 word2 word3 word4 yes
word1 word2 word3 word4 no
word1 word2 word3 word4 no
word1 word2 word3 word4 no
word1 word2 word3 word4 yes
word1 word2 word3 word4 no
word1 word2 word3 word4 yes
word1 word2 word3 word4 yes
word1 word2 word3 word4 no
word1 word2 word3 word4 no
word1 word2 word3 word4 no
word1 word2 word3 word4 no
word1 word2 word3 word4 yes




Any suggestions are appreciated. Also, I feel that my code is not the 
best way of solving the problem even if the problem of list indices is 
solved. Is my guess right?


Yes indeed. In actuality you need only to examine one line at a time and 
keep track of the "state" of things.


In computer theory we refer to a "state machine". There is a set of 
states. The program is always in exactly one of these states. In each 
state there are actions to take and a (conditional) moves to other states.


the program starts in, let's say, state 0:

state 0: open file, goto state 1.
state 1: read next line, at eof goto state 6; if it ends in yes, goto 
state 2 else stay in state 1.
state 2: read next line, at eof goto state 6; if it ends in yes stay in 
state 2 else goto state 3.
state 3: read next line, at eof goto state 6. if it ends in yes goto 
state 2 else print line and goto state 4.
state 4: read next line, at eof goto state 6. if it ends in yes goto 
state 2 else print line and goto state 5.
state 5: read next line, at eof goto state 6. if it ends in yes goto 
state 2 else stay in state 5.

state 6: close file and terminate

That can be implemented in Python as follows. This is not the prettiest 
or most compact program, but is it a straightforward implementation of a 
state machine.


state = 0 # initial state
data = open('test.txt')
while True: # iterate over lines
 if state == 0: # look for first line ending in 'yes'
   line = data.read().strip()
   if line:
 if line.endswith('yes'):
   state = 1
   else state = 6
 elif state == 1:
   # code for state i
 # more states
 elif state == 6:
   data.close()
   break

To simplify things I'd create a function to read and strip a line and 
raise an exception at end of file.


--
Bob Gailer
Chapel Hill NC
919-636-4239
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] # what do I do now to kill the the Windows program which has finished its work?

2009-04-25 Thread Kent Johnson
On Sat, Apr 25, 2009 at 11:35 AM, Ian Campbell  wrote:
> I am converting a Windows ProComm script into Python and  need help.
>
> ;  previous Procomm  script here
>
> run "c:\buy.exe" taskId                ; this runs the c:\buy.exe program
> and assigns the  task identification number to the integer variable called
> "taskId"
> pause 1                                      ; wait one second
> while taskexists(taskId)                               exitTask(taskId)
>           ; kills the task
> endwhile
>
> ; we carry on the ProComm    code to completion
>
>
>
> How do I do the same in Python?

I think something like this, in Python 2.6 anyway:

from subprocess import Popen
import time
p = Popen("c:\\buy.exe")  # Note double slashes for backslash
time.sleep(1)
if p.poll() is None:
  p.terminate()

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