Re: [Tutor] Communicating Between Programs Using Raw Inputs (con'd)

2011-06-18 Thread aditya
On Sat, Jun 18, 2011 at 9:35 PM, Jacob Bender wrote:

> Dear Tutors,
>
> Alright, I'm using linux (ubuntu) and I took all of your advice and I got
> something that works and doesn't work at the same time. Here's the source
> code for my two programs called Lock and Key:
>
> *Lock.py: *
>
> password = "a"
>
> psswd_try = raw_input("What's the password? ")
>
> if psswd_try == password:
> print "correct!!!"
> raw_input()
> else:
> print "wrong"
> raw_input()
> *
> *

Why do you need to call raw_input() again?  You are giving the input only
once so remove raw_input() from both if and else , that should do the work



> *Key.py*:
>
> import sys
>
> sys.stdout.write("a")
>
> In the linux terminal I ran this command(they were both in my home folder,
> so no directories were needed):
>
> python Key.py | python Lock.py
>
> And all went well except for an EOF error caused by the raw_input inside
> the "if" statement in my Lock program. However I did get it to print
> "correct", so I know sys.stdout.write() works for what I want it to, but I
> don't want the EOF error. Here's the output:
>
> Traceback (most recent call last):
>   File "Lock.py", line 7, in 
> raw_input()
> EOFError: EOF when reading a line
>
> Please help me get rid of it because I couldn't find a sys.stdout.close()
> command or any other std command that would help.
>
> Thanks!
>
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
>


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


[Tutor] Socket Programming issue

2011-06-20 Thread aditya
This is a small client-server program in which i am using a Vbscript program
to check for connectivity of 2 machines and write the output to a text file
whether it connectes or not ,


for example the contents of the file *output.txt* are

192.168.1.2 is connected
192.168.1.10 is not connected


Now i am trying to send the contents of this file from a client through a
socket to a server which is running on my main server .This is basically
created to automate the checking of connectivity of the machines. The issue
is that although the Vbscript writes the output to the file correctly but
when the client sends the contents of the file to the server via socket , it
sometimes prints all the lines of the file on the server and sometimes it
doesnt , i dont know whether the issue is with the client or the server ,
Please Help..


CLIENT.PY

import socket
import os
import sys
os.system("C:\Python26\ping.vbs")
host = "localhost"
port= 2
size = 1024

s=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((host,port))




f=open('output.txt','r')
while 1:
data = f.readline()
if data: s.send(data)
 else: break



f.close()

s.close()



SERVER.PY


import socket

host = ""
port = 2
size = 1024
backlog=5
s=socket.socket(socket.AF_INET, socket.SOCK_STREAM)

s.bind((host,port))
s.listen(backlog)

while 1:
client, addr =s.accept()
data=client.recv(size)
if data:
print data

else:
print  "client exit"

s.close()









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


Re: [Tutor] Socket Programming issue

2011-06-21 Thread aditya
On Tue, Jun 21, 2011 at 12:45 PM, Alan Gauld wrote:

>
> "aditya"  wrote
>
>
>  is that although the Vbscript writes the output to the file correctly but
>> when the client sends the contents of the file to the server via socket ,
>> it
>> sometimes prints all the lines of the file on the server and sometimes it
>> doesnt , i dont know whether the issue is with the client or the server ,
>>
>
> Use the return values from functions.
>
>
>  CLIENT.PY
>>
>> import socket
>> import os
>> import sys
>> os.system("C:\Python26\ping.**vbs")
>> host = "localhost"
>> port= 2
>> size = 1024
>>
>> s=socket.socket(socket.AF_**INET, socket.SOCK_STREAM)
>> s.connect((host,port))
>>
>> f=open('output.txt','r')
>> while 1:
>> data = f.readline()
>>
>
> You could print the data here to check that you got something
> meaningful from the file
>
>
>  if data: s.send(data)
>>
>
> The socket documentation specifically says:
> --**---
> socket.send(string[, flags])
>  Send data to the socket. The socket must be connected to a remote socket.
> The optional flags argument has the same meaning as for recv() above.
> Returns the number of bytes sent. Applications are responsible for checking
> that all data has been sent; if only some of the data was transmitted, the
> application needs to attempt delivery of the remaining data.
>
> >Thanks Alan i will put in some conditional checks to check and reattempt
to send the data if it has not been sent or not. besides i am sending you
the client,server, and the output file to just go though it once . You can
run the script for yourself and see what happens.It actually prints only one
line of the ouput file and some times all the lines at the server end.

Besides can you help me with the checks which you insist me to put in
socket.send() ?







> --**
> Notice that it tells you how many bytes have been sent, and it
> is your responsibility to check and retry if necessary.
> I see no check nor any attempt to retry
>
> That should tell you if the data is leaving the client at least.
>
>
>
>  SERVER.PY
>> import socket
>>
>> host = ""
>> port = 2
>> size = 1024
>> backlog=5
>> s=socket.socket(socket.AF_**INET, socket.SOCK_STREAM)
>>
>> s.bind((host,port))
>> s.listen(backlog)
>>
>> while 1:
>> client, addr =s.accept()
>> data=client.recv(size)
>> if data:
>> print data
>> else:
>> print  "client exit"
>>
>
> This implies you should always get something printed, do you?
> When you say it sometimes prints the lines and sometimes
> not, does it print the exit message instead?
>
>  s.close()
>>
>
> I'm not clear where this line sits since the mail has lost
> its indentation. Is it inside the else or at the while level?
>
> Just some things to c0onsider,
>
> HTH
>
>
> --
> Alan Gauld
> Author of the Learn to Program web site
> http://www.alan-g.me.uk/
>
>
>
> __**_
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/**mailman/listinfo/tutor<http://mail.python.org/mailman/listinfo/tutor>
>



-- 
Regards
Aditya
reply from 192.168.100.1
reply from 192.168.100.7


client.py
Description: Binary data


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


[Tutor] help in TKINTER

2011-08-15 Thread aditya
Hello tutors,

I wanted some help in using the Tkinter class for button creation, I am not
able to add on click events i.e. when I press the button certain action
should be performed for example if I press the button named 5, then it
should display 5 in the text field .

 Help will be appreciated.

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


Re: [Tutor] reading random line from a file

2007-07-19 Thread Aditya Lal
An alternative approach (I found the Yorick's code to
be too slow for large # of calls) :

We can use file size to pick a random point in the
file. We can read and ignore text till next new line.
This will avoid outputting partial lines. Return the
next line (which I guess is still random :)). 

Indicative code -

import os,random

def getrandomline(filename) :
  offset = random.randint(0,os.stat(filename)[6])
  fd = file(filename,'rb')
  fd.seek(offset)
  fd.readline()  # Read and ignore
  return fd.readline()

getrandomline("shaks12.txt")

Caveat: The above code will never choose 1st line and
will return '' for last line. Other than the boundary
conditions it will work well (even for large files). 

Interestingly :

On modifying this code to take in file object rather
than filename, the performance improved by ~50%. On
wrapping it in a class, it further improved by ~25%.

On executing the get random line 100,000 times on
large file (size 2707519 with 9427 lines), the class
version finished < 5 seconds.

Platform : 2GHz Intel Core 2 Duo macBook (2GB RAM)
running Mac OSX (10.4.10).

Output using python 2.5.1 (stackless)

Approach using enum approach : 9.55798196793 : for
[100] iterations
Approach using filename : 11.552863121 : for [10]
iterations
Approach using file descriptor : 5.97015094757 : for
[10] iterations
Approach using class : 4.46039891243 : for [10]
iterations

Output using python 2.3.5 (default python on OSX)

Approach using enum approach : 12.2886080742 : for
[100] iterations
Approach using filename : 12.5682640076 : for [10]
iterations
Approach using file descriptor : 6.55952501297 : for
[10] iterations
Approach using class : 5.35413718224 : for [10]
iterations

I am attaching test program FYI.

--
Aditya

--- Nathan Coulter
<[EMAIL PROTECTED]> wrote:

> >  ---Original Message---
> >  From: Tiger12506 <[EMAIL PROTECTED]>
> 
> >  Yuck. Talk about a one shot function! Of course
> it only reads through the
> >  file once! You only call the function once. Put a
> second print randline(f)
> >  at the bottom of your script and see what happens
> :-)
> >  
> >  JS
> >  
> 
> *sigh*
> 
> #!/bin/env python
> 
> import os
> import random
> 
> text = 'shaks12.txt'
> if not os.path.exists(text):
>   os.system('wget
> http://www.gutenberg.org/dirs/etext94/shaks12.txt')
> 
> def randline(f):
> for i,j in enumerate(file(f, 'rb')):
> if random.randint(0,i) == i:
> line = j
> return line
> 
> print randline(text)
> print randline(text)
> print randline(text)
> 
> -- 
> Yorick
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 



 

Sucker-punch spam with award-winning protection. 
Try the free Yahoo! Mail Beta.
http://advision.webevents.yahoo.com/mailbeta/features_spam.htmlimport os
import random

class randomline :
	
	def __init__(self, filename="largefile.txt") :
		self.filesize = os.stat(filename)[6]
		self.fd = file(filename, 'rb')

	def getline(self) :
		offset = random.randint(0,self.filesize)
		self.fd.seek(offset)
		self.fd.readline()
		line = self.fd.readline()
		return (offset,line)
	
	def close(self) :
		self.fd.close()

# Uses file name
def getrandomline(filename) :
	offset = random.randint(0,os.stat(filename)[6])
	fd = file(filename, 'rb')
	fd.seek(offset)
	ret = (offset,fd.readline())
	fd.close()
	return ret

# Uses file descriptor
def getrandline(fd) :
	offset = random.randint(0,os.fstat(fd.fileno())[6])
	fd.seek(offset)
	line = fd.readline()
	return (offset,fd.readline())

# Uses enumeration
def randline(fd):
	for i,j in enumerate(fd) :
		if random.randint(0,i) == i:
			line = j
	fd.seek(0)
	return line


if __name__ == '__main__' :

	# Substitute your file name
	filename = "largefile.txt"

	# Class
	rd = randomline(filename)
	print rd.getline()
	rd.close()

	# file name
	print getrandomline(filename)

	# file descriptor
	fd = file(filename,'rb')
	print getrandline(fd)
	fd.close()

	# Using enum approach
	fd = file(filename,'rb')
	print randline(fd)
	fd.close()

	from timeit import Timer 
	t_class = Timer('rd.getline()', 'from __main__ import randomline ; rd = randomline("'+filename+'")')
	t_filename = Timer('getrandomline("'+filename+'")', 'from __main__ import getrandomline')
	t_fd = Timer('getrandline(fd)', 'from __main__ import getrandline ; fd = file("'+filename+'")')
	t_enum = Timer('randline(fd)', 'from __main__ import rand

Re: [Tutor] reading random line from a file

2007-07-19 Thread Aditya Lal
Sorry, I did not see the other thread in which this
approach has already been covered. The point Kent has
raised about going into infinite loop with file having
single line is very true.

Following is the corrected version (for completeness
sake) -

import os,random

def getrandfromMem(filename) :
  fd = file(filename,'rb')
  l = fd.readlines()
  pos = random.randint(0,len(l))
  fd.close()
  return (pos,l[pos])

def getrandomline2(filename) :
  filesize = os.stat(filename)[6]
  if filesize < 4096 :  # Seek may not be very useful
return getrandfromMem(filename)

  fd = file(filename,'rb')
  for _ in range(10) : # Try 10 times
pos = random.randint(0,filesize)
fd.seek(pos)
fd.readline()  # Read and ignore
line = fd.readline()
if line != '' :
   break

  if line != '' :
return (pos,line)
  else :
getrandfromMem(filename)

getrandomline2("shaks12.txt")

Caveat : It will still skip 1st line during random
selection if its size exceed 4096 chars !!


--- Aditya Lal <[EMAIL PROTECTED]> wrote:

> An alternative approach (I found the Yorick's code
> to
> be too slow for large # of calls) :
> 
> We can use file size to pick a random point in the
> file. We can read and ignore text till next new
> line.
> This will avoid outputting partial lines. Return the
> next line (which I guess is still random :)). 
> 
> Indicative code -
> 
> import os,random
> 
> def getrandomline(filename) :
>   offset = random.randint(0,os.stat(filename)[6])
>   fd = file(filename,'rb')
>   fd.seek(offset)
>   fd.readline()  # Read and ignore
>   return fd.readline()
> 
> getrandomline("shaks12.txt")
> 
> Caveat: The above code will never choose 1st line
> and
> will return '' for last line. Other than the
> boundary
> conditions it will work well (even for large files).
> 
> 
> Interestingly :
> 
> On modifying this code to take in file object rather
> than filename, the performance improved by ~50%. On
> wrapping it in a class, it further improved by ~25%.
> 
> On executing the get random line 100,000 times on
> large file (size 2707519 with 9427 lines), the class
> version finished < 5 seconds.
> 
> Platform : 2GHz Intel Core 2 Duo macBook (2GB RAM)
> running Mac OSX (10.4.10).
> 
> Output using python 2.5.1 (stackless)
> 
> Approach using enum approach : 9.55798196793 : for
> [100] iterations
> Approach using filename : 11.552863121 : for
> [10]
> iterations
> Approach using file descriptor : 5.97015094757 : for
> [10] iterations
> Approach using class : 4.46039891243 : for [10]
> iterations
> 
> Output using python 2.3.5 (default python on OSX)
> 
> Approach using enum approach : 12.2886080742 : for
> [100] iterations
> Approach using filename : 12.5682640076 : for
> [10]
> iterations
> Approach using file descriptor : 6.55952501297 : for
> [10] iterations
> Approach using class : 5.35413718224 : for [10]
> iterations
> 
> I am attaching test program FYI.
> 
> --
> Aditya
> 
> --- Nathan Coulter
> <[EMAIL PROTECTED]> wrote:
> 
> > >  ---Original Message---
> > >  From: Tiger12506 <[EMAIL PROTECTED]>
> > 
> > >  Yuck. Talk about a one shot function! Of course
> > it only reads through the
> > >  file once! You only call the function once. Put
> a
> > second print randline(f)
> > >  at the bottom of your script and see what
> happens
> > :-)
> > >  
> > >  JS
> > >  
> > 
> > *sigh*
> > 
> > #!/bin/env python
> > 
> > import os
> > import random
> > 
> > text = 'shaks12.txt'
> > if not os.path.exists(text):
> >   os.system('wget
> >
> http://www.gutenberg.org/dirs/etext94/shaks12.txt')
> > 
> > def randline(f):
> > for i,j in enumerate(file(f, 'rb')):
> > if random.randint(0,i) == i:
> > line = j
> > return line
> > 
> > print randline(text)
> > print randline(text)
> > print randline(text)
> > 
> > -- 
> > Yorick
> > ___
> > Tutor maillist  -  Tutor@python.org
> > http://mail.python.org/mailman/listinfo/tutor
> > 
> 
> 
> 
>  
>

> Sucker-punch spam with award-winning protection. 
> Try the free Yahoo! Mail Beta.
>
http://advision.webevents.yahoo.com/mailbeta/features_spam.html>
import os
> import random
> 
> class randomline :
>   

Re: [Tutor] reading random line from a file

2007-07-20 Thread Aditya Lal
A bug:
The function random.randint(a,b) include both ends
i.e. b is also included. Thus for file with single
line a=0,b=1 my algo will give an IndexError.

Significance of number 4096 :
file is stored in blocks of size 2K/4K/8K (depending
upon the machine). file seek for an offset goes block
by block rather than byte by byte. Hence for file size
< 4096 (assuming you have 4K block size), you will
anyway end up scanning it entirely so as well load it
up in memory.

Luke suggestion for Index:
I think its an implicit need to give equal probability
to each line. Taking an example - suppose we are
trying to find "quote of the day" from a dictionary of
quotations which may contain 100s of thousands of
quotes. We would like to see a new one each time on
invocation rather than favour the longest one.
So, creating an index is the right solution. But I
just want to add that since index creation is quite a
laborious task (in terms of CPU/time) one should do it
only once (or till file is changed). Thus it should be
kept on disk and ensure that index is re-created in
case file changes. I would like suggestions on index
creation.

--- Luke Paireepinart <[EMAIL PROTECTED]> wrote:

> bhaaluu wrote:
> > Greetings,
> > Thanks for including the complete source code!
> > It really helps to have something that works to
> look at.
> > I modified an earlier version of this to run on my
> > computer (GNU/Linux; Python 2.4.3).
> >   
> I think the best strategy for this problem would be
> to build an index of 
> the offset of the start of each line, and then
> randomly select from this 
> list.
> that makes each line equally probable, and you can
> set up your class so 
> that the index is only built on the first call to
> the function.
> -Luke
> 
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 



   

Choose the right car based on your needs.  Check out Yahoo! Autos new Car 
Finder tool.
http://autos.yahoo.com/carfinder/
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] How to speed up input/string parsing ...

2007-09-27 Thread Aditya Lal
Hi !!
I was trying to solve SPOJ (www.spoj.pl) problems - ADDREV (add reversed
numbers).

My solution clocked 0.58 seconds in SPOJ's computer as compared to best time
of 0.28. Interestingly my program spends 50% of its total execution time in
reading/parsing the input.

Following is the sample input/output. The actual data set contains ~ 10,000
numbers.

Sample input:

3  --> indicates the # of lines to follow
24 1  --> 2 numbers separated by a space
4358 754
305 794


Sample output:

34  --> reverse of sum of reverse of both numbers
1998
1

I wrote the following code -

def rev(n) :
m = 0
while n > 0 :
m = m*10 + n%10
n = n/10
return m

def solve(line) :
nums = line.split(' ')
a = int(nums[0])
b = int(nums[1])
return rev( rev(a) + rev(b) )

if __name__ == '__main__' :

N = int(sys.stdin.readline())
lines = sys.stdin.readlines()
for i in xrange(N) :
print solve(lines[i])

My Question :

How do I improve the input reading or string parsing ? I know there should
be a better way because the best program (at cost of memory) performs > 50%
faster than mine. So he must have done something to improve input
processing.

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


Re: [Tutor] How to speed up input/string parsing ...

2007-09-27 Thread Aditya Lal
Hello Kent,
I tried finding solution with using only strings but unfortunately reversing
a number has some interesting issues - For example: take following two
numbers -
002000 002000

though the final answer is 4 - arriving at it using string is stripping '0'
from both left and right of both numbers. I thought it was far easier to
convert it into an integer and reverse. Anyway I wasn't aware of string
reversal shortcut - [::-1] ... thanx :)

Following code performs in 0.50 seconds :

import sys

def rev(n) :
m = 0
while n > 0 :
r = n%10
m = m*10 + r
n = n/10
return m

def solve(line) :
nums = line.split(' ')
a = int(nums[0].strip('0')[::-1])
b = int(nums[1].strip('0')[::-1])
return rev( a + b )

if __name__ == '__main__' :
N = int(sys.stdin.readline())
lines = sys.stdin.readlines()
for i in xrange(N) :
print solve(lines[i])


I will start working on psyco ... though not sure what is it ?

Thanks again Kent.

Cheers
Aditya

On 9/27/07, Kent Johnson <[EMAIL PROTECTED]> wrote:
>
> Aditya Lal wrote:
>
> > def rev(n) :
> > m = 0
> > while n > 0 :
> > m = m*10 + n%10
> > n = n/10
> > return m
>
> I would try reversing the numbers as strings. s[::-1] will reverse a
> string s.
>
> > How do I improve the input reading or string parsing ? I know there
> > should be a better way because the best program (at cost of memory)
> > performs > 50% faster than mine. So he must have done something to
> > improve input processing.
>
> The programs that use a lot of memory are using psyco.
>
> Kent
>



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


Re: [Tutor] 2 problems in a small script

2007-10-11 Thread Aditya Lal
Hi Dick,

You are deleting from the SAME list that you are traversing. This results in
problems. You should just create a new list for the elements that are
well-formed.

astr = ...
lstA = ...

def wellFormed(word) :
  for ch in word :
 if ch not in astr :
return False
  return True

final = []
for word in lstA :
  if wellFormed(word) :
 final.append(word)

You can also look at documentation for filter function (which is now handled
via list comprehension).

finalList = filter( wellFormed, lstA )

or

finalList = [ word for word in lstA if wellformed(word) ]

HTH
Aditya


On 10/12/07, Dick Moores <[EMAIL PROTECTED]> wrote:
>
> Please see the code and it's output here:
> <http://www.rcblue.com/Python/buggy_For_Web.py>
>
>
> I'm attempting to eliminate the elements (strings) of lstA that are
> not well-formed in that they contain at least one character that is
> not in the string astr.
>
> Problems:
> 1) If lstA[n] is removed, lstA[n+1] is skipped--isn't examined at
> all, and remains in the final form of lstA whether well-formed or not.
>
> Using print statements is as far as my debugging skills go, so you
> can see of bunch of them in the code. I did try to use winpdb for the
> first time, but haven't figured it out yet. Ulipad now has it built
> in, so I'd like to learn to use it it..
>
> 2) I'm not able to get the "for char in wordWithCommas:" loop to stop
> examining a wordWithCommas after it's word has been removed. I've
> tried "continue" and "break" in various places to no avail.
>
> I'd appreciate some help.
>
> Thanks,
>
> Dick Moores
> Win XP, Python 2.5.1
>
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>



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


Re: [Tutor] 2 problems in a small script

2007-10-12 Thread Aditya Lal
lstB = lstA

The above just points lstB to lstA and *does not* create a copy. If you do
not understand "pointers", think of lstB an alias of lstA. If you want to
create a copy you need to explicitly do it.

lstB = []
for word in lstA :
   lstB.append(word)

or shortcut

lstB = lstA[:]

So, even though you created a new variable lstB it was actually modifying
lstA.

HTH
Aditya

On 10/12/07, Dick Moores <[EMAIL PROTECTED]> wrote:
>
> At 11:25 PM 10/11/2007, Aditya Lal wrote:
> >Hi Dick,
> >
> >You are deleting from the SAME list that you are traversing. This
> >results in problems.
>
> Aditya,
>
> Well, if deleting from the same list I'm traversing is the problem,
> why doesn't inserting the line
> lstB = lstA
>
> and deleting from lstB clear it up? The output is exactly the same.
> I'm really puzzled. See <http://www.rcblue.com/Python/buggy_For_Web2.py>
>
> I thank you for showing me another way to get the result I want, but
> first I want to know why my code didn't work.
>
> Dick
>
> _______
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>



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


Re: [Tutor] 2 problems in a small script

2007-10-12 Thread Aditya Lal
w.r.t. prob 2, there is no break/continue in the code that you have given. I
added the "break" statement after you remove the word from lstB and code
does seems to work for me.

  
if word in lstB:
lstB.remove(word)
print
print "Removed", word
break
  

Can you specify where did you try putting break/continue ?


On 10/12/07, Dick Moores <[EMAIL PROTECTED]> wrote:
>
> At 10:53 PM 10/11/2007, Dick Moores wrote:
> >Please see the code and it's output here:
> ><http://www.rcblue.com/Python/buggy_For_Web.py>
> >
> >
> >I'm attempting to eliminate the elements (strings) of lstA that are
> >not well-formed in that they contain at least one character that is
> >not in the string astr.
> >
> >Problems:
> >1) If lstA[n] is removed, lstA[n+1] is skipped--isn't examined at
> >all, and remains in the final form of lstA whether well-formed or not.
> >
> >Using print statements is as far as my debugging skills go, so you
> >can see of bunch of them in the code. I did try to use winpdb for the
> >first time, but haven't figured it out yet. Ulipad now has it built
> >in, so I'd like to learn to use it it..
> >
> >2) I'm not able to get the "for char in wordWithCommas:" loop to stop
> >examining a wordWithCommas after it's word has been removed. I've
> >tried "continue" and "break" in various places to no avail.
> >
> >I'd appreciate some help.
>
> Now that Aditya and Alan have come to my rescue, problem #1 has been
> solved. But #2 remains..
>
> Dick
>
>
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>



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


Re: [Tutor] populating an array or using a dictionary

2007-10-21 Thread Aditya Lal
If the ease of use is the only answer then the size of the file should not
matter ideally. btw, how large is the file ? is it in MBs or GBs ? For
performance reasons, typically you should not have any problems using either
dictionary, array or list for file size of few KBs.

Like Kent said, if you can sent some code it will throw light on how you
plan to use the data because the right data structure depends upon the
access pattern.

On 10/19/07, Eric Brunson <[EMAIL PROTECTED]> wrote:
>
> Bryan Fodness wrote:
> > The data file is larger than shown, and I was wondering if it would be
> > better to populate an array or create a dictionary.  Which would be
> > easier?
> >
>
> A dictionary is an array with an index, if you need an index into your
> data, use a dictionary, if not use an array.
>
>
> >
> > On 10/19/07, *Kent Johnson* <[EMAIL PROTECTED] <mailto:[EMAIL PROTECTED]>>
> > wrote:
> >
> > Bryan Fodness wrote:
> > > I have a data file that I would like to extract data from:
> > >
> > > FS   1   2   3   4   5
> > > 1.5   1.000   1.000   1.000   1.000   1.000
> > > 2.0   0.985   0.994   0.997   0.996   0.996
> > > 2.5   0.967   0.976   0.981   0.981   0.982
> > > 3.0   0.949   0.958   0.965   0.966   0.967
> > > 3.5   0.925   0.937   0.945   0.948   0.951
> > > 4.0   0.901   0.916   0.925   0.930   0.934
> > > 4.5   0.882   0.896   0.906   0.912   0.917
> > > 5.0   0.863   0.876   0.887   0.893   0.899
> > >
> > >
> > > The first row is a variable d, and the first column is FS.  Any
> > > suggestions on the best way to do this.
> >
> > This looks the same as the question you asked on Wednesday...do
> > you have
> > some code already?
> >
> > It helps if you can show what you have already done and ask for help
> > with changes.
> >
> > Kent
> >
> >
> > ----
> >
> > ___
> > Tutor maillist  -  Tutor@python.org
> > http://mail.python.org/mailman/listinfo/tutor
> >
>
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>



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


Re: [Tutor] trouble with if

2007-10-25 Thread Aditya Lal
I think you need to use "raw_input" instead of "input". input "eval" the
input expression while "raw_input" just stores it. I find the module help
very handy when I am in doubt.

>>> print raw_input.__doc__
raw_input([prompt]) -> string

Read a string from standard input.  The trailing newline is stripped.
If the user hits EOF (Unix: Ctl-D, Windows: Ctl-Z+Return), raise EOFError.
On Unix, GNU readline is used if enabled.  The prompt string, if given,
is printed without a trailing newline before reading.

>>> print input.__doc__
input([prompt]) -> value
Equivalent to eval(raw_input(prompt)).


On 10/26/07, Bryan Fodness <[EMAIL PROTECTED]> wrote:
>
> I cannot get this to work either.
>
> woffaxis = 7
>
> if woffaxis != 0:
>  woaf_pos = input("What is Wedge Direction (N/A, Lateral, Towards
> Heal, Towards Toe)?")
>
> if woaf_pos == 'Towards Toe':
>  woffaxis = woffaxis
> elif woaf_pos == 'Towards Heal':
>  woffaxis = (woffaxis * -1)
> else:
>  woffaxis = 0
>
>
>
>
>
>
> On 10/24/07, John Fouhy <[EMAIL PROTECTED]> wrote:
> >
> > On 25/10/2007, Bryan Fodness <[EMAIL PROTECTED]> wrote:
> > > I have the following code, it keeps giving me a value of 1 for e.
> > >
> > > for line in file('21Ex6MV_oaf.dat'):
> > > oa, openoa, w15, w30, w45, w60 = line.split()
> > > if (float(oa) == round(offaxis)) and (eff_depth < 10 and
> > unblockedFS >
> > > 15):
> > > e = float(openoa)
> > > else:
> > > e = 1
> > >
> > > If I comment out the else, I get the correct value
> > >
> > > for line in file('21Ex6MV_oaf.dat'):
> > > oa, openoa, w15, w30, w45, w60 = line.split()
> > > if (float(oa) == round(offaxis)) and (eff_depth < 10 and
> > unblockedFS >
> > > 15):
> > > e = float(openoa)
> > > #else:
> > > #e = 1
> >
> > Maybe you need a 'break' statement after 'e = float(openoa)'?
> >
> > As written, e will have whatever value is appropriate for the last
> > line of your input file.
> >
> > --
> > John.
> >
>
>
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>


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


Re: [Tutor] 'source' in python or preloading variables

2007-10-27 Thread Aditya Lal
You can source the file in python provided that you make it python
friendly:-
STN_id[1]='AAA' instead of STN_id[1]=AAA
...

---
import re
# Read the file
fd = open('sitelocations')
lines = fd.readlines()
fd.close()

# Make it python friendly: put all values in 'single quotes'
cmd = '\n'.join([re.sub( r'^([^=]+)=(.*)$', r"\1='\2'", v) for v in lines])

# Create variables as list of appropriate size with default values (assuming
0)
max = 5
STN_id, STNlat, STNlon, STNelv = [0]*max, [0]*max, [0]*max, [0]*max

# Execute the command and all your variables are populated ...
exec(cmd)

---
Not sure if this is a better way :) But atleast it will make the file
sitelocations order invariant - implies you can interchange the lines
without breaking the logic.

Caveat - list in python starts at 0 index so STN_id[1] is not the first
element but the second element. But you can filter unwanted items from the
list if you want as in -
[ x for x in STN_id if x != 0 ]

HTH
Aditya

On 10/27/07, John <[EMAIL PROTECTED]> wrote:
>
> I have a file sitelocations:
>
> STN_id[1]=AAA
> STNlat[1]=58.80
> STNlon[1]=17.40
> STNelv[1]=20
> STN_id[2]=BBB
> STNlat[2]=42.45
> STNlon[2]=25.58
> STNelv[2]=2925
>
> which in shell scripts I can simple 'source'. In Python I have to:
> sitesFile=file('sitelocations','r')
> sites=sitesFile.readlines()
> i=0;
> for l in sites:
> if i==0:
> STN_id.append(l.split('=')[1].strip('\n')); i+=1;
> elif i==1:
> STNlat.append(l.split('=')[1].strip('\n')); i+=1;
> elif i==2:
> STNlon.append(l.split('=')[1].strip('\n')); i+=1;
> else:
> STNelv.append(l.split('=')[1].strip('\n')); i=0;
>
> Is there a better way??
>
> Thanks!
>
>
>
>
> --
> Configuration
> ``
> Plone 2.5.3-final,
> CMF-1.6.4,
> Zope (Zope 2.9.7-final, python 2.4.4, linux2),
> Five 1.4.1,
> Python 2.4.4 (#1, Jul 3 2007, 22:58:17) [GCC 4.1.1 20070105 (Red Hat
> 4.1.1-51)],
> PIL 1.1.6
>
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman<http://mail.python.org/mailman/listinfo/tutor>
> /listinfo/tutor <http://mail.python.org/mailman/listinfo/tutor>
>
>


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


Re: [Tutor] question re type()

2007-10-27 Thread Aditya Lal
On 10/27/07, Alan Gauld <[EMAIL PROTECTED]> wrote:
>
>
> "Dick Moores" <[EMAIL PROTECTED]> wrote
>
> > if type(n) == 'int' or type(n) == 'long':
> >   do something
>
> don't use strings
>
> if type(n) == int
>
> Or just use an instance of the same type:
>
> if type(n) == type(42)
>
> Alan G.
>
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>

or use types module
import types

if type(n) == types.IntType or type(n) == types.LongType :
blah!

this comes handy especially for some unique conditions - like whether the
function passed is a generator or a normal function (well I kinda had this
problem ... :) )

ex.
if type(f) == types.GeneratorType or type(f) == types.lambdaType :
   same blah!

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


Re: [Tutor] 'source' in python or preloading variables

2007-10-27 Thread Aditya Lal
On 10/27/07, John <[EMAIL PROTECTED]> wrote:
>
> Ok, so trying to convert it to a function:
>
> def source(ifile, *args):
> """ takes a file object and a list of variables as input.
> assumes, source file has variables in format:
> VAR[i]=variable """
>
> import re
> # Read the file
> lines = fd.readlines()
> fd.close()
>
> # Make it python friendly: put all values in 'single quotes'
> cmd = '\n'.join([re.sub( r'^([^=]+)=(.*)$', r"\1='\2'", v) for v
> in lines])
>
> # Create variables as list of appropriate size with default
> IM STUCK HERE... HOW DO I DYNAMICALLY CONVERT THE LIST OF VARIABLE NAMES
> TO VARIABLES OF TYPE LIST
>
> # Execute the command and all your variables are populated ...
> exec(cmd)
>
>
> Thanks,
>
>
>
>
>
> > Thanks! This is helpful.. I like the RE approach as it's conceivable to
> > write a function...
> >
> > On 10/27/07, Aditya Lal <[EMAIL PROTECTED] > wrote:
> > >
> > > You can source the file in python provided that you make it python
> > > friendly:-
> > >
> > > STN_id[1]='AAA' instead of STN_id[1]=AAA
> > > ...
> > >
> > >
> > > ---
> > > import re
> > > # Read the file
> > > fd = open('sitelocations')
> > > lines = fd.readlines()
> > > fd.close()
> > >
> > >
> > > # Make it python friendly: put all values in 'single quotes'
> > > cmd = '\n'.join([re.sub( r'^([^=]+)=(.*)$', r"\1='\2'", v) for v in
> > > lines])
> > >
> > >
> > > # Create variables as list of appropriate size with default values
> > > (assuming 0)
> > > max = 5
> > > STN_id, STNlat, STNlon, STNelv = [0]*max, [0]*max, [0]*max, [0]*max
> > >
> > >
> > > # Execute the command and all your variables are populated ...
> > > exec(cmd)
> > >
> > >
> > > ---
> > > Not sure if this is a better way :) But atleast it will make the file
> > > sitelocations order invariant - implies you can interchange the lines
> > > without breaking the logic.
> > >
> > >
> > > Caveat - list in python starts at 0 index so STN_id[1] is not the
> > > first element but the second element. But you can filter unwanted items 
> > > from
> > > the list if you want as in -
> > > [ x for x in STN_id if x != 0 ]
> > >
> > >
> > > HTH
> > > Aditya
> > >
> > >  On 10/27/07, John < [EMAIL PROTECTED] > wrote:
> > >
> > > >  I have a file sitelocations:
> > > >
> > > > STN_id[1]=AAA
> > > > STNlat[1]=58.80
> > > > STNlon[1]=17.40
> > > > STNelv[1]=20
> > > > STN_id[2]=BBB
> > > > STNlat[2]=42.45
> > > > STNlon[2]=25.58
> > > > STNelv[2]=2925
> > > >
> > > > which in shell scripts I can simple 'source'. In Python I have to:
> > > > sitesFile=file('sitelocations','r')
> > > > sites=sitesFile.readlines()
> > > > i=0;
> > > > for l in sites:
> > > > if i==0:
> > > > STN_id.append(l.split('=')[1].strip('\n')); i+=1;
> > > > elif i==1:
> > > > STNlat.append(l.split('=')[1].strip('\n')); i+=1;
> > > > elif i==2:
> > > > STNlon.append(l.split('=')[1].strip('\n')); i+=1;
> > > > else:
> > > > STNelv.append(l.split('=')[1].strip('\n')); i=0;
> > > >
> > > > Is there a better way??
> > > >
> > > > Thanks!
> > > >
> > > >
> > > >
> > > >
> > > > --
> > > > Configuration
> > > > ``
> > > > Plone 2.5.3-final,
> > > > CMF-1.6.4,
> > > > Zope (Zope 2.9.7-final, python 2.4.4, linux2),
> > > > Five 1.4.1,
> > > > Python 2.4.4 (#1, Jul 3 2007, 22:58:17) [GCC 4.1.1 20070105 (Red Hat
> > > > 4.1.1-51)],
> > > > PIL 1.1.6
> > > >
> > > > ___

Re: [Tutor] 'source' in python or preloading variables

2007-10-27 Thread Aditya Lal
On 10/27/07, John <[EMAIL PROTECTED]> wrote:
>
> The problem is the infies are also being used in a shell scripted
> environment, they are frequently updated and cannot be changed.
>
> So ideadly I could just define a function which sourced the file, assuming
> the variable names passed in the *args list. So, yes, I know the names, they
> just haven't been set in the program. I would like the source program to
> then define them. My re is not so great, but I'm assuming the statement
> here:
>
> cmd = '\n'.join([re.sub( r'^([^=]+)=(.*)$', r"\1='\2'", v) for v in
> lines])
>
> assumes the pattern VAR[i]=variable , and then makes it Python friendly.
>
> So it would look like:
>
> my_source(fid,['STN_id','STNlat','STNlon','STNelv'])
>
> then in the program, before exec(cmd) the *args list has to be converted
> into empy lists, preparing it for the cmd. Does that make sense??
>
> Thanks!
>
>

the re expression just changes "lvalue=rvalue" to "lvalue='rvalue'". It
doesn't know whether lvalue is array or something else.

Anyway, you can initialize the variables as follows -

for v in ['STN_id', ... ] :
   exec( 'global %s ; %s = [0]*5' % (v, v))

Unfortunately these variable need to be made global for them to be visible
everywhere.


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


Re: [Tutor] More type() puzzlement

2007-10-27 Thread Aditya Lal
On 10/27/07, Dick Moores <[EMAIL PROTECTED]> wrote:
>
> Win XP, Python 2.5.1
>
> 
> #!/usr/bin/env python
> #coding=utf-8
>
> n = 100 # 10 billion
> print "type of 10 billion is", type(n)
> n = 10 # 1 billion
> print "type of 1 billion is", type(n)
>
> raw_input("press enter to continue")
>
> n = 100
> print type(n)
> while True:
>  if type(n) == long:
>  n -= 100
>  print n, type(n)
>  else:
>  break
> print n
> print type(n), 'HERE'
> ==
>
> As an exercise in using type() I was thinking I could use it to begin
> to find where (without looking it up) a long becomes an int. I show
> that the boundary is somewhere between 10 billion and 1 billion. But
> the above script never ends--never gets to 'HERE'.
>
> Here's part of the output:
>
> 600 
> 500 
> 400 
> 300 
> 200 
> 100 
> 0 
> -100 
> -200 
> -300 
> -400 
> -500 
> -600 
>
> Note that it shows even 1 million and 0 to be longs, whereas
> >>> type(100)
> 
> >>> type(0)
> 
> >>>
>
> What's going on?
>
> Thanks,
>
> Dick Moores
>
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>

Hi Dick,
I would expect that a type change will happen if there is a need. Hence if
type(n) is already long it does not have to get converted to int to
accommodate something small.

I changed your program to increase from 1B to 10B and the results are as
expected :)

 - your old code

n = 10  # 1 billion
print type(n)
while n < 100 :  # 10 billion
if type(n) == int:
n += 100
print n, type(n)
else :
break

 - your old code

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


Re: [Tutor] 'source' in python or preloading variables

2007-10-27 Thread Aditya Lal
On 10/27/07, John <[EMAIL PROTECTED]> wrote:
>
> Note, i need the ns+1 because the 'source files are not zero indexed.
>
> On 10/27/07, John <[EMAIL PROTECTED] > wrote:
> >
> > Here's where I am:
> >
> >
> > def source(filename, vList):
> >  """ takes a file object and a list of variables as input """
> >  import re
> >  # Read the file
> >  fid=open(filename,'r')
> >  lines = fid.readlines()
> >  fid.close()
> >  #how many variables
> >  ns=len(lines)/len(vList)
> >  #predefine the varibles
> >  for v in vList:
> >   exec( 'global %s ; %s = [0]*(ns+1)' % (v, v))
> >
> >  # Make it python friendly: put all values in 'single quotes'
> >  cmd = '\n'.join([re.sub( r'^([^=]+)=(.*)$', r"\1='\2'", v) for v in
> > lines])
> >  exec(cmd)
> >  for v in vList:
> >   exec( '%s=%s[1:]' % (v,v))
> >
> > source('infile.py',['files','nfiles','nreleases'])
> >
> > print files
> > print nreleases
> > print nfiles
> >
> >
> >
> > But oddly, my output is:
> >
> > [0, 'ASP_200603', 'ASP_200604', 'ASP_200605']
> > [0, '248', '240', '248']
> > [0, '3', '3', '3']
> >
> >
> >
> > So, I am not properly getting rid of the list[0], is it something with
> > the 'global' nature of the vairables... it looks like it's only changing
> > locallly in my source function.
> >
>
>
>
> --
> Configuration
> ``
> Plone 2.5.3-final,
> CMF-1.6.4,
> Zope (Zope 2.9.7-final, python 2.4.4, linux2),
> Five 1.4.1,
> Python 2.4.4 (#1, Jul 3 2007, 22:58:17) [GCC 4.1.1 20070105 (Red Hat
> 4.1.1-51)],
> PIL 1.1.6
>

I think you need to define the variable global again otherwise it will
re-assign the object in local space.

exec( "global %s ; %s = %s[1:]" % (v,v,v) )

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


Re: [Tutor] question re type()

2007-10-30 Thread Aditya Lal
On 10/29/07, Kent Johnson <[EMAIL PROTECTED]> wrote:
>
> Aditya Lal wrote:
> > or use types module
> >
> > import types
> >
> > if type(n) == types.IntType or type(n) == types.LongType :
> > blah!
>
> A few notes:
> - If you look at types.py, you find
> IntType = int
> LongType = long
>
> and so on for all the built-in types, so there is no need or advantage
> to importing types vs
>if type(n) == int
>
> - Common Python practice is to prefer the least restrictive type check
> possible. For Dick's specific case it doesn't matter, but I generally
> use isinstance() instead of checking for a specific type. The difference
> is that isinstance() is true for subtypes as well as the named type. You
> can also pass a tuple of types to isinstance() so you can say
>if isinstance(n, (int, long))
>
> Kent
>
>
I completely agree that the check " type(n) == int " is very intuitive and
simple. Its just that there are many more types that the basic ones and
'types' module provide a "consistent" way for checking for types. As an
example - consider a function :
def execMyFun( f ) :
   if type(f) == types.GeneratorType :
  return f.next()
   elif type(f) == types.FunctionType :
  return f()
   else :
  raise Exception("Invalid type for f : " + type(f) )

Here types module came to the rescue which otherwise I would have written
using exception handling. *Well ! if you have a cleaner solution do let me
know.*


BTW, isinstance is cool :) as it checks for all subclasses as well - didn't
think of that.


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


Re: [Tutor] perplexing error with shelve REVISED

2007-10-30 Thread Aditya Lal
On 10/31/07, Orest Kozyar <[EMAIL PROTECTED]> wrote:
>
> > Please post the entire traceback (omitting duplicate lines).
>
> Sorry, I should have included the traceback.  I've revised the sample
> script
> so that it generates the traceback when run.  The sample script is at the
> very bottom of this email.
>
> ### SCRIPT OUTPUT ###
> [kozyar]:~$ python example.py
>
> Successfully retrieved and parsed XML document with ID 16842423
> Successfully shelved XML document with ID 16842423
> Successfully retrieved and parsed XML document with ID 16842422
>
> Traceback (most recent call last):
>   File "example.py", line 30, in 
> data[badkey] = doc
>   File "/usr/lib64/python2.5/shelve.py", line 123, in __setitem__
> p.dump(value)
>
> RuntimeError: maximum recursion depth exceeded
>
> Exception exceptions.RuntimeError: 'maximum recursion depth exceeded' in
>  }> ignored
>
>
> ### START SCRIPT ###
> import urllib, shelve
> from xml.dom import minidom
>
> baseurl = 'http://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi?'
>
> params = {
> 'db':   'pubmed',
> 'retmode':  'xml',
> 'rettype':  'medline'
> }
>
> badkey = '16842422'
> goodkey = '16842423' #or just about any other ID
>
> data = shelve.open('data.tmp', writeback=True)
>
> params['id'] = goodkey
> url = baseurl + urllib.urlencode(params)
> doc = minidom.parseString(urllib.urlopen(url).read())
> print 'Successfully retrieved and parsed XML document with ID %s' %
> goodkey
> data[goodkey] = doc
> print 'Successfully shelved XML document with ID %s' % goodkey
>
> params['id'] = badkey
> url = baseurl + urllib.urlencode(params)
> doc = minidom.parseString(urllib.urlopen(url).read())
> print 'Successfully retrieved and parsed XML document with ID %s' % badkey
> data[badkey] = doc
> #Will fail on the above line
> print 'Successfully shelved XML document with ID %s' % badkey
>
>
The program worked fine for me (python 2.5.1 - stackless on Mac OSX). Can
you provide details about your platform (python version, OS, etc.) ?
-- 
Aditya
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] question re type()

2007-10-31 Thread Aditya Lal
On 10/31/07, Kent Johnson <[EMAIL PROTECTED]> wrote:
>
> Aditya Lal wrote:
> > On 10/29/07, *Kent Johnson* <[EMAIL PROTECTED] <mailto:[EMAIL PROTECTED]>>
> wrote:
>
> > - Common Python practice is to prefer the least restrictive type
> check
> > possible.
>
> > I completely agree that the check " type(n) == int " is very intuitive
> > and simple. Its just that there are many more types that the basic ones
> > and 'types' module provide a "consistent" way for checking for types.
>
> Yes, for some types it is easiest to import types and use its
> definitions. Whether to use types.IntegerType or int is a matter of
> preference, I suppose.
> > As
> > an example - consider a function :
> >
> > def execMyFun( f ) :
> >if type(f) == types.GeneratorType :
> >   return f.next()
> >elif type(f) == types.FunctionType :
> >   return f()
> >else :
> >   raise Exception("Invalid type for f : " + type(f) )
> >
> > Here types module came to the rescue which otherwise I would have
> > written using exception handling. /Well ! if you have a cleaner solution
> > do let me know./
>
> You probably should write this using exception handling. The least
> restrictive type check is to check for the specific operations you need,
> rather that checking for a type that supports the operation. This can be
> done with preflight checks - known as Look Before You Leap - or by
> trying an operation and catching exceptions in case of failure, known as
> Easier to Ask Forgiveness than Permission.
>
> In this case, it seems that if f implements the iterator protocol then
> you want the next item and if f is callable then you want to just call
> it. In both cases checking for specific operations or trying the
> operation and catching any exception will allow a wider range of
> parameters. For example, next() is meaningful for generators, iterators
> on built-in types, user-defined iterators (defined with classes).
> In [129]: import types
> In [130]: i=iter([1])
> In [131]: type(i)
> Out[131]: 
> In [132]: type(i)==types.GeneratorType
> Out[132]: False
> In [133]: isinstance(i, types.GeneratorType)
> Out[133]: False
> In [134]: i.next
> Out[134]: 
>
> Function call is valid for functions, bound methods, and instances of
> any class that defines a __call__() method.
>
> Here is a less restrictive LBYL implementation of your function:
> def execMyFun( f ) :
> if hasattr(f, 'next') and callable(f.next):
>return f.next()
> elif callable(f):
>return f()
> else :
>raise Exception("Invalid type for f : " + type(f) )
>
> Here in an EAFP implementation:
> def execMyFun( f ) :
> try:
>return f.next()
> except AttributeError:
>pass
>
> try:
>return f()
> except TypeError:
>pass
> raise Exception("Invalid type for f : " + type(f) )
>
> I think I prefer the LBYL version here, it allows the same values for f
> and it won't hide AttributeErrors and TypeErrors raised by calling
> f.next() or f().
>
> Finally you should probably raise TypeError which is "raised when an
> operation or function is applied to an object of inappropriate type."
>
> Kent
>
>
Hey! I really liked LBYL version ... it matches exactly what I intended. And
yeah! I should raise TypeError instead of Exception. Thanx :)

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


Re: [Tutor] repeated times

2007-11-04 Thread Aditya Lal
On 11/4/07, Thorsten Kampe <[EMAIL PROTECTED]> wrote:
>
> * linda.s (Sun, 4 Nov 2007 01:39:46 -0800)
> > On Nov 2, 2007 1:03 AM, ALAN GAULD <[EMAIL PROTECTED]> wrote:
> > > > > >I want to run an .exe file and get the output many times.
> > > >> Given that I know that you know about loops I have to
> > > >> ask what you see as the problem?
> > > >
> > > >I want to run it many times and export all the output to a text file.
> > >
> > > OK, Do you mean you want to run the program multiple times
> > > but put the output in the same file?
> >
> > Yes. For example, I want to run the exe file one hundred times and
> > save all the results into one file.
> > Is there any example code to do that?
>
> There's no reason to do that in Python. You should use a batch or
> shell script for that. If you really insist on using Python then look
> at the subprocess module...
>
> Thorsten
>
On Unix, you can execute "script " on the command prompt. This
will create a new session in which you execute the program as many times.
After you are done press ^D to come out of session. Everything of that
session will be saved in the file .

On Windows, you can probably build something like "script" in python. BTW,
does your executable takes any user inputs ?

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


[Tutor] Swapping variables ...

2007-11-09 Thread Aditya Lal
 After quizzing newbies in C on swapping without 3rd variable, I found this
to be really *cool* construct to swap :)
x = 10
y = 20
x,y = y,x

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


Re: [Tutor] parsing an array

2007-11-12 Thread Aditya Lal
On Nov 13, 2007 8:29 AM, sith . <[EMAIL PROTECTED]> wrote:

> a = [[0,1,2,3,4,5],[1,2,3,4,5,6]]
> You cannot modify the same array when you are looping through it. You have
> to loop through the copy of the contents :- a[:].
>
> # Untested code
> for i in a[:]: # You are looping through the copy of contents
>
> # I'm new I'm going to try and explain my understanding of this code; pls
> correct if wrong
> # i[0] is [0,1,2,3,4,5] and i[1] is the other
> # the loop first goes to the list on the left then goes to the list on the
> right
>
>for j in i:
>
> #each element in the sublist is now evaluated
> # first 0 in i[0] then 1 in i[1] then back to 1 in i[0] and then to 2 in
> i[1]- is this right?
># implement your logic with j
>if j < i[0]: # or any dynamic conditional check.
>
> the first time this loops,
> 0 in the first list or i[0] is evaulated against itself
> what is the next j value for the next loop?
>a[i][j] = j <- don't understand this bit
>
>
>
> Does this help you?
>
> I've looked on the net as well as my book (python dummies), but can't find
> an explantion for nested for loops in nested lists.  Would it be possible to
> explain?  Thank you.
>
> --
>
>
Not sure but it looks like you want to iterate over an array of array (using
C syntax).

for i in a[:] will make i point to the elements of the list and not its
index. For getting the index you need to use enumerate or just range(len(a))
as in :

for i in range(len(a)) :
# now you can access element as a[i]
for j in range(len(a[i])) :
# now you can access the inner array element as a[i][j]
a[i][j] *= 2

You can use this to modify the array content as well. But do exercise
caution in case of length change.

Or have I completely misunderstood your question ?

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


Re: [Tutor] parsing an array

2007-11-13 Thread Aditya Lal
On Nov 13, 2007 7:06 PM, bob gailer <[EMAIL PROTECTED]> wrote:

> Aditya Lal wrote:
> > [snip]
>
> > for i in a[:] will make i point to the elements of the list
> To be more precise:
> a[:] is a copy of the list
> the for statement assigns each list element in turn to i. Assign is not
> exactly the same as point.
>
>
Yup! Bob is right. I just cut-paste the example from previous mail. It
should be for i in a :
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] parsing an array

2007-11-15 Thread Aditya Lal
On Nov 15, 2007 12:37 PM, sith . <[EMAIL PROTECTED]> wrote:

> a = [[1,2],[3,1.5],[5,6]]
> for i in a:
> print i
> if i[1]>i[0]:
> print "second index is larger"
> else:
> print "second index is smaller"
> [1, 2]
> second index is larger
> [3, 1.5]
> second index is small
> er
> [5, 6]
> second index is larger
>
> What I'd like do is compare if 1.5 in i[1] is greater than 2 in i[0];
> for time series, t(1)>t(0) and interate through the entire list - is 6 in
> i[2]>than 1.5 in i[1] etc?
> Since the data is in columns in a text file or csv, I can't put 1.5 in the
> same sublist as 2, and 6 in the same sublist as 1.5 to make things
> easier.  What can I do?
> Thank you for your help.
>
> --
>
>
for i in range(1,len(a)) :
  if a[i][1] > a[i-1][1] :
 print 'greater !!' # or whatever you want

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


Re: [Tutor] lstrip removes '/' unexpectedly

2007-12-03 Thread Aditya Lal
On Dec 3, 2007 4:29 PM, Ricardo Aráoz <[EMAIL PROTECTED]> wrote:

> Danny Yoo wrote:
> >> Hello:
> >> I'm seeing some strange behavior with lstrip operating
> >> on string representations of *nix-style file paths
> >> Example:
> >>>>> s = '/home/test/'
> >>>>> s1 = s.lstrip('/home')
> >>>>> s1
> >> 'test/'   ## '/test/' was expected! '/' was unexpectedly removed
> >> Any comments or corrective measures are welcome
> >
> >
> >
> > Hi Tim,
> >
> > Here's another example to help you see what's going on:
> >
> > ##
> >>>> s = '/home/test/'
> >>>> s1 = s.lstrip('/ehmo')
> >>>> s1
> > 'test/'
> > ##
> >
> > Take a closer look at the documentation of lstrip, and you should see
> that
> > what it takes in isn't treated as a prefix: rather, it'll be treated as
> a
> > set of characters.
> >
>
> But then the real bug is why does it not strip the trailing '/' in
> 'test/' or the 'e' that is in your set?
>
>
Thats because you called lstrip() and not strip() which will strip only from
left side.

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


Re: [Tutor] run in "deamon" mode?

2008-01-10 Thread Aditya Lal
On Jan 10, 2008 11:11 AM, Allen Fowler <[EMAIL PROTECTED]> wrote:

> Hello,
>
> How can a make a python script run in "deamon mode"? (on a linux box)
>
> That is, I want to run the program via "python myfile.py" and have it drop
> me back to the command line.  The program should continue running until I
> kill it via it's PID, the machine shuts down, or the program itself decides
> to shutdown.   It should _not_  die when I simply log-out, etc.
>
> Is there a standard library module to help with this?
>
> -- Thank you
>
>
>
>
The simplest way to achieve this is as follows :
$ nohup python myfile.py &
Otherwise you need to become daemon from inside the program. fork(),
setsid(), etc. - the normal C language method for becoming a daemon..

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


Re: [Tutor] os.system() problem

2008-02-05 Thread Aditya Lal

On 04/02/08 10:42 PM, "Eric Brunson" <[EMAIL PROTECTED]> wrote:

> dave selby wrote:
>> Hi all,
>> 
>> I am not sure if this is a Python or bash issue :).
>> 
>> In bash if I execute 'motion' with the following ...
>> 
>> [EMAIL PROTECTED]:~/.kde/share/apps/kmotion$ motion &> /dev/null &
>> [1] 10734
>> [EMAIL PROTECTED]:~/.kde/share/apps/kmotion$
>> 
>> I get what I expect, a background job, however if I execute it from
>> Python with an os.system ...
>> 
>> os.system('motion &> /dev/null &')
>>   
> 
> This happens because &> and & are shell constructs, they are bash
> specific shell syntax for "redirect stderr and stdout" and "put this job
> in the background".  But os.system simply calls the OS's "system(3)"
> call, which under linux calls "/bin/sh".  If you read the docs for bash,
> calling it as "sh" results in POSIX compliance mode and falls back to
> Bourne shell's less rich syntax, so it doesn't understand the "&>"
> construct.  If I had to guess at the parsing, I imagine it runs the
> "motion &" as one process in the background, then "> /dev/null &" as a
> second.
> 
> Long story short, look at this page:
> http://docs.python.org/lib/node537.html
> 
>> I get tons of output to the BASH shell ...
>> 
>> [0] Processing thread 0 - config file /etc/motion/motion.conf
>> [0] Processing config file /etc/motion/motion.1.conf
>> [0] Processing config file /etc/motion/motion.2.conf
>> [1] Thread is from /etc/motion/motion.1.conf
>> [2] Thread is from /etc/motion/motion.2.conf
>> [1] Thread started
>> [2] Thread started
>> [1] File of type 2 saved to: /var/lib/motion/20080203/01/tmp/175253.jpg
>> ...etc ...
>> 
>> I just can't work out why this is happening & how to stop it ?. Any ideas ?
>> 
>> Cheers
>> 
>> Dave
>> 
>> 

Try os.system('bash motion &> /dev/null &')


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


Re: [Tutor] Problem with installing python

2015-06-05 Thread Aditya Shaw
I was trying to install Python 2.7 on my Windows 8.1(x64) PC and got
the following error:
"There is a problem with this Windows Istaller Package.A DLL required
for this install to complete could not be run.Contact your support
personnel or package vendor."
Please help!
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] Help with a task

2018-04-12 Thread Aditya Mukherjee
Hello, I'm relatively new to python and have been given a task for
university, and would greatly appreciate if anyone could help me basically
just get started because as of now I am completely clueless and have no
idea what to do. I don't really know who to ask, but anything would be of
assistance.


I feel like I understand the basics of functions such as lists,
if/elif etc. but can't really comprehend what to do with anything involving
more than the use of simple functions.


Helping me getting started and just understanding what I actually need to
do would be vastly helpful, as I've heard from other students that they
have over 200 lines. :)


I've attached the premise of what the task is asking for, due in 2 days.


Thank you in advance


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