Re: [Tutor] Str method

2012-11-05 Thread Alan Gauld

On 05/11/12 01:52, Oscar Benjamin wrote:

On 5 November 2012 01:45, Ashley Fowler  wrote:

I'm trying to  initialize a list to several elements using the string
method. I have some idea that you use a for loop I suppose...


It will help if you work on getting your terminology clearer.
Computing is a precise art, it has very specific meanings for things.
From your previous thread I assume you mean that you want break a list 
down into its individual parts so that you can convert them to strings?


To get the individual parts you do indeed need a loop - a for loop is 
probably best.


To convert them to strings use the str() type convertor on each
part.

for part in myList:
myString = str(part)

But assuming this is still part of your previous exercise you really 
want to create one long string so you probably want the last line to 
look like


myString = myString + str(part)

There are more efficient ways of doing that but they might confuse you 
so I'll leave it with string addition for now.


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

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


Re: [Tutor] serial to parallel

2012-11-05 Thread Bala subramanian
Friends,
In the previous mail there was an "mistake" i was not aware of. So pls
dnt get upset.

For frame in trajectory-A:
> cunt= str(frame.time)

It is count =str(frame.time). A counter to find frame number.

Thanks joel for letting me to know it.

Bala

On Mon, Nov 5, 2012 at 11:46 AM, Bala subramanian
 wrote:
> Friends,
> I use a python package to analyse molecular trajectories. For those
> not familiar, I have described the the problem below.
> I have two trajectories A,B. Each trajectory has a collection of
> frames. A frame is a numpy array.
> For frame in trajectory-A:
> cunt= str(frame.time)
> function(trajectoryB, frame, outfile=cunt+'.txt')
> process all .txt files
>
> The function is described in the package that I use. It also has a
> built-in counter for each frame.
> I want to convert this to a parallel code in the following way. Each
> processor can take one frame from trajectory-A and applies the
> function and write the corresponding output file.
> This is the first time I am trying such parallelism. I would
> appreciate your guidance on how I can do it. The original code is
> pasted below.
> ---
> #!/usr/bin/env python
> import MDAnalysis
> from MDAnalysis.analysis.align import rmsd,fasta2select, rms_fit_trj
> import argparse
> import numpy as np
>
> parser = argparse.ArgumentParser(description=info)
> # a series of  parser.add_argument definitions
>
> U1=MDAnalysis.Universe(args.rtop,args.rtrj)   # open  trajectory-A
> U2=MDAnalysis.Universe(args.ttop,args.ttrj)   # open   trajectory-B
>
>
> for fr in U1.trajectory:
> nd='%0*d' % ( 5,fr.frame)
> rms_fit_trj(U2,U1.selectAtoms('all'),rmsdfile=str(nd) + '.rmsd')
>
> Thanks in advance,
> Bala



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


Re: [Tutor] please give me feedback - linux & virtual machine python script

2012-11-05 Thread eryksun
On Sun, Nov 4, 2012 at 1:43 AM,   wrote:
>
> There are more features I like to implement but It would be nice to get
> constructive feedback from the community.
> Here is the code http://pastebin.com/R8b8M5PR

On line 104 you print an error message to stdout instead of stderr and
then call sys.exit(1). You can print the message to stderr and set the
return code to 1 at the same time:

sys.exit("Pynotify Python module does not seem to be installed")

On line 131 you're checking if an object equals None. This isn't
idiomatic. None is a singleton, so when you use None as a sentry or
default option, it's faster and more reliable to test identity (is, is
not) instead of equality or boolean value. Here's a toy example where
testing equality fails:

>>> class Equal(object):
... def __eq__(self, other):
... return True
...
>>> Equal() == None
True
>>> Equal() is None
False

On line 148 you're not taking advantage of os.getenv's default return
value of None. Also, you're manually splitting on '\n' instead of
using the splitlines() method:

uris = os.getenv("NAUTILUS_SCRIPT_SELECTED_URIS")
if uris is not None:
return uris.splitlines()

On line 166 you use a list comprehension to replace some text in uris
and then immediately iterate over the result in a for loop. Just move
the replace operation into the loop:

uris = self.nautilus()
for uri in uris:
uri = uri.replace(self._home_path, SHARE_NAME)

Lines 249 and 259 should be "elif" statements. Also, I doubt the
following does what you think it does:

while not vmc.vbox_is_running() and range(45):

Each evaluation of the expression creates a new range(45) list. Did
you want a counter here?
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] serial to parallel

2012-11-05 Thread Dave Angel
On 11/05/2012 06:53 AM, Bala subramanian wrote:
> Friends,
> In the previous mail there was an "mistake" i was not aware of. So pls
> dnt get upset.
>
> For frame in trajectory-A:
>> cunt= str(frame.time)
> It is count =str(frame.time). A counter to find frame number.
>
> Thanks joel for letting me to know it.
>
> Bala
>
> On Mon, Nov 5, 2012 at 11:46 AM, Bala subramanian
>  wrote:
>> Friends,
>> I use a python package to analyse molecular trajectories. For those
>> not familiar, I have described the the problem below.
>> I have two trajectories A,B. Each trajectory has a collection of
>> frames. A frame is a numpy array.
>> For frame in trajectory-A:
>> cunt= str(frame.time)
>> function(trajectoryB, frame, outfile=cunt+'.txt')
>> process all .txt files
>>
>> The function is described in the package that I use. It also has a
>> built-in counter for each frame.
>> I want to convert this to a parallel code in the following way. Each
>> processor can take one frame from trajectory-A and applies the
>> function and write the corresponding output file.
>> This is the first time I am trying such parallelism. I would
>> appreciate your guidance on how I can do it. The original code is
>> pasted below.
>> ---
>> #!/usr/bin/env python
>> import MDAnalysis
>> from MDAnalysis.analysis.align import rmsd,fasta2select, rms_fit_trj
>> import argparse
>> import numpy as np
>>
>> parser = argparse.ArgumentParser(description=info)
>> # a series of  parser.add_argument definitions
>>
>> U1=MDAnalysis.Universe(args.rtop,args.rtrj)   # open  trajectory-A
>> U2=MDAnalysis.Universe(args.ttop,args.ttrj)   # open   trajectory-B
>>
>>
>> for fr in U1.trajectory:
>> nd='%0*d' % ( 5,fr.frame)
>> rms_fit_trj(U2,U1.selectAtoms('all'),rmsdfile=str(nd) + '.rmsd')
>>
>> Thanks in advance,
>> Bala
>
>

Before you spend too much energy on this, I'd suggest that you'll
probably see a substantial slowdown trying to write the two files in
parallel.  Unless the calculations are extensive that actually format
the data for writing.

On the other hand, if the calculations dominate the problem, then you
probably want to do multiprocessing to get them to happen in parallel. 
See the recent thread "using multiprocessing efficiently to process
large data file"

Just be sure and do some measuring before spending substantial energy
optimizing.

-- 

DaveA

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


Re: [Tutor] serial to parallel

2012-11-05 Thread wrw
On Nov 5, 2012, at 8:44 AM, Dave Angel  wrote:

> On 11/05/2012 06:53 AM, Bala subramanian wrote:
>>> 

[Huge byte]


>>> Thanks in advance,
>>> Bala
>> 
>> 
> 
> Before you spend too much energy on this, I'd suggest that you'll
> probably see a substantial slowdown trying to write the two files in
> parallel.  Unless the calculations are extensive that actually format
> the data for writing.
> 
> On the other hand, if the calculations dominate the problem, then you
> probably want to do multiprocessing to get them to happen in parallel. 
> See the recent thread "using multiprocessing efficiently to process
> large data file"
> 
> Just be sure and do some measuring before spending substantial energy
> optimizing.
> 
> -- 
> 
> DaveA
> 

Assuming, after you take Dave's advice, that you still want to try parallel 
processing.  Take a quick look at:

 
http://docs.python.org/2/library/multiprocessing.html?highlight=multiprocessing#multiprocessing

and in particular at section 16.6.1.5 on using a pool of workers.  This might 
provide a simple clean way for you to hand off the work.

-Bill

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


[Tutor] why different result from two similar ways

2012-11-05 Thread Frank Pontius
Hello,
I have code that works.  Then tried to move some of it into function
IncrementAndRebuildInput, then result changes, I no longer have same result
as when code in function was inline - why?

(Function version way below)

Inline version: (this correctly adds 1 to all numbers in text string,
and prints it out with incremented #s):

def IsNum(string):
#print "IsNum string", string
for char in string: #checks string groupings to be all nums
if not char.isdigit():
#print "false"
return False
#print "true"
return True


def main():
text = raw_input("Type something: ")
print
if text:
print text
else:
text = "I got 432 when I counted, but Jim got 433 which is a lot for
only 6 cats, or were there 12 cats?"
print text  #string input

SplitText = text.split()#makes a list from string input
#   print SplitText
#   print "Did I print LIST?"
for index, element in enumerate(SplitText):
if IsNum(element):  #looks@every list element,
checks for #
num = int(element) + 1  #if #, increments it
#   print num
#   print "Bkpt8"
SplitText[index] = str(num)
else:
pass
#print "bkpt9"

 #   NewString = " ".join(SplitText)
print "bkpt10"
print
print SplitText
print
print " ".join(SplitText)
print
print "END"
main()

OUTPUT:::
>>>
>>> 
Type something: 

I got 432 when I counted, but Jim got 433 which is a lot for only 6 cats, or
were there 12 cats?
bkpt10

['I', 'got', '433', 'when', 'I', 'counted,', 'but', 'Jim', 'got', '434',
'which', 'is', 'a', 'lot', 'for', 'only', '7', 'cats,', 'or', 'were',
'there', '13', 'cats?']

I got 433 when I counted, but Jim got 434 which is a lot for only 7 cats, or
were there 13 cats?

END
>>>


Function version way below: (This version does not produce the
same output (w/numbers incremented by 1)

def IsNum(string):
#print "IsNum string", string
for char in string: #checks string groupings to be all nums
if not char.isdigit():
#print "false"
return False
#print "true"
return True



def IncrementAndRebuildInput(text):
newtext = text.split()#makes a list from string input
print newtext
#   print "Did I print LIST?"
for index, element in enumerate(newtext):
if IsNum(element):  #looks@every list element,
checks for #
num = int(element) + 1  #if #, increments it
print num
#   print "Bkpt8"
newtext[index] = str(num)
print newtext
print "NOWHERE"
else:
pass
#print "bkpt9"
print newtext # contains new list w/#'s incremented by 1
print "Point6"
return newtext


def main():
text = raw_input("Type something: ")
print
if text:
print text
else:
text = "I got 432 when I counted, but Jim got 433 which is a lot for
only 6 cats, or were there 12 cats?"
print text  #string input

IncrementAndRebuildInput(text)

#   print "bkpt10"
print
print text#  **  Placing previous inline
code into function changes result - what am I doing wrong?**
print "Point7"
print "".join(text)
print
print "END"
main()

OUTPUT:::
>>>
>>> 
Type something: 

I got 432 when I counted, but Jim got 433 which is a lot for only 6 cats, or
were there 12 cats?
['I', 'got', '432', 'when', 'I', 'counted,', 'but', 'Jim', 'got', '433',
'which', 'is', 'a', 'lot', 'for', 'only', '6', 'cats,', 'or', 'were',
'there', '12', 'cats?']
433
['I', 'got', '433', 'when', 'I', 'counted,', 'but', 'Jim', 'got', '433',
'which', 'is', 'a', 'lot', 'for', 'only', '6', 'cats,', 'or', 'were',
'there', '12', 'cats?']
NOWHERE
434
['I', 'got', '433', 'when', 'I', 'counted,', 'but', 'Jim', 'got', '434',
'which', 'is', 'a', 'lot', 'for', 'only', '6', 'cats,', 'or', 'were',
'there', '12', 'cats?']
NOWHERE
7
['I', 'got', '433', 'when', 'I', 'counted,', 'but', 'Jim', 'got', '434',
'which', 'is', 'a', 'lot', 'for', 'only', '7', 'cats,', 'or', 'were',
'there', '12', 'cats?']
NOWHERE
13
['I', 'got', '433', 'when', 'I', 'counted,', 'but', 'Jim', 'got', '434',
'which', 'is', 'a', 'lot', 'for', 'only', '7', 'cats,', 'or', 'were',
'there', '13', 'cats?']
NOWHERE
['I', 'got', '433', 'when', 'I', 'counted,', 'but', 'Jim', 'got', '434',
'which', 'is', 'a', 'lot', 'for', 'only', '7', 'cats,', 'or', 'were',
'there', '13', 'cats?']
Point6

I got 432 when I counted, but Jim got 433 which is a lot for only 6 cats, or
were there 12 cats?
Point7
I got 432 when I counted, but Jim got 433 which is a lot for only 6 cats, or
were there 12 cats?

END
>>> 
>>>

[Tutor] help on dic creation

2012-11-05 Thread Brayden Zhao
hello! 

I am doing my homework now and I am kinda stuck. Could any of you help me out? 


Here is the homework problem:

 fieldict(filename) reads a file in DOT format and 
  returns a dictionary with the DOT CMPLID, converted to an
  integer, as the key, and a tuple as the corresponding value
  for that key.  The format of the tuple is:
 (manufacturer, date, crash, city, state)
  where these tuple items have the following types:
 manufacturer -- this comes from the MFR_NAME field in the DOT format 
 date -- this comes from the FAILDATE field in the DOT format, 
 but converted to a Python datetime.date object
 crash -- this comes from the CRASH field in the DOT format, 
 but converted to a Python bool type (True for a crash)
 city -- comes from the CITY field in the DOT format
 state -- comes from the STATE field in the DOT format
should return: fieldict("DOT500.txt")[82]
  ('FORD MOTOR COMPANY', datetime.date(1995, 1, 1), False, 'MARBLE HEAD', 'MA')


and here are parts of the data:

1   958164  TOYOTA MOTOR CORPORATIONTOYOTA  LAND CRUISER1994
19941223N   0   0   SERVICE BRAKES, 
HYDRAULIC:ANTILOCK  ARNOLD  CA  JT3DJ81W8R0 19950103
19950103ABS SYSTEM FAILURE, AT 20MPH.  TT   EVOQ


V   
2   958156  TOYOTA MOTOR CORPORATIONTOYOTA  PASEO   1994Y   
19941226N   0   0   PARKING BRAKE:CONVENTIONAL  SAN 
JOSECA  JT2EL45U5R0 19950103199501031   
PARKED ON FLAT SURFACE EMERGENCY BRAKING ENGAGED VEHICLE ROLLED REARWARD.  
TT   EVOQ   

 V   
3   958124  TOYOTA MOTOR CORPORATIONTOYOTA  COROLLA 1994Y   
19941128N   0   0   AIR BAGS:FRONTALPHOENIX 
AZ  1995010319950103UPON FRONTAL 
COLLISION, AIR BAG FAILED TO DEPLOY. VEHICLE CLASSIFIED AS TOTALED. PLEASE 
DESCRIBE DETAILS.  TT   EVOQ

V   
4   958122  NISSAN NORTH AMERICA, INC.  NISSAN  MAXIMA  1994
19950103N   0   0   SUSPENSION  TUCSON  AZ  
JN1HJ01F4RT 1995010319950103THE STRUT WAS 
BAD THERE IS A NOISE ON THE PASSENGER SIDE DOOR AND THE ENGINE LIGHT 
MALFUNCTION.  TT EVOQ   

 V   
5   958122  NISSAN NORTH AMERICA, INC.  NISSAN  MAXIMA  1994
19950103N   0   0   ENGINE AND ENGINE COOLING:ENGINE
TUCSON  AZ  JN1HJ01F4RT 1995010319950103
THE STRUT WAS BAD THERE IS A NOISE ON THE PASSENGER SIDE DOOR AND THE 
ENGINE LIGHT MALFUNCTION.  TT EVOQ  

  V 
  



Here is my code and I dont know why my code is only reading the 500th line of 
the file. Thanks for your help! 


import datetime
def boolean(S):
  if S=="Y":
return True
  return False

def fieldict(filename):
  D={}
  with open(filename) as FileObject:
for lines in FileObject:
  linelist=lines.split('\t')
  Key=linelist[0]
  ValCity=(linelist[12]).strip()
  ValState=linelist[13]
  ValOne=linelist[2]
  ValTwo=linelist[6]
  ValThree=boolean(linelist[7])
  D={Key:(ValOne, ValTwo, ValThree, ValCity,ValState)}
  return D
print fieldict("DOT500.txt")
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Help with class example

2012-11-05 Thread Prasad, Ramit
Frank Pontius wrote:
> Sent: Saturday, October 27, 2012 12:27 PM
> To: d...@davea.name; bgai...@gmail.com
> Cc: tutor@python.org
> Subject: Re: [Tutor] Help with class example
> 
> Here ya go!
> Can't do what you want as this is a programmatic error from interrupter.  
> Only a screen shot will tell you the
> full situation.  I have class example which is to be used for our homework, 
> and I copied it into IDLE and it
> won't work, with error below.  I've tried several ways to work around this
> 
> Thanks
> Frank
> 


You would be better off trying to run this from the command
line.  The problem is the "if" and "else" lines are indented one
level too far. If you match them with the previous line
it should work just fine.

~Ramit


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


Re: [Tutor] help on dic creation

2012-11-05 Thread Brett Ritter
> Here is my code and I dont know why my code is only reading the 500th line of 
> the file. Thanks for your help!

Let me offer you some hints:

This sounds like only the last line is getting saved into the dict.
Yet your loop is clearly going over each line.  Ergo, the problem is
probably in the part where you add the line to the dict.

Focus on that part and see what is happening versus what you want to
have happening.  Double check what command you are actually giving.

On Tue, Oct 30, 2012 at 6:01 PM, Brayden Zhao  wrote:
> hello!
>
> I am doing my homework now and I am kinda stuck. Could any of you help me
> out?
>
>
> Here is the homework problem:
>
> fieldict(filename) reads a file in DOT format and
>
>   returns a dictionary with the DOT CMPLID, converted to an
>   integer, as the key, and a tuple as the corresponding value
>   for that key.  The format of the tuple is:
>  (manufacturer, date, crash, city, state)
>   where these tuple items have the following types:
>  manufacturer -- this comes from the MFR_NAME field in the DOT
> format
>date -- this comes from the FAILDATE field in the DOT format,
>but converted to a Python datetime.date object
>crash -- this comes from the CRASH field in the DOT format,
>but converted to a Python bool type (True for a crash)
>  city -- comes from the CITY field in the DOT format
>state -- comes from the STATE field in the DOT format
>
> should return: fieldict("DOT500.txt")[82]
>
>   ('FORD MOTOR COMPANY', datetime.date(1995, 1, 1), False, 'MARBLE HEAD',
> 'MA')
>
>
>
> and here are parts of the data:
>
> 1 958164  TOYOTA MOTOR CORPORATIONTOYOTA  LAND
> CRUISER   199419941223N   0   0   SERVICE 
> BRAKES, HYDRAULIC:ANTILOCK  ARNOLD
>   CA  JT3DJ81W8R0 1995010319950103
> ABS SYSTEM FAILURE, AT 20MPH.
> TTEVOQ
>   
>   V   
> 2 958156  TOYOTA MOTOR CORPORATIONTOYOTA  PASEO   1994Y   
> 19941226N   0   0   PARKING
> BRAKE:CONVENTIONALSAN JOSECA  JT2EL45U5R0 19950103
> 199501031   PARKED
> ON FLAT SURFACE EMERGENCY BRAKING ENGAGED VEHICLE ROLLED REARWARD.
> TTEVOQ
>   
>   V   
> 3 958124  TOYOTA MOTOR CORPORATIONTOYOTA  COROLLA 1994Y   
> 19941128N   0   0   AIR
> BAGS:FRONTAL  PHOENIX AZ  1995010319950103
> UPON FRONTAL COLLISION,
> AIR BAG FAILED TO DEPLOY. VEHICLE CLASSIFIED AS TOTALED. PLEASE DESCRIBE
> DETAILS.  TT  EVOQ
>   
>   V   
> 4 958122  NISSAN NORTH AMERICA,
> INC.  NISSAN  MAXIMA  199419950103N   0   0   
> SUSPENSION  TUCSON
>   AZ  JN1HJ01F4RT 1995010319950103
> THE STRUT WAS BAD THERE IS A NOISE ON
> THE PASSENGER SIDE DOOR AND THE ENGINE LIGHT MALFUNCTION.
> TTEVOQ
>   
>   V   
> 5 958122  NISSAN NORTH AMERICA,
> INC.  NISSAN  MAXIMA  199419950103N   0   0   
> ENGINE AND ENGINE
> COOLING:ENGINETUCSON  AZ  JN1HJ01F4RT 19950103
> 19950103THE STRUT WAS
> BAD THERE IS A NOISE ON THE PASSENGER SIDE DOOR AND THE ENGINE LIGHT
> MALFUNCTION.  TT  EVOQ
>   
>   V   
>
>
>
>
> Here is my code and I dont know why my code is only reading the 500th line
> of the file. Thanks for your help!
>
>
> import datetime
> def boolean(S):
>   if S=="Y":
> return True
>   return False
>
> def fieldict(filename):
>   D={}
>   with open(filename) as FileObject:
> for lines in FileObject:
>   linelist=lines.split('\t')
>   Key=linelist[0]
>   ValCity=(linelist[12]).strip()
>   ValState=linelist[13]
>   ValOne=linelist[2]
>   ValTwo=linelist[6]
>   ValThree=boolean(linelist[7])
>   D={Key:(ValOne, ValTwo, ValThree, ValC

Re: [Tutor] help on dic creation

2012-11-05 Thread Brett Ritter
FYI - Gmail's new "compose" feature makes it WAY too easy to miss
trimming the quotes. :(

On Mon, Nov 5, 2012 at 3:37 PM, Brett Ritter  wrote:
(way too much)

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


Re: [Tutor] why different result from two similar ways

2012-11-05 Thread Oscar Benjamin
On 30 October 2012 01:36, Frank Pontius  wrote:
> Hello,

Hi,

It would be good if you could remove unnecessary debug code before
posting since it makes it harder for others to read your actual code.
Also why is there an empty line between each two lines of code? I
think this makes it much harder to read the code.

>
> I have code that works.  Then tried to move some of it into function
> IncrementAndRebuildInput, then result changes, I no longer have same result
> as when code in function was inline – why?

Because you're not using the result returned by the function.

>
> Function version way below: (This version does not produce the
> same output (w/numbers incremented by 1)
>
> def IsNum(string):
>
> #print "IsNum string", string
>
> for char in string: #checks string groupings to be all nums
>
> if not char.isdigit():
>
> #print "false"
>
> return False
>
> #print "true"
>
> return True

You could always just return string.isdigit() instead of looping over
the characters in the string:

>>> s = '123'
>>> s.isdigit()
True
>>> s = '12r'
>>> s.isdigit()
False


>
>
>
> def IncrementAndRebuildInput(text):
>
> newtext = text.split()#makes a list from string input
>
> print newtext
>
> #   print "Did I print LIST?"
>
> for index, element in enumerate(newtext):
>
> if IsNum(element):  #looks@every list element,
> checks for #
>
> num = int(element) + 1  #if #, increments it
>
> print num
>
> #   print "Bkpt8"
>
> newtext[index] = str(num)
>
> print newtext
>
> print "NOWHERE"
>
> else:
>
> pass
>
> #print "bkpt9"
>
> print newtext # contains new list w/#'s incremented by 1
>
> print "Point6"
>
> return newtext

Here the function returns the created list of strings.

>
>
> def main():
>
> text = raw_input("Type something: ")
>
> print
>
> if text:
>
> print text
>
> else:
>
> text = "I got 432 when I counted, but Jim got 433 which is a lot for
> only 6 cats, or were there 12 cats?"
>
> print text  #string input
>
> IncrementAndRebuildInput(text)

The function returns a list of strings but you ignore its return
value. You need to do

  text = IncrementAndRebuildInput(text)

to actually capture the output of the function in a variable called text.

>
> #   print "bkpt10"
>
> print
>
> print text#  **  Placing previous inline
> code into function changes result – what am I doing wrong?**


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


Re: [Tutor] using python to read csv clean record and write out csv

2012-11-05 Thread Oscar Benjamin
On 2 November 2012 10:40, Sacha Rook  wrote:
>
> I have a problem with a csv file from a supplier, so they export data to csv
> however the last column in the record is a description which is marked up
> with html.
>
> trying to automate the processing of this csv to upload elsewhere in a
> useable format. If i open the csv with csved it looks like all the records
> aren't escaped correctly as after a while i find html tags and text on the
> next line/record.
>
> If I 'openwith' excel the description stays on the correct line/record?
>
> I want to use python to read these records in and output a valid csv with
> the descriptions intact preferably without the html tags so a string of text
> formatted with newline/CR where appropriate.
>
> So far I have this but don't know where to go from here can someone help me?
>
> import csv
>
> infile = open('c:\data\input.csv', 'rb')
> outfile = open('c:\data\output.csv', 'wb')
>
> reader = csv.reader(infile)
> writer = csv.writer(outfile)
>
>
> for line in reader:
> print line
> writer.writerow(line)
>

You already have a program. Does it work? If not, then what's wrong
with the output?

If you get an error message can you please show the exact error message?

> I have attached the input.csv i hope this is good form here?
>
> I know I am far from complete but don't know how to proceed :-)

It's okay to send attachments when there is a need to. It would be
good though to cut the csv file down to a smaller size before posting
it here. That's 4 MB wasting space in a lot of inboxes. Better yet,
you could copy the first three lines directly into the email so that
people can see it without needing to download the attachment.


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


Re: [Tutor] Help with OOP!

2012-11-05 Thread Oscar Benjamin
On 30 October 2012 06:56, Pete  wrote:
> I’m taking this class on python at UCSC. They said this list could help. I
> don’t’ understand OOP and I’m having a hard time understanding the “scope”
> and why the def inside class are not like function –plus I can’t get my
> c-brain around the implicit typing. It looks like the interpreter does not
> want to return a tuple… why?

If you want help understanding Python in general then you should
choose a specific question and send that to the list. Give an example
of the code that you understand and the code that you don't and
explain what you expected to happen. Then it is possible for someone
to help.

Otherwise I suggest that you read the python tutorial:

  http://docs.python.org/3/tutorial/

for version 3 or, for version 2:

  http://docs.python.org/2/tutorial/

> I don’t’ know if anybody can fix this, or offer a better solution to this
> problem.
>
> The code and assignment are attached.

I don't think anyone will be prepared to do your assignment for you
(or even to read the attachments and guess which part you are finding
difficult). If you want help you will need to ask for help with
something specific.


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


Re: [Tutor] why different result from two similar ways

2012-11-05 Thread Steven D'Aprano

On 30/10/12 12:36, Frank Pontius wrote:

Hello,
I have code that works.  Then tried to move some of it into function
IncrementAndRebuildInput, then result changes, I no longer have same result
as when code in function was inline - why?


Have you tried running it in isolation to see what it does?

When I try it, it works for me (apart from printing a lot of unnecessary
intermediate results):

py> result = IncrementAndRebuildInput("abc def 123 xyz 456")
['abc', 'def', '123', 'xyz', '456']
124
['abc', 'def', '124', 'xyz', '456']
NOWHERE
457
['abc', 'def', '124', 'xyz', '457']
NOWHERE
['abc', 'def', '124', 'xyz', '457']
Point6



Now check the returned result:

py> result
['abc', 'def', '124', 'xyz', '457']

So it certainly does increment the numbers in the string. The only
bit it doesn't do is rebuild the string, but that takes just one
minor change: instead of "return newstring" (by the way, that's false
advertising -- newstring is not a string, it is a list), use:

return ' '.join(newstring)


You also use this function:


def IsNum(string):
#print "IsNum string", string
 for char in string: #checks string groupings to be all nums
 if not char.isdigit():
#print "false"
 return False
#print "true"
 return True


You don't need it! The isdigit method doesn't only work on a single character
at a time, it works on an entire string:

py> "12345".isdigit()
True
py> "12345a".isdigit()
False




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


Re: [Tutor] Help with OOP!

2012-11-05 Thread Steven D'Aprano

On 30/10/12 17:56, Pete wrote:

I'm taking this class on python at UCSC. They said this list could help. I
don't' understand OOP and I'm having a hard time understanding the "scope"
and why the def inside class are not like function


But they are like functions. Can you explain in more detail what you don't
understand about def inside classes?



-plus I can't get my
c-brain around the implicit typing. It looks like the interpreter does not
want to return a tuple. why?


I can't answer that question because I don't know why you think you can't
return a tuple. Can you show an example of it failing?


In C, you have variables, which are typed, and values. When you declare that
"n" is an int, the C compiler can tell ahead of time that any operation you
do to n will give an int or not, and prohibit you from using n to store (say)
a string.

In Python, variable names are not typed. If you consider the name "n", Python
will not prevent you from using n to store ints one moment and strings another
moment. That's a deliberate design choice, so please don't get into an
argument about it being "better" or "worse" than the way C does it. There are
pros and cons to both.

But at any specific moment, the variable name "n" will be bound to an object,
and Python always knows what the type of the object is. So if you try to do
something to n as if it were a string, but it is actually an int, Python will
know that you can't and give you an exception (instead of crashing the
computer). For example, you can convert strings to uppercase, but not ints:


py> n = "Fred"  # n for Name
py> n.upper()
'FRED'
py> n = 42
py> n.upper()
Traceback (most recent call last):
  File "", line 1, in 
AttributeError: 'int' object has no attribute 'upper'



So the main difference in typing is that in C you get *compile-time*
type errors while in Python you get them at *run-time* instead. In both
cases, you have to write your code to avoid type errors.




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


Re: [Tutor] matplotlib question - Dates not showing up on X axis

2012-11-05 Thread Steven D'Aprano

On 06/11/12 04:42, jim schmidt wrote:

import website as website


What's website? When I try it, I get an error.

py> import website as website
Traceback (most recent call last):
  File "", line 1, in 
ImportError: No module named website


By the way, there's no need to say "import X as X". Just say "import X".



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


Re: [Tutor] matplotlib question - Dates not showing up on X axis

2012-11-05 Thread eryksun
On Mon, Nov 5, 2012 at 12:42 PM, jim schmidt  wrote:
>
> fig = figure()
>
> ax = fig.add_subplot(1,1,1)
> ax.plot_date(dates, kbSec, '-')
>
> ax.xaxis.set_major_locator(WeekdayLocator(byweekday=MO))
> ax.xaxis.set_major_formatter(DateFormatter('%m-%d'))
> fig.autofmt_xdate()
> show()

The dates have to be in ordinal form (i.e. days since 1/1/1). You can
use datetime's toordinal() method for that, or
matplotlib.dates.epoch2num:

from pylab import figure, show
from matplotlib.dates import (epoch2num, WeekdayLocator,
  DateFormatter, MONDAY)

# epoch dates - 10/21, 10/29, 11/5
epoch_dates = [1350792000, 1351483200, 1352091600]
# convert to ordinal form
dates = [epoch2num(d) for d in epoch_dates]
kbSec = [24.3, 32.5, 21]

fig = figure()
ax = fig.add_subplot(1,1,1)
ax.plot_date(dates, kbSec, '-')
ax.xaxis.set_major_locator(WeekdayLocator(MONDAY))
ax.xaxis.set_major_formatter(DateFormatter('%m-%d'))
fig.autofmt_xdate()
show()
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Help with class example

2012-11-05 Thread Dave Angel
On 11/05/2012 06:07 PM, Prasad, Ramit wrote:
> Frank Pontius wrote:
>> Sent: Saturday, October 27, 2012 12:27 PM
>> To: d...@davea.name; bgai...@gmail.com
>> Cc: tutor@python.org
>> Subject: Re: [Tutor] Help with class example
>>
>> Here ya go!
>> Can't do what you want as this is a programmatic error from interrupter.  
>> Only a screen shot will tell you the
>> full situation.  I have class example which is to be used for our homework, 
>> and I copied it into IDLE and it
>> won't work, with error below.  I've tried several ways to work around this
>>
>> Thanks
>> Frank
>>
>
> You would be better off trying to run this from the command
> line.  The problem is the "if" and "else" lines are indented one
> level too far. If you match them with the previous line
> it should work just fine.
>
> ~Ramit
And the other problem is that the source in the OP message does not
match the source in the jpg file.  A line was omitted during the retyping.


-- 

DaveA

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


Re: [Tutor] help on dic creation

2012-11-05 Thread Alan Gauld

On 31/10/12 01:01, Brayden Zhao wrote:


Here is my code and I dont know why my code is only reading the 500th
line of the file. Thanks for your help!

def fieldict(filename):
   D={}
   with open(filename) as FileObject:
 for lines in FileObject:
   linelist=lines.split('\t')
   Key=linelist[0]
   ValCity=(linelist[12]).strip()
   ValState=linelist[13]
   ValOne=linelist[2]
   ValTwo=linelist[6]
   ValThree=boolean(linelist[7])


You are assigning each line to the same variable.
So at the end of the loop ypou have the values of the last line.
You need to build a collection.

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

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