Re: [Tutor] Lotka-Volterra Model Simulation Questions

2012-10-01 Thread Oscar Benjamin
On Oct 1, 2012 12:26 AM, "Alan Gauld"  wrote:
>
> On 30/09/12 11:50, Oscar Benjamin wrote:
>> While I can write a script like the OP's in less than 5 minutes, in
>> practise it takes longer to convince myself that the code is correct (if
>> it is important for it to be so). I spend most of the time when
>> developing such a script simply looking at the code and comparing it
>> with the mathematical problem I was trying to solve.
>
>
> Which is great if you understand the problem domain and the math
involved. If you don't you have to rely on getting the algorithm from the
experts and then translating it into something you can work with after the
expert has moved on.

I guess we won't get to find out but I assumed that the OP understood what
he was doing mathematically but was struggling with the Python code: his
code is correct in it's description of the mathematical model but the
integration algorithm had not been implemented. If I was correct about that
then it would have been bad advice to change the variable names. Also (even
if I was correct) it's still very likely that my own post went over his
head because of the level of assumed Python experience.

>> # Lotka-Volterra derivative
>> def f(Z, t):
>
>
> Although I would argue that 'f' is still a rotten name
> for any function!
>
> def lotka_volterra(Z,t):
>
> would be better. :-)

I'm not sure I would really use f in a real problem but I should say that
it is the mathematical convention to call this particular function f. I'll
meet you (sort of)half way:

def f_lotka_volterra(x, t):

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


Re: [Tutor] Help for Python Beginner with extracting and manipulating data from thousands of ASCII files

2012-10-01 Thread Oscar Benjamin
On Sep 30, 2012 11:10 PM, "Cecilia Chavana-Bryant"
 wrote:
>
> Hola again Python Tutor!

Hi Cecilia

>
> With a friend's help I have the following code to extract reflectance data 
> from an ASCII data file, do a bit of data manipulation to calibrate the data 
> and then write the calibrated file into an out file.
>
> import numpy
> # import glob - use if list_of_files is used
>
>
> dataFile = "1SH0109.001.txt"
> #list_of_files = glob.glob('./*.txt') to replace dataFile to search for all 
> text files in ASCII_files folder?
> caliFile1 = "Cal_File_P17.txt" # calibration file to be used on data files 
> created from July to 18 Sep
> caliFile2 = "Cal_File_P19.txt" # calibration file to be used on data files 
> created from 19 Sep onwards
> outFile = "Cal_" + dataFile # this will need to change if list_of_files is 
> used
> fileDate = data[6][16:26] # location of the creation date on the data files

The variable data used in the line above is not created until the
lines below run. I think you need to move this line down. What format
does fileDate have? I guess it's a string of text from the file. If
you can convert it to a datetime (or date) object it will be easy to
compare with the dates as required for your calibration file. Can you
show us how it looks e.g.

'12-Nov-2012'
or
'12/11/12'
or something else?

>
> #extract data from data file
> fdData = open(dataFile,"rt")
> data = fdData.readlines()
> fdData.close()


Python has a slightly better way of writing code like this:

with open(dataFile, 'rt') as fdata:
data = fdata.readlines()

This way you don't need to remember to close the file. In fact Python
will even remember to close it if there is an error.


>
> #extract data from calibration file
> fdCal = open(caliFile,"rt")
> calibration = fdCal.readlines()
> fdCal.close()

Where is caliFile set? If your going to load all the data files you
might as well load both calibration files here at the beginning.

>
> #create data table
> k=0 #just a counter
> dataNum = numpy.ndarray((2151,2))

Does dataNum store integers or floating point numbers? Numpy won't let
you do both in the same array. You should always specify the type of
the numpy array that you want to create:

dataNum = numpy.ndarray((2152, 2), float)

or

dataNum = numpy.ndarray((2152, 2), int)

As it happens you are creating an array floats. That means that when
you try to store an integer in the array below it gets converted to a
float.

>
> #the actual data (the numbers) in the data file begin at line 30
> for anItem in data[30:]:
> theNums = anItem.replace("\r\n","").split("\t")
> dataNum[k,0] = int(theNums[0])
> dataNum[k,1] = float(theNums[1])
> k+=1 #advance the counter

You should look into using numpy.fromfile. This function is
specifically designed for this purpose.

For example:

with open(dataFile) as fdata:
header_lines = [fdata.readline() for _ in range(30)]
dataNum = numpy.fromfile(fdata, float, sep='\t')


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


Re: [Tutor] Lotka-Volterra Model Simulation Questions

2012-10-01 Thread Alan Gauld

On 01/10/12 09:52, Oscar Benjamin wrote:


I guess we won't get to find out but I assumed that the OP understood
what he was doing mathematically but was struggling with the Python


In retrospect I think that's true. When I posted my original reply I 
assumed he was new to Python and learning about the math. (And of course 
I didn't know about the math side at all)



I'll meet you (sort of)half way:

def f_lotka_volterra(x, t):


:-)


--
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] generic repr method?

2012-10-01 Thread Albert-Jan Roskam


- Original Message -

> From: eryksun 
> To: Albert-Jan Roskam 
> Cc: Python Mailing List 
> Sent: Sunday, September 30, 2012 1:46 AM
> Subject: Re: [Tutor] generic repr method?
> 
> On Sat, Sep 29, 2012 at 4:15 PM, Albert-Jan Roskam  
> wrote:
>> 
>>      def __repr__(self):
>>          code = self.__class__.__name__ + "("
>>          for arg in inspect.getargspec(self.__init__).args [1:]  :
>>              if isinstance(eval("self." + arg), basestring):
>>                  code += ("%(" + arg + ")r, ")
>>              else:
>>                  code += ("%(" + arg + ")s, ")
>>          code = code[:-2] + ")"
>>          return code % self.__dict__
> 
> 
> __init__ could use *args and **kwds.
> Keyword-only arguments in Python 3 require using inspect.getfullargspec.
> A class with __slots__ probably lacks a __dict__.
> Use the repr of all values.

Hi Oscar, Eryksun,

Thanks! My code was an attempt to generalize a __repr__ method from Mark 
Summerfield's book 
(http://www.amazon.com/Programming-Python-Complete-Introduction-Language/dp/0137129297).
 But the inability to deal with *args, **kwargs is maybe its biggest 
shortcoming. And, as Oscar noted, it depends on the convention that somevalue 
always maps to self.somevalue in __init__. I had not considered __slots__ at 
all. I have read about it; IIRC they can be uised to "slim down" a class so it 
uses less memory. Is it true that this is not used very often?

It seems that for my current project I could still use the code, though I'd 
find it more readable if the keywords are also included in the string.

Thanks again!

Albert-Jan




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


Re: [Tutor] Lotka-Volterra Model Simulation Questions

2012-10-01 Thread Albert-Jan Roskam


- Original Message -

> From: Alan Gauld 
> To: tutor@python.org
> Cc: 
> Sent: Sunday, September 30, 2012 10:22 AM
> Subject: Re: [Tutor] Lotka-Volterra Model Simulation Questions
> 
> On 30/09/12 00:09, Brett Ritter wrote:
> 
>>  agreement.  Can you point to any of the research you mention?  I'd
>>  like to read into to see how my personal experience equates with the
>>  overall study - I might learn something!
> 
> I can probably dig out some references but a good place to start if you have 
> access (and every programmer should! :-) is Steve McConnell's book Code 
> Complete.
> 

That's also one of my favourite books! Definitely worth reading, also because 
it is written in quite a humorous way. There are checklists of that book that 
can be found on the internet: 
http://www.matthewjmiller.net/files/cc2e_checklists.pdf Chapter 11 is relevant 
for this discussion.

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


Re: [Tutor] OT: Netiquette

2012-10-01 Thread Emile van Sebille

On 9/30/2012 6:16 PM, Dwight Hutto wrote:


But he started it.



Now be the man and end it.

Emile


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


Re: [Tutor] generic repr method?

2012-10-01 Thread eryksun
On Mon, Oct 1, 2012 at 8:16 AM, Albert-Jan Roskam  wrote:
>
>I had not considered __slots__ at all. I have read about it; IIRC they
>can be uised to "slim down" a class so it uses less memory. Is it true
>that this is not used very often?

In a class defined with __slots__, it's up to you whether there should
be a slot for __dict__ and __weakref__ (see the weakref module).
Usually these aren't included because the point is, as you say, to
have a smaller footprint if you need to create thousands of objects.
But __dict__ can still be a property that returns a new dict when
requested.

For example, have you ever used collections.namedtuple? It's basically
a tuple with the indexed items mapped to field-name attributes via
properties. It's meant for light-weight, heterogeneous data records.
namedtuple uses an an empty __slots__ (the only option for tuple
subclasses) in order to exclude creation of an instance dict. Instead
the __dict__ attribute is a property (_asdict is the getter) that
returns a new collections.OrderedDict.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] generic repr method?

2012-10-01 Thread Oscar Benjamin
On 1 October 2012 13:16, Albert-Jan Roskam  wrote:
>
>> On Sat, Sep 29, 2012 at 4:15 PM, Albert-Jan Roskam 
>> wrote:
>>>
>>>  def __repr__(self):
>>>  code = self.__class__.__name__ + "("
>>>  for arg in inspect.getargspec(self.__init__).args [1:]  :
>>>  if isinstance(eval("self." + arg), basestring):

Please don't use eval for this. Python has a much better function that is
explicitly designed to use what you want., e.g.:

eval("self." + arg)  # Bad
getattr(self, arg)# Good


>>>  code += ("%(" + arg + ")r, ")
>>>  else:
>>>  code += ("%(" + arg + ")s, ")
>>>  code = code[:-2] + ")"
>>>  return code % self.__dict__
>>
> It seems that for my current project I could still use the code, though
I'd find it more readable if the keywords are also included in the string.

Is it so hard to write a repr for each class that needs one (most don't)?

I think most repr functions I've written have been very short and easy to
write.

def __repr__(self):
return 'MyClass(x={0}, y={1})'.format(self.x, self.y)

It's also good to think about each individual class and whether or not the
repr really makes sense.

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


Re: [Tutor] Help for Python Beginner with extracting and manipulating data from thousands of ASCII files

2012-10-01 Thread Cecilia Chavana-Bryant
On Mon, Oct 1, 2012 at 12:33 AM, Alan Gauld wrote:

> On 30/09/12 23:07, Cecilia Chavana-Bryant wrote:
>
>> Hola again Python Tutor!
>>
>> With a friend's help I have the following code to extract reflectance
>> data from an ASCII data file, do a bit of data manipulation to calibrate
>> the data and then write the calibrated file into an out file.
>>
>
>
> 
>
>
>  I have successfully calibrated one ASCII file at a time with this code.
>> However, I have 1,000s of files that I need to calibrate so I would like
>> some help to modify this code so it can:
>>
>> 1. Use one calibration file (Cal_FileP17.txt) on data files created from
>> July to the 18th Sep and a different calibration file (Cal_FileP19.txt)
>> for data files created from the 19th of Sep onwards.
>>
>> 2. Find all the .txt files in a folder called ASCII_files, which is
>> subdivided into 12 different folders and calibrate all these files
>>
>
>
> Number 2 is easier to solve and the os.walk() and glob.glob()
> functions should provide all the tools you need.
>
> Number 1 is more tricky since there is no obvious way to determine the
> arbitrary start/stop dates you specify. So I'd suggest you need to
> generalise the requirement to take a start/stop date as well as the
> calibration file name and the input data file pattern. Use those as input
> parameters to a function that generates the list of files to process and
> then calls your existing code (wrapped in a new function) and possibly
> provide default values for all/some of the parameters.
>
> Another option is to add the start/end dates to the calibration file if
> you have control of that, but personally I'd stick with input parameters...
>
> Many thanks Alan for your reply. I have added start and end dates as part
of the header information for the calibration files in the date format:
01/07/2011. So, I now need to write some code to take this into
consideration, any suggestions?

>
> --
> Alan G
> Author of the Learn to Program web site
> http://www.alan-g.me.uk/
>
> __**_
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/**mailman/listinfo/tutor
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Help for Python Beginner with extracting and manipulating data from thousands of ASCII files

2012-10-01 Thread Cecilia Chavana-Bryant
On Mon, Oct 1, 2012 at 1:16 AM, Dave Angel  wrote:

> On 09/30/2012 06:07 PM, Cecilia Chavana-Bryant wrote:
> > Hola again Python Tutor!
> >
> > With a friend's help I have the following code to extract reflectance
> data
> > from an ASCII data file, do a bit of data manipulation to calibrate the
> > data and then write the calibrated file into an out file.
> >
> > import numpy
> > # import glob - use if list_of_files is used
> >
> >
> > dataFile = "1SH0109.001.txt"
> > #list_of_files = glob.glob('./*.txt') to replace dataFile to search for
> all
> > text files in ASCII_files folder?
>
> First, an important observation.  This code has no functions defined in
> it.  Thus it's not reusable.  So every time you make a change, you'll be
> breaking the existing code and then trying to make the new version work.
>
> The decision of one file versus many is usually handled by writing a
> function that deals with one file.  Test it with a single file.  Then
> write another function that uses glob to build a list of files, and call
> the original one in a loop.
>
> As you work on it, you should discover that there are a half dozen other
> functions that you need, rather than one big one.
>
> Many thanks for this advise this helps me to get started with trying to
write functions for the different procedures and then think about many
files.

> > caliFile1 = "Cal_File_P17.txt" # calibration file to be used on data
> files
> > created from July to 18 Sep
> > caliFile2 = "Cal_File_P19.txt" # calibration file to be used on data
> files
> > created from 19 Sep onwards
> > outFile = "Cal_" + dataFile # this will need to change if list_of_files
> is
> > used
> > fileDate = data[6][16:26] # location of the creation date on the data
> files
>
> Show us the full traceback from the runtime error you get on this line.
>
> The option of using 2 different calibration files is an idea that I
haven't tested yet as I am a bit lost in how to do this. I have gotten as
far as adding start and end dates on both calibration files as part of the
header information for each file.

#extract data from data file

> > fdData = open(dataFile,"rt")
> > data = fdData.readlines()
> > fdData.close()
> >
> > #extract data from calibration file
> > fdCal = open(caliFile,"rt")
>
> Show us the full traceback from the runtime error here, as well.
>
> In the original code which uses only one calibration file this and the
rest of the code works without error.


> > calibration = fdCal.readlines()
> > fdCal.close()
> >
> > #create data table
> > k=0 #just a counter
> > dataNum = numpy.ndarray((2151,2))
> >
> > #the actual data (the numbers) in the data file begin at line 30
> > for anItem in data[30:]:
> > theNums = anItem.replace("\r\n","").split("\t")
> > dataNum[k,0] = int(theNums[0])
> > dataNum[k,1] = float(theNums[1])
> > k+=1 #advance the counter
> >
> > #create the calibration table
> > k = 0
> > calNum = numpy.ndarray((2151,2))
> > for anItem in calibration[5:]:
> > theNums = anItem.replace("\r\n","").split("\t")
> > calNum[k,0] = int(theNums[0])
> > calNum[k,1] = float(theNums[1])
> > k+=1
> >
> > #calibrate the data
> > k=0
> > calibratedData = numpy.ndarray((2151,2))
> > for aNum in dataNum:
> > calibratedData[k,0] = aNum[0] #first column is the wavelength
> > calibratedData[k,1] = (aNum[1] * dataNum[k,1]) * 100.0 #second column
> > is the measurement to be calibrated.
> > k+=1
> >
> > #write the calibrated data
> > fd = open(outFile,"wt")
> Error traceback ?
> > #prior to writing the calibrated contents, write the headers for data
> files
> > and calibration files
> > fd.writelines(data[0:30])
> > fd.writelines(calibration[0:5])
> > for aNum in calibratedData:
> > #Write the data in the file in the following format:
> > # "An integer with 3 digits", "tab character", "Floating point
> number"
> > fd.write("%03d\t%f\n" % (aNum[0],aNum[1]))
> >
> > #close the file
> > fd.close()
> >
>
> Are the individual files small?  By doing readlines() on them, you're
> assuming you can hold all of both the data file and the calibration file
> in memory.
>
> Both the calibration and the data files are small. The original excel
calibration files have been saved as "Tab delimited text files" and the
data files are ASCII files with 2151 rows and 2 columns.

> I have successfully calibrated one ASCII file at a time with this code.
> Unless I'm missing something, this code does not run.  I didn't try it,
> though, just inspected it quickly.
> > However, I have 1,000s of files that I need to calibrate so I would like
> > some help to modify this code so it can:
> >
> > 1. Use one calibration file (Cal_FileP17.txt) on data files created from
> > July to the 18th Sep and a different calibration file (Cal_FileP19.txt)
> for
> > data files created from the 19th of Sep onwards.
> >
> > 2. Find all the .txt files in a folder called ASCII_files, which is
> > subdivided into 12 different folders and calibrate all these f

Re: [Tutor] html checker

2012-10-01 Thread bob gailer

On 10/1/2012 11:45 AM, Matthew Dalrymple wrote:
Im trying to write an html syntax checker...pretty much read an 
imported file, if it has all the opening and closing "<" and ">" it 
will return True and if it doesn't it will return False.


this is what i have so far
http://pastie.org/4891833

how can i get it to run correctly?
Welcome to the tutor list. I assume this is your first visit. Why? 
because we always request that you tell us what happens to lead you to 
say it does not run correctly. This can mean many things.


So - what happens when you run the program? Be specific.

Also - always reply-all so a copy goes to the list.

Tell us which version of Python you are using, which OS and what you do 
to run the program.


Put your response(s) after the item(s) you are responding to (as I have 
done here). In other words do not "top-post".


Delete irrelevant text (as I have done here).

A quick glance at your program shows many flaws.

from  pythondsBasicimport  stack

This is an unknown (to me and to Google) module. Where did you get it? 
What is stack?


for  linein  infile:
data=  infile.readline()

This will read all the lines in the file. Each line in turn will be 
assigned to data,
so at the of the loop data will contain the last line. data is not 
referenced anyweere

else in the program.

for  chin  infile:

Will immediately terminate as the file is now at EOF. If you were to 
remove the for line in infile: loop then ch will contain one line, not 
one character!


Your program does an import and defines functions. There is nothing in 
it to run any of the functions.


There are many other problems! Too many for me to continue analyzing and 
reporting.


Did you succeed in the previous labs? How did you get this far and then 
fail so miserably?


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

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


Re: [Tutor] html checker

2012-10-01 Thread Matthew Dalrymple

I don't need to hear how bad my programs are...either you are gonna help or 
your not...if you have questions about what i have wrote or why i wrote 
something someway ask...dont just jump to conclusions I forgot to include that 
i had to write a "stack" function in a "pythonbasic" file to 
importhttp://pastie.org/4892792 Im here because i want to learn not to be 
fucking bashed...a few of the functions were copied from my book as they were 
required for other parts of the lab...so again if you have a problem with those 
other functions maybe you should take it up with the author... anyway i just 
don't know where to start to get the htmlChecker function to run...i am not a 
programmer by any means but is required to learn for my major...this is why im 
stuggling...i have networking experience not programming 
 Date: Mon, 1 Oct 2012 14:48:39 -0400
From: bgai...@gmail.com
To: computer_dud...@hotmail.com
CC: tutor@python.org
Subject: Re: [Tutor] html checker


  

  
  
On 10/1/2012 11:45 AM, Matthew
  Dalrymple wrote:



  
  
Im trying to write an html syntax checker...pretty much read an
imported file, if it has all the opening and closing "<" and
">" it will return True and if it doesn't it will return
False.

 

this is what i have so far

http://pastie.org/4891833

 

how can i get it to run correctly?

  

Welcome to the tutor list. I assume this is your first visit. Why?
because we always request that you tell us what happens to lead you
to say it does not run correctly. This can mean many things.



So - what happens when you run the program? Be specific.



Also - always reply-all so a copy goes to the list. 



Tell us which version of Python you are using, which OS and what you
do to run the program.



Put your response(s) after the item(s) you are responding to (as I
have done here). In other words do not "top-post".



Delete irrelevant text (as I have done here).



A quick glance at your program shows many flaws.

from pythondsBasic import stack

This is an unknown (to me and to Google) module. Where did you get
it? What is stack?

for line in infile:
data = infile.readline()


This will read all the lines in the file. Each line in turn will be
assigned to data, 

so at the of the loop data will contain the last line. data is not
referenced anyweere

else in the program.

for ch in infile: 

Will immediately terminate as the file is now at EOF. If you were to
remove the for line in infile: loop then ch will contain one line,
not one character!



Your program does an import and defines functions. There is nothing
in it to run any of the functions. 



There are many other problems! Too many for me to continue analyzing
and reporting.



Did you succeed in the previous labs? How did you get this far and
then fail so miserably?

-- 
Bob Gailer
919-636-4239
Chapel Hill NC___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] html checker

2012-10-01 Thread Andre' Walker-Loud
Dear Matthew,

> I don't need to hear how bad my programs are...either you are gonna help or 
> your not...if you have questions about what i have wrote or why i wrote 
> something someway ask...dont just jump to conclusions
>  
> I forgot to include that i had to write a "stack" function in a "pythonbasic" 
> file to import
> http://pastie.org/4892792
>  
> Im here because i want to learn not to be fucking bashed...a few of the 
> functions were copied from my book as they were required for other parts of 
> the lab...so again if you have a problem with those other functions maybe you 
> should take it up with the author...
>  
> anyway i just don't know where to start to get the htmlChecker function to 
> run...i am not a programmer by any means but is required to learn for my 
> major...this is why im stuggling...i have networking experience not 
> programming


Bob was not trying to bash you.
You clearly must be frustrated with your program, as your response was very 
intense and negative.
Try not to project your frustration with your program out on the people who are 
trying to help you.
Recall, those responding to the list are purely volunteers - they do what they 
do because they enjoy helping others learn about python - or feel like giving 
back to new people learning since they received help from this list and others.

In addition to helping you with the programming, the senior responders also try 
to teach you how to think about your problems better, including what 
information to include in such emails, so that they can help you.  Bob was 
pointing out that you have not included enough information in your original 
post for those on the list to help you.

May I suggest that you relieve your frustration on something local, and then 
try and see what information Bob was asking for that you can provide, so that 
people on the list can provide you with guidance and help.


Cheers,

Andre




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


Re: [Tutor] html checker

2012-10-01 Thread c smith
You will not find much help in getting a program to 'just work' regardless
of your own experience. My advice would be to try and run small parts at a
time to pinpoint where the problem is. Are you opening and reading the file
properly? Are you iterating over the read file properly? Does your html
check work on a local, properly formatted html file? Create a small text
file to run it on. Also keep track of file position and when you are
assigning variables new values. I am still learning myself, so this isnt
very specific, but you will have to ask more specifically so more
experienced people will be willing to help without doing your work for you.
Good luck
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] html checker

2012-10-01 Thread Brian van den Broek
On 1 Oct 2012 15:28, "Matthew Dalrymple" 
wrote:
>
> I don't need to hear how bad my programs are...either you are gonna help
or your not...if

Matthew,

Bob didn't cuddle you and he may have been a bit more brusque than you'd
have liked. However, his response to you was intended as help, it provided
what would be help if you would read it as such, and it was worth much more
than you paid for it.

Your reply to that offer of help is not such as to encourage anyone else to
give their time to you. I suggest you have a calm breath and reflect. You
can surmount your start with this list, but for more than a few who answer
here, you'll have to demonstrate you are more appreciative of the time and
effort you are given before you get more.

While you may not like this email I am fairly sure it contains a message
you very much need to hear.

Best,

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


Re: [Tutor] html checker

2012-10-01 Thread Matthew Dalrymple


 > Subject: Re: [Tutor] html checker
> From: walksl...@gmail.com
> Date: Mon, 1 Oct 2012 12:38:07 -0700
> CC: tutor@python.org
> To: computer_dud...@hotmail.com
> 
> Dear Matthew,
> 
> > I don't need to hear how bad my programs are...either you are gonna help or 
> > your not...if you have questions about what i have wrote or why i wrote 
> > something someway ask...dont just jump to conclusions
> >  
> > I forgot to include that i had to write a "stack" function in a 
> > "pythonbasic" file to import
> > http://pastie.org/4892792
> >  
> > Im here because i want to learn not to be fucking bashed...a few of the 
> > functions were copied from my book as they were required for other parts of 
> > the lab...so again if you have a problem with those other functions maybe 
> > you should take it up with the author...
> >  
> > anyway i just don't know where to start to get the htmlChecker function to 
> > run...i am not a programmer by any means but is required to learn for my 
> > major...this is why im stuggling...i have networking experience not 
> > programming
> 
> 
> Bob was not trying to bash you.
> You clearly must be frustrated with your program, as your response was very 
> intense and negative.
> Try not to project your frustration with your program out on the people who 
> are trying to help you.
> Recall, those responding to the list are purely volunteers - they do what 
> they do because they enjoy helping others learn about python - or feel like 
> giving back to new people learning since they received help from this list 
> and others.
> 
> In addition to helping you with the programming, the senior responders also 
> try to teach you how to think about your problems better, including what 
> information to include in such emails, so that they can help you.  Bob was 
> pointing out that you have not included enough information in your original 
> post for those on the list to help you.
> 
> May I suggest that you relieve your frustration on something local, and then 
> try and see what information Bob was asking for that you can provide, so that 
> people on the list can provide you with guidance and help.
> 
> 
> Cheers,
> 
> Andre No i understand that i might not have been as specific as i needed to 
> be and that i did forget to include a lot of information that is kind of 
> required to understand why i did what i did with certan areas... what 
> bothered me though is when he asked if i was ever succesful in previous labs 
> an how i could have gotten so far and still fail so miserably...i feel that 
> was uncalled for and really not necessary in helping me with the program
I wrote the "stack" moduleI have made a few changes to the file opening 
lines...and i think that part is working nowThe professor wants to start the 
program on his own by running "htmlChecker()" in IDLEAlso this is in Python 3.2 
What i need to have done is to verify that every  "<" at the beginning of the 
tags has a ">" at the end...and visa versa...and i have to do this using "pop" 
and "push" i don't really understand the pop and push or even stacks for that 
matter...the professor i have isn't really the best at teaching...so if anyone 
could give me a hand with any of this that would be appreciated Matt
   ___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Lotka-Volterra Model Simulation Questions

2012-10-01 Thread Brian van den Broek
On 30 September 2012 04:37, Alan Gauld  wrote:

> 
> One of the things that makes math hard for people to grasp is its insistence
> on abstracting functions/values to single letter names etc. (especially when
> those names are in a foreign language/symbology,
> like Greek!) Of course, the abstraction is powerful in its own right because
> it can then be applied in multiple domains, but that abstraction is often
> the barrier to people understanding the
> principle. Those that are "good at math" are often really those
> who are "good at abstraction".
> 

Hi Alan and all,

While I think I see what you mean here, Alan, I cannot quite resist
and, as this thread long since got hopelessly off-topic :-) I feel no
need for restraint.

To a first approximation, mathematics can reasonably be thought of as
the science of abstraction. So, to say (with a hint of complaint) that
those who are good at math are often those who are good at abstraction
seems a bit like complaining that it is those with good spatial
reasoning and a sense of direction that are good at navigation. While
it is indeed possible for mathematical presentation to devolve into
unhelpful abstraction (it is this that I suspect Alan intended to
target), abstraction is of the essence to the enterprise; nothing that
still counts as maths could be easily understood by those without the
ability to think abstractly.

Having posted twice in a half-hour, I resume my lurk-cloak.

Best to all,

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


Re: [Tutor] html checker

2012-10-01 Thread c smith
yourlisthere.pop() will return the last element in the list and change the
list so it no longer contains the element. yourlisthere.push(x) will add x
to the end of the list. Works on more than just lists
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] html checker

2012-10-01 Thread Joel Goldstick
> i don't really understand the pop and push or even stacks for that
> matter...the professor i have isn't really the best at teaching...so if
> anyone could give me a hand with any of this that would be appreciated

The way I was taught about pop and push:

Think of a stack of dishes.  Each time you push you are adding a new
dish to the top of a stack.  Each time you pop you are removing a dish
from the stack.
>
> Matt
>
>
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>



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


Re: [Tutor] html checker

2012-10-01 Thread eryksun
On Mon, Oct 1, 2012 at 11:45 AM, Matthew Dalrymple
 wrote:
>
> Im trying to write an html syntax checker...pretty much read an imported
> file, if it has all the opening and closing "<" and ">" it will return True
> and if it doesn't it will return False.

It's just this htmlChecker function that you need help with, right?
Below I've indented your code by 4 spaces and split it into sections.
I've placed simple code suggestions in-line with my comments. I hope
it's easy enough to follow.


def htmlChecker():
fname = input('What is the name of the file you would like to open: ')
infile = open(fname, 'r+')


You should generalize this by having the function take "fname" as an
argument and moving the "input" line to another function that calls
htmlChecker. Keep the back-end processing separate from the user
interface.

Also, why are you opening in read-write mode? Use "open(fname)" to
open the file in read-only text mode.


for line in infile:
data = infile.readline()


Python 3 doesn't raise an error for this, but Python 2 would.

(1) You're already iterating through the file by line, i.e. "for line
in infile", so why do you call readline() in the body of the loop?

(2) This repeatedly assigns a line from the file to the name "data".
It does not extend "data", nor would that be generally advisable since
it's inefficient to repeatedly allocate, copy, and deallocate memory
to extend a string.

(3) If you want the entire contents of the file in "data", use either
"data = infile.read()" to get it all as one string, or "data =
infile.readlines()"  (note the "s" in "readlines") to load the lines
of the file into a list.


s = stack()
s1 = stack()


Stack s1 seems to be for the contents of the tag. You can just use a
list for this, i.e. "s1 = []". Actually, you can use a list as a
stack, too, but I assume you were instructed to use this particular
stack data structure.

A stack is just like a stack of plates. You can push a plate on top,
and pop one off. The "list.append" method functions to "push" a value
on the top (end of the list), and "list.pop()" defaults to removing
the last item if you don't specify an index (like popping off the top
of a stack).


for ch in infile:


(1) File objects iterate by line, not by character.
(2) You've already exhausted the iterator from the last loop, so this
loop immediately terminates.

Let's assume you've read the entire file into memory as a string with
"data = infile.read()". Then you can iterate over the characters with
"for ch in data".


if ch =='<':
if s.isEmpty():
s.push(ch)
else:
return s.isEmpty()


Why are you returning s.isEmpty()? Does this method return something
other than True/False? Otherwise, I think you should explicitly
"return False".


if ch =='>':
s.pop()


This should use "elif", not "if". ch can't be both '<' and '>' (it's
made of classical bits, not quantum qubits), so there's no reason to
test for '>' if it already matched '<'.


if not s.isEmpty()and ch!='<':
s1.push(ch)


As above, but this line should be "elif not s.isEmpty()". If you make
s1 a list, you can append the character with "s1.append(ch)".


Finally:


print(s1)


If s1 is an iterable sequence, you can print the string using either
"print(''.join(s1))" or "print(*s1, sep='')". Also, at this point
should s1 be emptied?
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] html checker

2012-10-01 Thread eryksun
On Mon, Oct 1, 2012 at 4:23 PM, eryksun  wrote:
>
> Finally:
>
>
> print(s1)
>
>
> If s1 is an iterable sequence, you can print the string using either
> "print(''.join(s1))" or "print(*s1, sep='')". Also, at this point
> should s1 be emptied?

Sorry, that last statement was wrong. I was thinking you were
progressively printing the contents of each tag. But that would need
to happen when you pop() the stack. What you need to do here is
"return True", else your function implicitly returns "None".
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] 1d to 2d array creation

2012-10-01 Thread Bala subramanian
Friends,
I have an 1d array like a=[1, 1, 2, 2, 2, 3, 3, 1, 1, 1], i have to
convert it to 2d array for plotting as follows. The 2d array is filled
by a[colum index] to obtain the new array shown below.

[ [ 1.,  1.,  0.,  0.,  0.,  0.,  0.,  1.,  1.,  1.],
  [ 0.,  0.,  2.,  2.,  2.,  0.,  0.,  0.,  0.,  0.],
  [ 0.,  0.,  0.,  0.,  0.,  3.,  3.,  0.,  0.,  0.] ]

I wrote the following simple code for the conversion. However i guess
there should be more fancy/speeder way to do that. Also i need to
create such 2d-array from larger 1d arrays of size 2,3 items
etc. Hence i would like to request hints for a better code for the
purpose.

Here no. rows in my case is always = no. of discrete values in array a.

>>>my=1
>>>for i in range(3):
>>>  for j in range(10):
>>> if a[j] == my : b[i,j]=my
>>> else: b[i,j]=0
>>>  my +=1

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


Re: [Tutor] 1d to 2d array creation

2012-10-01 Thread Oscar Benjamin
On 1 October 2012 22:04, Bala subramanian  wrote:

> Friends,
> I have an 1d array like a=[1, 1, 2, 2, 2, 3, 3, 1, 1, 1], i have to
> convert it to 2d array for plotting as follows. The 2d array is filled
> by a[colum index] to obtain the new array shown below.
>
> [ [ 1.,  1.,  0.,  0.,  0.,  0.,  0.,  1.,  1.,  1.],
>   [ 0.,  0.,  2.,  2.,  2.,  0.,  0.,  0.,  0.,  0.],
>   [ 0.,  0.,  0.,  0.,  0.,  3.,  3.,  0.,  0.,  0.] ]
>
> I wrote the following simple code for the conversion. However i guess
> there should be more fancy/speeder way to do that. Also i need to
> create such 2d-array from larger 1d arrays of size 2,3 items
> etc. Hence i would like to request hints for a better code for the
> purpose.
>
> Here no. rows in my case is always = no. of discrete values in array a.
>
> >>>my=1
> >>>for i in range(3):
> >>>  for j in range(10):
> >>> if a[j] == my : b[i,j]=my
> >>> else: b[i,j]=0
> >>>  my +=1
>

Instead of

my = 1
for i in range(3):
   # stuff
   my += 1

why not do

for my in range(1, 4):
# stuff

But actually it makes more sense to eliminate one of the loops and do:

for i, ai in enumerate(a):
b[i, ai] = ai

It may be that you get better speed with something like

for j in range(max(a.max)):
b[j, a==j+1] = j

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


Re: [Tutor] Lotka-Volterra Model Simulation Questions

2012-10-01 Thread Alan Gauld

On 01/10/12 21:05, Brian van den Broek wrote:

On 30 September 2012 04:37, Alan Gauld  wrote:



like Greek!) Of course, the abstraction is powerful in its own right because
it can then be applied in multiple domains, but that abstraction is often
the barrier to people understanding the principle.



To a first approximation, mathematics can reasonably be thought of as
the science of abstraction.


Absolutely and that's what I mean by its general applicability.



So, to say (with a hint of complaint)


No complaint was intended it was just an observation. But equally I have 
observed that people who think they can't do math can often *use* math 
successfully once the abstract has been translated to the specific. They 
understand what the math is telling them but can't relate to it in a 
purely abstract form. The math community sometimes forgets that not 
everyone thinks as they do and to communicate their ideas they need to 
revert to specifics sometimes.



it is indeed possible for mathematical presentation to devolve into
unhelpful abstraction (it is this that I suspect Alan intended to
target), abstraction is of the essence to the enterprise;


Absolutely.
I suspect this thread has been sparked because I just finished reading a 
book (The Geek Manifesto) which complains at length about how few 
figures in public life understand the workings of science and math.
But I think that the same could be said about scientists' understanding 
of accounts/law/politics. If we don't expect scientists to grok legalese 
why should we expect politicians to speak math. Those who can need to do 
the translation for them, not just complain of their 'ignorance'. But 
that's now taking things way, way off topic!! :-)


--
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] Lotka-Volterra Model Simulation Questions

2012-10-01 Thread Brian van den Broek
On 1 October 2012 19:30, Alan Gauld  wrote:

> translation for them, not just complain of their 'ignorance'. But that's now
> taking things way, way off topic!! :-)


I think you meant ``way^2 off topic'' ;-)

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


Re: [Tutor] html checker

2012-10-01 Thread Alan Gauld

On 01/10/12 20:59, Matthew Dalrymple wrote:


i don't really understand the pop and push or even stacks for that
matter...the professor i have isn't really the best at teaching...so if
anyone could give me a hand with any of this that would be appreciated


The Raw materials topic in my tutor has a short intro to stacks. It 
says, in part:


Stack

Think of a stack of trays in a restaurant. A member of staff puts a pile 
of clean trays on top and these are removed one by one by customers. The 
trays at the bottom of the stack get used last (and least!). Data stacks 
work the same way: you push an item onto the stack or pop one off. The 
item popped is always the last one pushed. This property of stacks is 
sometimes called Last In First Out or LIFO. One useful property of 
stacks is that you can reverse a list of items by pushing the list onto 
the stack then popping it off again. The result will be the reverse of 
the starting list. Stacks are not built in to Python, VBScript or 
JavaScript. You have to write some program code to implement the 
behavior. Lists are usually the best starting point since like stacks 
they can grow as needed.

-

As c smith points out, Python lists have a pop/push mechanism as 
standard which makes implementing a stack in Python fairly trivial.


To expand on how reversing works consider pushing the string foo onto 
the stack then popping it off again:


s = 'foo'
stack = []
stack.push(s[0])  # stack -> ['f']
stack.push(s[1])  # stack -> ['o','f']
stack.push(s[2])  # stack -> ['o','o','f']

c1 = stack.pop()  # stack -> ['o','f'], c1 = 'o'
c2 = stack.pop()  # stack -> ['f'], c1 = 'o', c2 = 'o'
c3 = stack.pop()  # stack -> [], c1 = 'o', c2 = 'o', c3 = 'f'

print c1+c2+c3  # prints 'oof' the reverse of s

HTH,

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

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


[Tutor] HELP!

2012-10-01 Thread Mark Rourke
hello, I am a college student in my first year of computer programming, 
I was wondering if you could look at my code to see whats wrong with it.


# Mark Rourke
# Sept 29, 2012
# Write a program to calculate the sales tax at the rate of 4% and 2% 
respectively
# Thereafter compute the total sales tax (sum of the state tax and the 
county tax)
# and the total purchase amount (sum of the purchase amount and the 
total sales tax).
# Finally, display the amount of purchase, the state sales tax, the 
county sales tax,

#the total sales tax and the total amount of the sale.

#Variable Declarations
#Real purchaseAmount, stateSalesTax, countySalesTax, totalSalesTax, 
totalPurchaseAmount

#Constant Real SALES_TAX = 0.4, COUNTY_TAX = 0.02

#Display "Input Purchase Amount: $"

#input the hours worked and hourly wage wage

SALES_TAX = 0.4

COUNTY_TAX = 0.02
print("--")
print(("This program calculates the sales tax at the rate of 4% and 2% 
respectively, as well sum of the state tax"))

print("--")

purchaseAmount = input("Please input the Purchase Amount: $")

#Calculate the State Sales Tax, County Sales Tax, Total Sales Tax, Total 
Purchase Amount


purchaseAmount = int(purchaseAmount)

stateSalesTax = int(purchaseAmount * SALES_TAX)

countySalesTax = int(purchaseAmount * COUNTY_TAX)

totalSalesTax = int(stateSalesTax + countySalesTax)

totalPurchaseAmount = int(purchaseAmount + totalSalesTax)

#Output the results

Display ("Purchase Amount:$") purchaseAmount
Display ("The State Sales Tax $") SALES_TAX
Display ("The County Sales Tax: $") COUNTY_TAX
Display ("The Total Sales Tax: $") totalSalesTax
Display ("The Total Amount of the Purchase: $") totalPurchaseAmount

--

Mark Rourke

T: 705-728-6169
M: 705-331-0175
E: mark.rour...@gmail.com

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


Re: [Tutor] HELP!

2012-10-01 Thread c smith
Is the only problem that your code is giving unexpected results, or that it
doesnt run or what?
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] python help?

2012-10-01 Thread c smith
It is hard to see things like images and attachments. I think purely html
is preferred, but i would have to look over 'the list rules' again.
You should look into dictionaries as the structure to hold your info.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] html checker

2012-10-01 Thread eryksun
On Mon, Oct 1, 2012 at 7:46 PM, Alan Gauld  wrote:
>
> As c smith points out, Python lists have a pop/push mechanism as standard
> which makes implementing a stack in Python fairly trivial.
>
> To expand on how reversing works consider pushing the string foo onto the
> stack then popping it off again:
>
> s = 'foo'
> stack = []
> stack.push(s[0])  # stack -> ['f']
> stack.push(s[1])  # stack -> ['o','f']
> stack.push(s[2])  # stack -> ['o','o','f']
>
> c1 = stack.pop()  # stack -> ['o','f'], c1 = 'o'
> c2 = stack.pop()  # stack -> ['f'], c1 = 'o', c2 = 'o'
> c3 = stack.pop()  # stack -> [], c1 = 'o', c2 = 'o', c3 = 'f'
>
> print c1+c2+c3  # prints 'oof' the reverse of s

It's a good example, but please indicate when you've switched to
pseudocode. In Python "stack = []" assigns a new list to stack, which
has no "push" method. It can append() and pop() from the end in
constant time to implement an efficient stack.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] python help?

2012-10-01 Thread Dave Angel
On 10/01/2012 08:16 PM, c smith wrote:
> It is hard to see things like images and attachments. I think purely html
> is preferred, but i would have to look over 'the list rules' again.

Since this is a text mailing-list, it's text messages that are
preferred.  html messages frequently trash indentation, which can be
fatal to a python source excerpt.  And many people cannot see
attachments at all, while others would simply skip any messages that
require looking at attachments.

> You should look into dictionaries as the structure to hold your info.
>
>

-- 

DaveA

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


[Tutor] Civil discourse from a newbie's perspective

2012-10-01 Thread boB Stepp
I have been following the discussions here since middle-May of this
year. I have gathered that the volunteers strongly value precision of
speech and proper formatting of posts and especially making a strong
effort to solve one's problem(s) before bringing it(them) up here for
help. I think I understand the frustrations that can arise when
newcomer after newcomer continue to repeat the same basic posting
errors, seemingly without end (May I never do the same!). However, I
think that extra care may be needed in dealing with newbies who may
only be taking a programming course using Python because of curriculum
requirements. I'm sure I am stating the obvious to most of you, but,
nonetheless, I think it is still worth saying (Again?). How one of you
phrase your meant-to-be-helpful response can inadvertently prove
crushing to someone who is very insecure in their programming
knowledge, and in some instances, apparently, incite them to
profanity.

In my first post here I inappropriately used the phrase, "begs the
question." I soon was informed of the error of my ways! While
educational (And, I confess, somewhat irritating.), these
clarifications had nothing to do with the actual intent of my post. I
shrugged it off, examined the comments and links about my offending
phrase, and went on to appreciate the valuable helpful comments that I
did receive on what I was really asking about. I only bring this up as
a concrete example of an instance that might have caused a newbie to
go elsewhere in frustration and anger, if I were thin-skinned about
it.

I am hesitant in even bringing these thoughts up, but it seems
recently there has been a rash of anger, profanity and hurt feelings.
Of course this is my subjective impression, which may be colored by my
lack of a thick skin.

But I DO want to say, that I greatly value the efforts of the
volunteers who strive to be so helpful and demonstrate repeatedly
great patience in the face of what clearly must, at times, be
extremely frustrating. But please exercise precision in your
communications with overly sensitive, frustrated or tentative newbies!

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


Re: [Tutor] python help?

2012-10-01 Thread Dave Angel
On 09/30/2012 02:02 AM, patrick Howard wrote:
> I have to write a program that takes an input file, with students names and 
> various grades.
> My vindictive teacher also added grades that are not supposed to count, so I 
> need to pick the grades that are 'HM1-4"; not HW, or TEST or anything else.
> Then when these are listed in order with that persons name, sort the list 
> alphabetically. I know that this is '.sort;
> But, how do I get it to sort only names, AND keep the right grades with them. 
> Below is a list of parameters… Can you help me please?
>
>

What part are you stuck on? It's hard to give advice when we don't know
what part of the assignment matters. First question is what language are
you to write this in, and on what OS. Assuming it's Python, then what's
the version?

I'm a little surprised you call the teacher vindictive. Bad data is
quite common in the real world. And in the real world, I'd be writing a
separate program to "cleanse" the data before processing.

Anyway, first you need to be able to open the specified file and read
and parse the text lines into some form of data structure.

Second you manipulate that structure, so that the output can be produced
in a straightforward manner.

Third, you produce the output, which now should be pretty straightforward.

Write them as three (at least) separate functions, and you can debug
them separately. Much easier than trying to make it a monolith which
either works or is hopeless.

So the first question is what kind of structure can hold all that data.
I have no idea what level of Python you've attained, but I'll guess you
don't know how to write your own classes or generators. So you have to
build the structures from whatever's in the standard library.

Outermost structure is a list, one per student. Each item of the list is
a defaultdict, keyed by name, and by the various HMn fields. Values of
each of those dict items are floats.

-- 

DaveA

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


Re: [Tutor] what's wrong with my code? (was HELP!)

2012-10-01 Thread bob gailer

On 9/30/2012 3:31 PM, Mark Rourke wrote:
hello, I am a college student in my first year of computer 
programming, I was wondering if you could look at my code to see whats 
wrong with it.
Welcome to the tutor list. I assume this is your first visit. Why? 
because we always request that you tell us what happens to lead you to 
say it does not run correctly. This can mean many things.


So - what happens when you run the program? Be specific.

Also - always reply-all so a copy goes to the list.

Tell us which version of Python you are using, which OS and what you do 
to run the program.


Put your response(s) after the item(s) you are responding to (as I have 
done here). In other words do not "top-post".


Delete irrelevant text (as I have done here).

Provide a problem-specific subject (not HELP) so we can track our 
conversation.


Realize that we are a few volunteers (no pay other than the fun of 
assisting).


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

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


Re: [Tutor] python help?

2012-10-01 Thread Dave Angel
On 10/01/2012 09:44 PM, Dave Angel wrote:
> On 09/30/2012 02:02 AM, patrick Howard wrote:
>> I have to write a program that takes an input file, with students names and 
>> various grades.
>> My vindictive teacher also added grades that are not supposed to count, so I 
>> need to pick the grades that are 'HM1-4"; not HW, or TEST or anything else.
>> Then when these are listed in order with that persons name, sort the list 
>> alphabetically. I know that this is '.sort;
>> But, how do I get it to sort only names, AND keep the right grades with 
>> them. 

Use a tuple of  (name, grades)   where the name is a string, and the
grades are in a dict or defaultdict.  When sorting a list of tuples, the
sort will work only on the first element of each tuple, unless there's a
tie.  Checking for duplicate student names is one of those things that
gets separately verified, before even running your code.

>> Below is a list of parameters… Can you help me please?
>>
>>
> What part are you stuck on? It's hard to give advice when we don't know
> what part of the assignment matters. First question is what language are
> you to write this in, and on what OS. Assuming it's Python, then what's
> the version?
>
> I'm a little surprised you call the teacher vindictive. Bad data is
> quite common in the real world. And in the real world, I'd be writing a
> separate program to "cleanse" the data before processing.
>
> Anyway, first you need to be able to open the specified file and read
> and parse the text lines into some form of data structure.
>
> Second you manipulate that structure, so that the output can be produced
> in a straightforward manner.
>
> Third, you produce the output, which now should be pretty straightforward.
>
> Write them as three (at least) separate functions, and you can debug
> them separately. Much easier than trying to make it a monolith which
> either works or is hopeless.
>
> So the first question is what kind of structure can hold all that data.
> I have no idea what level of Python you've attained, but I'll guess you
> don't know how to write your own classes or generators. So you have to
> build the structures from whatever's in the standard library.
>
> Outermost structure is a list, one per student. Each item of the list is
> a defaultdict, keyed by name, and by the various HMn fields. Values of
> each of those dict items are floats.
>
One simplification, so you won't need a confusing key function, is to
make each item of the list a tuple, student-name string followed by
defaultdict.  By not putting the name inside the dict, sort of the list
will get the order right by default.  In particular, when sorting a list
of tuples, it uses the first item of each tuple as a primary key.

Recapping:
A list of tuples, one tuple per line.  First item of the tuple is the
studentname for that line. Other item of the tuple is a defaultdict
keyed by such strings as HM1, HM2, ...

Now, write some code, and when you get stuck, show us what you have, how
you tested it, and what went wrong.

-- 

DaveA

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


Re: [Tutor] HELP!

2012-10-01 Thread Brian van den Broek
On 1 Oct 2012 19:58, "Mark Rourke"  wrote:
>
> hello, I am a college student in my first year of computer programming, I was 
> wondering if you could look at my code to see whats wrong with it.
>
> # Mark Rourke
> # Sept 29, 2012
> # Write a program to calculate the sales tax at the rate of 4% and 2% 
> respectively
> # Thereafter compute the total sales tax (sum of the state tax and the county 
> tax)
> # and the total purchase amount (sum of the purchase amount and the total 
> sales tax).



> SALES_TAX = 0.4
>
> COUNTY_TAX = 0.02



> purchaseAmount = input("Please input the Purchase Amount: $")
>
> #Calculate the State Sales Tax, County Sales Tax, Total Sales Tax, Total 
> Purchase Amount
>
> purchaseAmount = int(purchaseAmount)
>
> stateSalesTax = int(purchaseAmount * SALES_TAX)



Hi Mark,

c smith is certainly right to suggest that you ought to specify a bit
more about what the symptoms are that you would like help diagnosing.

That said, what should be the result if an item with a sticker price
of 1.35 is purchased? Perhaps thinking about that and comparing the
following will help:

IDLE 2.6.6
>>> user_input = "1.35"
>>> purchaseAmount = int(user_input)

Traceback (most recent call last):
  File "", line 1, in 
purchaseAmount = int(user_input)
ValueError: invalid literal for int() with base 10: '1.35'
>>> user_input = float("1.35")
>>> purchaseAmount = int(user_input)
>>> purchaseAmount
1
>>>

Best,

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


Re: [Tutor] Civil discourse from a newbie's perspective

2012-10-01 Thread Steven D'Aprano
On Mon, Oct 01, 2012 at 08:34:03PM -0500, boB Stepp wrote:
> I have been following the discussions here since middle-May of this
> year. I have gathered that the volunteers strongly value precision of
> speech and proper formatting of posts 

Some more than others, but yes.


> and especially making a strong
> effort to solve one's problem(s) before bringing it(them) up here for
> help.

Certainly! Many beginners don't realise that the most important skill to 
learn is not programming syntax, or programming libraries, but the skill 
to fix your own code. The reason that experienced programmers rarely ask 
for help is not because they don't make mistakes, but because when they 
do so, they have the skills to fix the mistake themselves.

Skills such as:

- read the traceback that Python gives you, it is chock-full of useful 
  information

- learn how to interpolate from the error to the cause of the error

- learn how to work backwards from the immediate cause of the error to 
  the original cause

- test code snippets at the interactive interpreter or IDLE

- insert calls to print in your code

- how to use the Python debugger.


> I think I understand the frustrations that can arise when
> newcomer after newcomer continue to repeat the same basic posting
> errors, seemingly without end (May I never do the same!).

Thank you :)


> However, I
> think that extra care may be needed in dealing with newbies who may
> only be taking a programming course using Python because of curriculum
> requirements. I'm sure I am stating the obvious to most of you, but,
> nonetheless, I think it is still worth saying (Again?). How one of you
> phrase your meant-to-be-helpful response can inadvertently prove
> crushing to someone who is very insecure in their programming
> knowledge, and in some instances, apparently, incite them to
> profanity.

What you say is very true. But I want to give you a different 
perspective on volunteer-based help.

On another mailing list I subscribe to, one where I am a beginner, 
somebody asked a question about clearing the mail indexes used by Kmail 
so they would be regenerated when he next opened the mail program. It 
was a pretty simple question, and one of the regulars replied, 
sympathizing with his problems, wishing that her software problems were 
as easy to solve, and giving him the answer he was looking for.

He turned around and sarcastically thanked her for helping him with his 
"trivial" problem, gave her permission to ignore his posts in the 
future, and declared that he too would ignore hers as he was filtering 
them straight to the trash.

What a dick, right?

So you'll understand if I'm a tad underwhelmed by suggestions that 
volunteers should moderate their behaviour to make it easier for 
ungrateful wretches like this person. Not everyone deserves free help -- 
it is a privilege, not a right.

There are more people who need help than those who are willing and able 
to give help. When there is more demand for help than there is supply of 
it, how can we ration assistance?

- by charging for it?

- by lottery?

- first come, first served?

- how about by being uncompromisingly strict on those asking for help 
  and insisting that they make it easy for us to help them?

If they get offended and abuse us, they're sent to the back of the 
queue. If they get upset and go away, that's one less person who is 
asking for help. Only those who demonstrate sufficient humility, 
intelligence and dedication to accept criticism and learn from that 
criticism will hang around to ask for, and be given, help.

Does that sound harsh? Well, perhaps a little, but what's the 
alternative?

"You volunteers have to spend all your time and energy trying to 
decipher the mysterious ramblings and cries for help from people too 
lazy to write in complete sentences, and they probably won't listen to 
your advice anyway, if they don't abuse you for helping."

Screw that. It's about give and take. Both sides have to give a little 
to take a lot.


> In my first post here I inappropriately used the phrase, "begs the
> question." I soon was informed of the error of my ways!

I should certainly accept so! The correct use of idiom is unvalued for 
communication, otherwise we will all be hoist up by the petard.

*grin*


[...]
> But I DO want to say, that I greatly value the efforts of the
> volunteers who strive to be so helpful and demonstrate repeatedly
> great patience in the face of what clearly must, at times, be
> extremely frustrating. But please exercise precision in your
> communications with overly sensitive, frustrated or tentative newbies!

And thank you for saying so, and thank you for your frank expression of 
your opinion.



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