Re: [Tutor] Looping through Dictionaries

2017-05-23 Thread Mats Wichmann
On 05/23/2017 11:38 AM, Rafael Knuth wrote:
> I wrote a function (shopping list) which calculates the total price of
> the purchase (quantity * price) as well as the stock change (stock -
> quantity). I know the latter is imperfect (my function does not take
> into account if items are out of stock for example, but that's my next
> challenge. The function does exactly what it's supposed to do:
> 
> def shopping(quantity, price, stock):
> total = 0
> for key in quantity:
> total += quantity[key] * price[key]
> stock_update = stock[key] - quantity[key]
> print(stock_update)
> print(total)
> 
> quantity = {
> "bapple": 10,
> "banana": 20
> }
> 
> price = {
> "bapple": 5,
> "banana": 3
> }
> 
> stock = {
> "bapple": 20,
> "banana": 50
> }
> 
> shopping(quantity, price, stock)
> 
> Now, I want to print the item next to the stock update, and I am
> receiving an error message. I couldn't figure out how to fix that:

in the code below you're trying to use "value" as your key, but it isn't
the key. Why did you change that from the code above?

it helps if you include the errors, by the way :)

> 
> def shopping(quantity, price, stock):
> total = 0
> for key, value in quantity.items():
> total += quantity[value] * price[value]
> stock_update = stock[value] - quantity[value]
> print(key, stock_update)
> print(total)
> 
> quantity = {
> "bapple": 10,
> "banana": 20
> }
> 
> price = {
> "bapple": 5,
> "banana": 3
> }
> 
> stock = {
> "bapple": 20,
> "banana": 30
> }
> 
> shopping(quantity, price, stock)
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
> 

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


Re: [Tutor] Looping through Dictionaries

2017-05-23 Thread Alan Gauld via Tutor
On 23/05/17 18:38, Rafael Knuth wrote:

> Now, I want to print the item next to the stock update, and I am
> receiving an error message. I couldn't figure out how to fix that:

So show us the error message, all of it.
I can't begin to guess what it might be.

UI also don't understand what "print the
item next to the stock update" means.
Do you mean the actual location of the
data in the printed string? Or do you
mean the value(which?) next to the one
in your function?

Can you show us some examples?


> def shopping(quantity, price, stock):
> total = 0
> for key, value in quantity.items():
> total += quantity[value] * price[value]
> stock_update = stock[value] - quantity[value]

I don't see how this would work. value is the value
from the dictionary which is an integer. But you are
using it as a key which should be a string?
So in your first iteration key,value will be
key = 'bapple', value=10

so you are trying to evaluate

stock[10]-quantity[10]

but thee are no such items.

I suspect you mean:

stock['bapple'] - quantity['bapple']

or in your function:

stock[key] - quantity[key]

But in that case you don;t need the value from items()
you can just iterate over the keys:

for item in quantity:
...
stock_update = stock[item] - quantity[item]
print(item, stock_update)

> print(key, stock_update)
> print(total)
> 
> quantity = {
> "bapple": 10,
> "banana": 20
> }
> 
> price = {
> "bapple": 5,
> "banana": 3
> }
> 
> stock = {
> "bapple": 20,
> "banana": 30
> }
> 
> shopping(quantity, price, stock)

I'm not clear on what these variables indicate.
What is the difference between quantity and stock?

Also this might be a good time to look at classes
and objects. You could avoid all the multiple
stores by putting the various data elements
in a class.  This would avoid the potential
headaches caused by mis-typing the item names
in each store, for example. You could then
have variables bapple and banana and access,
for example, bapple.quantity and bapple.price.
And just keep a simple list of items.
Just a thought...

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


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


Re: [Tutor] looping - beginner question

2017-03-02 Thread leam hall
On Thu, Mar 2, 2017 at 8:42 AM, Rafael Knuth  wrote:

> I wrote a program that is supposed to take orders from customers in a bar.
> If the desired drink is available, the customer will be served. If
> not, he will be informed that the drink is not available. This is what
> I wrote:
>
> bar = ["beer", "coke", "wine"]
>
> customer_order = input("What would you like to drink, dear guest? ")
>
> for drink in bar:
> if customer_order != drink:
> print ("Sorry, we don't serve %s." % customer_order)
> else:
> print ("Sure, your %s will be served in a minute!" %
> customer_order)
>
> What I want the program to do is to "silently" loop through the list
> of drinks and to print the correct answer. Instead, it loops through
> each item on the list like this:
>
> >>>
> == RESTART: C:/Users/Rafael/Documents/01 - BIZ/Python/Python Code/PPC_4.py
> ==
> What would you like to drink, dear guest? coke
> Sorry, we don't serve coke.
> Sure, your coke will be served in a minute!
> Sorry, we don't serve coke.
> >>>
>
> Rafael, don't forget that your input string might have a newline character
that needs to be cleaned off. I think, can't test at the moment. The
simplest test might be:

if drink in bar:
  
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] looping - beginner question

2017-03-02 Thread Mats Wichmann
On 03/02/2017 08:06 AM, Alan Gauld via Tutor wrote:
> On 02/03/17 13:42, Rafael Knuth wrote:
> 
>> bar = ["beer", "coke", "wine"]
>>
>> customer_order = input("What would you like to drink, dear guest? ")
>>
>> for drink in bar:
>> if customer_order != drink:
>> print ("Sorry, we don't serve %s." % customer_order)
>> else:
>> print ("Sure, your %s will be served in a minute!" % customer_order)
>>
>> What I want the program to do is to "silently" loop through the list
> 
> So you only want the sorry... message if the loop completes without
> finding a drink. That means you need to put that print statement after
> the loop. Python includes a feature for that - a for/else construct.
> 
> for drink in bar:
> if drink == customer_order:
>print(Sure...)
>break  #exit loop and avoid else
> else:
> # only if the loop completes normally
> 
> However, there is another way to do this that doesn't
> use an explicit loop: the 'in' operator
> 
> if customer_order in bar:
> print("sure)
> else:
> print ("Sorry)

To follow on to what Alan said, you don't need to loop over a list (or
tuple, or dictionary, or other "iterable") to find out if it contains an
item. You can just test membership directly.




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


Re: [Tutor] looping - beginner question

2017-03-02 Thread Alan Gauld via Tutor
On 02/03/17 13:42, Rafael Knuth wrote:

> bar = ["beer", "coke", "wine"]
> 
> customer_order = input("What would you like to drink, dear guest? ")
> 
> for drink in bar:
> if customer_order != drink:
> print ("Sorry, we don't serve %s." % customer_order)
> else:
> print ("Sure, your %s will be served in a minute!" % customer_order)
> 
> What I want the program to do is to "silently" loop through the list

So you only want the sorry... message if the loop completes without
finding a drink. That means you need to put that print statement after
the loop. Python includes a feature for that - a for/else construct.

for drink in bar:
if drink == customer_order:
   print(Sure...)
   break  #exit loop and avoid else
else:
# only if the loop completes normally

However, there is another way to do this that doesn't
use an explicit loop: the 'in' operator

if customer_order in bar:
print("sure)
else:
print ("Sorry)

hth
-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


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


Re: [Tutor] looping generator

2016-01-07 Thread Alan Gauld
On 07/01/16 18:31, richard kappler wrote:
> Alan, have you ever actually been guilty of 'missing something'? :-)

Actually quite often.
Usually when its late at night(tired) or early morning(no coffee)
or I'm rushing to go someplace.

But it happens quite a lot, Usually Steven or Peter or someone
will jump in and show me the error of my ways.  ;-)

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos

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


Re: [Tutor] looping generator

2016-01-07 Thread Martin A. Brown

Hi there Richard,

>I have a stream of incoming xml data. I can receive the data, parse 
>the data, etc, so long as I don't get fancy and I have a miniscule 
>delay in between each message. If I get rid of the time delay, 
>which I need to, I need the script to continuously process the 
>incoming messages. Here's what I have:

To begin, I have a suggestion that is not specifically a Python 
suggestion.  I have read several of your prior emails describing 
your problem.

If I were faced with the problem of receiving and processing data 
from remote "dumb" nodes, I would separate the software components 
into, at least, two distinct pieces.

  1. Trust the filesystem.  Write one software component that 
 receives the data from the wire and writes it out to a 
 configurable directory.  If, for whatever reason, you lose the
 data, the performance of the rest of the system does not 
 matter.  Thus, capturing the data is the most important first 
 step.  Use your system's daemonization tools to run this 
 service.

  2. Improve performance of the parsing and processing tools.
 Teach the tools how to read the data stored in the filesystem 
 and iteratively locate hot spots, performance issues, parsing 
 problems or data shortcomings.

Here are a few disorganized thoughts about why and how to do it this 
way:

  * the network listener becomes much simpler since it will not 
parse, and will only write out to disk

  * let's assume each XML chunk is about 128k and you have 30 data 
sources and are receiving 4 chunks per second from each; total 
data volume is 1.5MiB, easily able to be received and written to 
disk on modern hardware

  * you could segregate the XML chunks also by data source (and 
maybe also time), writing out each chunk into the filesytem; if 
you break each message into its own file, that would be a large 
number of files (with attendant open() and close() costs), so
perhaps writing out a new file every minute or fifteen minutes;
here's a possible file naming scheme

received/2016/01/-10.143.17.227.data
received/2016/01/0100-10.143.17.227.data
received/2016/01/0200-10.143.17.227.data
  ...
received/2016/01/2300-10.143.17.227.data

that would leave you with about 720 files per daily directory, 
something that is eminently manageable for modern filesystems 
(and for any pesky humans who happen to be wandering around)

  * if you write out the stream of data to the filesystem, your 
network listener need only locate the \x02 byte and the \x03 
byte--it could ensure that every file it wrote contained a first 
byte of \x02 and a final byte of \x03

  * you can independently upgrade the parsing and processing tools 
and the data recording service

  * if you retain these files, you can "replay" the past (errors, 
bursts, reprocessing); alternatively simply delete the files 
after they are processed for downstream consumers

  * separating the responsibilities of each software component also 
simplifies your diagnosis and software authorship process; first 
you can make sure that you are recording the data properly; once 
that is done, you can start to process your data, moving along 
to performance questions next

Now, below, I have a few Python-specific points or questions:

>#!/usr/bin/env python
>
>import socket
>import lxml.etree as ET
>
>def dataRecv(connection):
>print 'receiving'
>while True:
>data = connection.recv(65536)
>while True:
>print "writing to data.in"
>f2.write(data)
>start = data.find('\x02')
>end = data.find('\x03')
>message = data[start+1:end]
>print "writing to messages.out"
>f3.write(message)
>yield message

You do not define f2 and f3 until below.  If you are going to do 
this, pass them into the function f2 and f3.  I.e.
  
  def dataRecv(connection, f2, f3):
   
  
  while True:
  # wait for a connection
  connection, client_address = sock.accept()
  q = dataRecv(connection, f2, f3)
  

>def dataParse(message):
>print 'parsing'
>xslt = ET.parse('stack13.xsl')
>dom = ET.XML(message)
>transform = ET.XSLT(xslt)
>newdom = transform(dom)
>f1.write(str(newdom))
>
>
>sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
>sock_addr = ('', 2008)
>#data = sock.makefile('r')
>sock.bind(sock_addr)
>sock.listen(5)
>print 'listening'
>
>f1 = open('parser.out', 'a')
>print "opening parser.out"
>f2 = open('data.in', 'a')
>print "opening data.in"
>f3 = open('messages.out', 'a')
>print "opening messages.out"
>
>while True:
># wait for a connection
>connection, client_address = sock.accept()
>q = dataRecv(connection)
>dataParse(q.next())
>
># close sockrx
>#connection.close()
>
>f1.close()
>
>

By the way, keep on breaking these things into functions

Re: [Tutor] Looping over histogram plots

2012-06-27 Thread Mark Lawrence

On 27/06/2012 08:47, Alan Gauld wrote:

On 27/06/12 00:32, Elaina Ann Hyde wrote:


Thanks for the comment, the set type is no problem for me, this is
just a variable that I call set... and it works great for my purposes,


It may work just now but if you ever decide you need to use a Python set
you will be unable to because you have effectively hidden that data
type. And it's unlikely to beimmediately obvious why its not working.
That's why its a bad idea to use the built-in type names as variables.

eg:

myList = [1,2,3,3,4,5,6,3,1,5]
myUniqueList = list(set(mylist)) # remove duplicates

In your program the second line would fail.
If you are confident you will never use sets then its not an issue, but
these decisions have a habit of coming back to bite you in the future!



And they always seem to bite the most tender part of the anatomy that 
they can find :)


--
Cheers.

Mark Lawrence.

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


Re: [Tutor] Looping over histogram plots

2012-06-27 Thread Steven D'Aprano
On Wed, Jun 27, 2012 at 08:47:08AM +0100, Alan Gauld wrote:
> On 27/06/12 00:32, Elaina Ann Hyde wrote:
> 
> > Thanks for the comment, the set type is no problem for me, this is
> >just a variable that I call set... and it works great for my purposes,
> 
> It may work just now but if you ever decide you need to use a Python set 
> you will be unable to because you have effectively hidden that data 
> type. And it's unlikely to beimmediately obvious why its not working. 
> That's why its a bad idea to use the built-in type names as variables.

This is called "shadowing a built-in", and is discouraged for exactly 
the reasons that Alan mentions.

It is much less risky to shadow built-ins inside small functions, so you 
are not surprised that the built-in doesn't work as expected.

When you do it deliberately to change the behaviour of a built-in, it is 
often called "monkey-patching"[1] which is a risky, sometimes useful but 
advanced technique.

Nevertheless, any of these cases should be used with care, and only if 
necessary.




[1] Sometimes called "raving insanity" 
*grin*

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


Re: [Tutor] Looping over histogram plots

2012-06-27 Thread Alan Gauld

On 27/06/12 00:32, Elaina Ann Hyde wrote:


 Thanks for the comment, the set type is no problem for me, this is
just a variable that I call set... and it works great for my purposes,


It may work just now but if you ever decide you need to use a Python set 
you will be unable to because you have effectively hidden that data 
type. And it's unlikely to beimmediately obvious why its not working. 
That's why its a bad idea to use the built-in type names as variables.


eg:

myList = [1,2,3,3,4,5,6,3,1,5]
myUniqueList = list(set(mylist))   # remove duplicates

In your program the second line would fail.
If you are confident you will never use sets then its not an issue, but 
these decisions have a habit of coming back to bite you in the future!


--
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] Looping over histogram plots

2012-06-26 Thread Elaina Ann Hyde
Yay Python:

The solution was a syntax one, if anyone else ever feels like massively
multi-plotting histograms, here is the working code:

#--
fig, axes = plt.subplots(nrows=5, ncols=6, figsize=(12,6))

index=0
for b in axes:
for ax in b:
index=index+1
set=(dat['a'+str(index)] == 1.00)
#write the data
n, bins, patches = ax.hist(VGSR[set], 30, normed=1)

#label the axis
if index==13.0:
ax.set_ylabel('counts')
if index >= 25.0:
ax.set_xlabel('VGSR')
plt.show()
#---

~Elaina Hyde
-- 
PhD Candidate
Department of Physics and Astronomy
Faculty of Science
Macquarie University
North Ryde, NSW 2109, Australia
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Looping over histogram plots

2012-06-26 Thread Elaina Ann Hyde
Dear Don,
Thanks for the comment, the set type is no problem for me, this is just
a variable that I call set... and it works great for my purposes, I do
suspect it is something in the way that matplotlib/pyplot deals with
histograms, but I have not so far been able to find the right syntax.
 Note, the first code example works great, it is only the second (with the
hist attempt) that does not do well.  It creates 29 blank plots and 1
histogram instead of 30 histograms... so probably it does need a different
phrasing, but the one you suggest gives invalid syntax.
~Elaina

On Tue, Jun 26, 2012 at 9:19 PM, Don Jennings  wrote:

> > Message: 1
> > Date: Tue, 26 Jun 2012 18:40:50 +1000
> > From: Elaina Ann Hyde 
> > To: tutor@python.org
> > Subject: [Tutor] Looping over histogram plots
>
> 
>
> >set=(dat['a'+str(index)] == 1.00)
>
> You should not override the builtin set() type [1] as you've done here by
> assigning it.
>
> > #write the data
> >P.hist(VGSR[set],bins=30, normed=True)
>
> I am not familiar with matplotlib, etc. but given that the primary
> difference in your two code samples is where you write the data, I suspect
> you want something like:
>
>ax.plot(P.hist(VGSR[set],bins=30, normed=True))
>
> Take care,
> Don
>
> [1] http://docs.python.org/library/stdtypes.html#set




-- 
PhD Candidate
Department of Physics and Astronomy
Faculty of Science
Macquarie University
North Ryde, NSW 2109, Australia
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Looping over histogram plots

2012-06-26 Thread Don Jennings
> Message: 1
> Date: Tue, 26 Jun 2012 18:40:50 +1000
> From: Elaina Ann Hyde 
> To: tutor@python.org
> Subject: [Tutor] Looping over histogram plots



>set=(dat['a'+str(index)] == 1.00)

You should not override the builtin set() type [1] as you've done here by 
assigning it.

> #write the data
>P.hist(VGSR[set],bins=30, normed=True)

I am not familiar with matplotlib, etc. but given that the primary difference 
in your two code samples is where you write the data, I suspect you want 
something like:

ax.plot(P.hist(VGSR[set],bins=30, normed=True))

Take care,
Don

[1] http://docs.python.org/library/stdtypes.html#set
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Looping

2009-04-20 Thread Paul McGuire
> 
> xrange was a kludge to improve on range's memory efficiency
> but it is a horrible name that obscures the code.
> 
> Also it does not exist in v3 so if you use it you will need to change
> the code for v3. It is as well to be as consistent with v3 as possible
> IMHO
> 
> Alan G

I have felt this way also (i.e., "xrange was a kludge" and "it is a horrible
name"), and have resisted the general adoption of xrange in my code.
Fortunately, I rarely use range, but iterate over sequences directly; or if
I absolutely need the item's index, I iterate over enumerate(seq).

But even if you use "range" exclusively, you may need to change code when
migrating to Python 3.  In Py2, range returns a list; in Py3 range returns
an iterator (a la Py2-xrange's behavior).  If you have code that uses the
value returned from range as a list, then in Py3 you will need to explicitly
convert it to a list using "list(range(n))".

I concur with Alan's suggestion that you code to Py3 semantics, but there
are certainly cases where xrange makes sense vs. range (such as doing some
sort of repetitive test 1e8 times, there is no sense in creating a
100-million entry list just to iterate over it).  So I'll propose some
usages for those who use range:

1. For Py2-Py3 range-xrange compatibility, add this code to the top of your
Python scripts:

try:
range = xrange
except NameError:
pass

In this way, your code under Py2 will use xrange whenever you call range,
and you will adopt the future-compatible range behavior.  (Hmm, maybe this
would have been a good option to add to the "future" module...)

2. In all cases where you really must use the result returned from range as
a list, ALWAYS write this as "list(range(n))", as in:

nonnegative_numbers_up_to_but_not_including_10 = list(range(10))
even_numbers_up_to_but_not_including_20 = list(range(0,20,2))

Using the "list(range(n))" form when you actually need a list will prepare
you for the change in idiom when you upgrade to Py3, and is fully Py2
compatible (even if you don't first bind xrange to range as in suggestion 1
- it simply copies the original list).  It also makes it very explicit that
you REALLY WANT THE RANGE AS A LIST, and not just as something for counting
up to n.

-- Paul


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


Re: [Tutor] Looping

2009-04-20 Thread Alan Gauld


"Matt"  wrote


As an aside, why use range rather than xrange? I was under the impression
that xrange is a generator and therefore more memory efficient.


xrange was a kludge to improve on range's memory efficiency
but it is a horrible name that obscures the code.

Also it does not exist in v3 so if you use it you will need to change
the code for v3. It is as well to be as consistent with v3 as possible
IMHO

Alan G





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


Re: [Tutor] Looping

2009-04-20 Thread W W
On Mon, Apr 20, 2009 at 12:34 PM, Matt

> wrote:

> Thank you. Func is in fact a call to an external non-python program. =]
> Therefore, the loop must actually be mindlessly done. My question, however,
> has been answered.
> As an aside, why use range rather than xrange? I was under the impression
> that xrange is a generator and therefore more memory efficient.
>

Probably because for small values (under 100), range just looks cleaner, and
as far as memory goes it's not a whole lot of difference.

AFAIK,
Wayne
-- 
To be considered stupid and to be told so is more painful than being called
gluttonous, mendacious, violent, lascivious, lazy, cowardly: every weakness,
every vice, has found its defenders, its rhetoric, its ennoblement and
exaltation, but stupidity hasn’t. - Primo Levi
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Looping

2009-04-20 Thread Matt
Thank you. Func is in fact a call to an external non-python program. =]
Therefore, the loop must actually be mindlessly done. My question, however,
has been answered.
As an aside, why use range rather than xrange? I was under the impression
that xrange is a generator and therefore more memory efficient.

On Mon, Apr 20, 2009 at 1:27 PM, Alan Gauld wrote:

> "Matt" > wrote
>
>  Let's say I want to run func 10 times Is there a more pythonic way to do
>> it
>> than this:
>> for i in xrange(10):
>> func()
>>
>
> Yes, use range() rather than xrange :-)
>
> But more seriously, as others have pointed out, if func() is well
> written then calling it ten times will have no effect over calling
> it once. (Except taking up 10 times as much time!)
>
> Its like saying
>
> for n in range(10):
>   x = 42
>
> The assignment is identical each time through the loop
>
> In fact it's worse than that because you don't even store the
> result of func() so it has no effect whatsoever on your program
> outside the loop. It would be more normal to do something like:
>
> for value in mycollection:
> result = func(somevalue)
>
> in other words apply func() to each value in a collection.
>
> So unless your func() really takes arguments or prints time
> related output or modifies global data (a bad practice) then
> what you are asking doesn't make much sense.
>
> Finally, if your function is really a program in disguise - ie it
> does all its own input/output then it would make more sense
> to put the loop inside the function and put the repeat count
> as a parameter:
>
> def func(repetitions):
>   for n in range(repetitions):
># your old func code here
>
> And call it:
>
> func(repetitions=10)   # use keyword for clarity of purpose
>
> HTH,
>
> --
> Alan Gauld
> Author of the Learn to Program web site
> http://www.alan-g.me.uk/
>
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Looping

2009-04-20 Thread Alan Gauld

"Matt"  wrote

Let's say I want to run func 10 times Is there a more pythonic way to do 
it

than this:
for i in xrange(10):
 func()


Yes, use range() rather than xrange :-)

But more seriously, as others have pointed out, if func() is well
written then calling it ten times will have no effect over calling
it once. (Except taking up 10 times as much time!)

Its like saying

for n in range(10):
   x = 42

The assignment is identical each time through the loop

In fact it's worse than that because you don't even store the
result of func() so it has no effect whatsoever on your program
outside the loop. It would be more normal to do something like:

for value in mycollection:
 result = func(somevalue)

in other words apply func() to each value in a collection.

So unless your func() really takes arguments or prints time
related output or modifies global data (a bad practice) then
what you are asking doesn't make much sense.

Finally, if your function is really a program in disguise - ie it
does all its own input/output then it would make more sense
to put the loop inside the function and put the repeat count
as a parameter:

def func(repetitions):
   for n in range(repetitions):
# your old func code here

And call it:

func(repetitions=10)   # use keyword for clarity of purpose

HTH,

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



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


Re: [Tutor] Looping

2009-04-20 Thread spir
Le Mon, 20 Apr 2009 17:26:30 +0200,
"A.T.Hofkamp"  s'exprima ainsi:

> Matt wrote:
> > Hey everyone,
> > 
> > First post to this list. I hope I'm doing it right.
> > 
> > Let's say I want to run func 10 times Is there a more pythonic way to do
> > it than this: for i in xrange(10):
> >  func()
> 
> no, that looks fine for your requirement.
> 
> What may be a bit weird here is the requirement to run the same function 10 
> times without further input/output parameters. I have never needed such a 
> construct.
> What kind of function do you have that needs to be called 10 times?

Actually, it's even rare to have to run a func n times, where n is known at 
runtime only. Builtin iteration (for item in container) removes 99% (about ;-) 
of such needs.

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


Re: [Tutor] Looping

2009-04-20 Thread A.T.Hofkamp

Matt wrote:

Hey everyone,

First post to this list. I hope I'm doing it right.

Let's say I want to run func 10 times Is there a more pythonic way to do it 
than this:
for i in xrange(10):
 func()


no, that looks fine for your requirement.

What may be a bit weird here is the requirement to run the same function 10 
times without further input/output parameters. I have never needed such a 
construct.

What kind of function do you have that needs to be called 10 times?


If you are doing timing experiments, the timeit library has a way of repeating 
the same experiment a number of times.



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


Re: [Tutor] Looping

2009-04-20 Thread W W
On Mon, Apr 20, 2009 at 8:48 AM, Matt

> wrote:

> Hey everyone,
>
> First post to this list. I hope I'm doing it right.
>
> Let's say I want to run func 10 times Is there a more pythonic way to do it
> than this:
> for i in xrange(10):
>  func()


AFAIK that's the most pythonic way to do it... and probably how I'd do it...
if I had a function I needed to run 10 times :P

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


Re: [Tutor] Looping, and Win32com.client

2008-12-19 Thread Andreas Kostyrka
Am Fri, 19 Dec 2008 15:57:49 +
schrieb Tim Golden :

> Eduardo Vieira wrote:
> > Hello, this is my first post in this list and I'm not a programmer,
> > but am enjoying learning python.
> > I'm trying to make a script to add worksheets to excel files:
> > I managed to implement this code:
> > 
> > import os
> > folder = 'C:\\Personal\\oldxlsformat\\'
> > from win32com.client import Dispatch
> > xl = Dispatch('Excel.Application')
> > xl.Application.AskToUpdateLinks = "False"
> > for ficheiro in os.listdir(folder):
> 
> 
> os.listdir returns a list of files relative to
> the directory in question. (Try it at the
> interpreter and see). Excel requires, pretty
> much, a list of absolute filenames. So try
> using something like os.path.join (folder, ficheiro)
> when opening in Excel.

The above should be enough, but if problems persists, it's often
helpful in Win32 OSes to use the 8.3 filename:

shortname = win32api.GetShortPathName(os.path.join(folder, ficheiro))

Another alternative would be to use glob:

import glob

...

for ficheiro in glob.glob(os.path.join(folder, "*.xls")):


glob.glob returns the full path that was found.

Andreas

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


Re: [Tutor] Looping, and Win32com.client

2008-12-19 Thread Tim Golden

Tim Golden wrote:

Eduardo Vieira wrote:

Hello, this is my first post in this list and I'm not a programmer,
but am enjoying learning python.
I'm trying to make a script to add worksheets to excel files:
I managed to implement this code:

import os
folder = 'C:\\Personal\\oldxlsformat\\'
from win32com.client import Dispatch
xl = Dispatch('Excel.Application')
xl.Application.AskToUpdateLinks = "False"
for ficheiro in os.listdir(folder):



os.listdir returns a list of files relative to
the directory in question. (Try it at the
interpreter and see). Excel requires, pretty
much, a list of absolute filenames.


Of course, I meant this it requires one absolute
filename, not a list :)

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


Re: [Tutor] Looping, and Win32com.client

2008-12-19 Thread Eduardo Vieira
Thank you, now it worked! I made these changes to my code:
for ficheiro in os.listdir(folder):
file = os.path.join(folder, ficheiro) #added this
if ficheiro.endswith('.xls'):
wb = xl.Workbooks.Open(file, 2) # changed this

On Fri, Dec 19, 2008 at 8:57 AM, Tim Golden  wrote:
> Eduardo Vieira wrote:
>>
>> Hello, this is my first post in this list and I'm not a programmer,
>> but am enjoying learning python.
>> I'm trying to make a script to add worksheets to excel files:
>> I managed to implement this code:
>>
>> import os
>> folder = 'C:\\Personal\\oldxlsformat\\'
>> from win32com.client import Dispatch
>> xl = Dispatch('Excel.Application')
>> xl.Application.AskToUpdateLinks = "False"
>> for ficheiro in os.listdir(folder):
>
>
> os.listdir returns a list of files relative to
> the directory in question. (Try it at the
> interpreter and see). Excel requires, pretty
> much, a list of absolute filenames. So try
> using something like os.path.join (folder, ficheiro)
> when opening in Excel.
>
> TJG
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Looping, and Win32com.client

2008-12-19 Thread Tim Golden

Eduardo Vieira wrote:

Hello, this is my first post in this list and I'm not a programmer,
but am enjoying learning python.
I'm trying to make a script to add worksheets to excel files:
I managed to implement this code:

import os
folder = 'C:\\Personal\\oldxlsformat\\'
from win32com.client import Dispatch
xl = Dispatch('Excel.Application')
xl.Application.AskToUpdateLinks = "False"
for ficheiro in os.listdir(folder):



os.listdir returns a list of files relative to
the directory in question. (Try it at the
interpreter and see). Excel requires, pretty
much, a list of absolute filenames. So try
using something like os.path.join (folder, ficheiro)
when opening in Excel.

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


Re: [Tutor] Looping + Variables

2007-10-21 Thread Martin Walsh
James wrote:
> Hi.  :)
>
> I'm trying to write a loop to simplify my life (and code :)).  The
> loop is going to iterate over a list of values that I have to change
> in a file.  I think my problem is better described with some code.  :)

Use a dictionary instead of a tuple ...

# variables
editValues = {
"interface": "eth0",
"address": "192.168.1.5",
"mask": "255.255.255.0",
"gateway": "192.168.1.1"
}

> def replaceText( old , new , file ):
>   for line in fileinput.FileInput( file , inplace = 1 ):
>   line = line.replace( old , new )
>   sys.stdout.write( line )
> 

for key in editValues.keys():
replaceText('$' + key + '$' ,
editValues[key] , '/etc/conf.d/net' )

> 
> config_$interface$=( "$address$ netmask $mask$" )
> routes_$interface$=( "default via $gateway$" )

Are you locked into this substitution format? If not, then how about
something like this:

# /etc/conf.d/net
config_%(interface)s=( "%(address)s netmask %(mask)s" )
routes_%(interface)s=( "default via %(gateway)s" )

You can then use python string formating (described here:
http://docs.python.org/lib/typesseq-strings.html), and pass the dict
directly. Note: if your file already contains '%' symbols that won't be
substituted, you must escape (prefix) them with an additional '%'.

valuedict = {
"interface": "eth0",
"address": "192.168.1.5",
"mask": "255.255.255.0",
"gateway": "192.168.1.1"
}

template = """\
# /etc/conf.d/net
config_%(interface)s=( "%(address)s netmask %(mask)s" )
routes_%(interface)s=( "default via %(gateway)s" )
"""

print template % valuedict

... prints ...

# /etc/conf.d/net
config_eth0=( "192.168.1.5 netmask 255.255.255.0" )
routes_eth0=( "default via 192.168.1.1" )

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


Re: [Tutor] looping problem

2006-09-23 Thread Kent Johnson
John Fouhy wrote:
> On 24/09/06, Python <[EMAIL PROTECTED]> wrote:
>> slices may be the best way to go
>> listA = biglist[0::3]   # start from index 0 taking every third element
>> listB = biglist[2::3]   # start from index 2 taking every third element
> 
> I'm not certain they would be.. If you do that, you will:
> 
> 1. Create a really big list.
> 2. Go through the list, taking every third element.
> 3. Go through the list again, taking every third+2 element.
> 
> If the list is really big, step 1. might take some time and/or space,
> and you would like to avoid it.

That's a good point, though the OP didn't seem to have a problem with 
memory.
> 
> If we have:
> 
> f2= open('myfile','r')
> listA = []
> listB = []
> 
> then we can iterate through f2 as follows:
> 
> for i, line in enumerate(f2):
> if i % 3 == 0 then
> listA.append(line)
> elif i % 3 == 2 then
> listB.append(line)
> 
> This may be faster..
> (although I should like to see evidence before committing to that
> statement :-) )

Since the end goal seems to be to create a dictionary, there is really 
no need to create the intermediate lists at all. You could do something 
like this (following your file example):

d = {}
while 1:
   try:
 key, _, value = f2.next(), f2.next(), f2.next()
 d[key] = value
   except StopIteration:
 pass

To do this with a list instead of a file use f2=iter(reallyBigList).

Kent

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


Re: [Tutor] looping problem

2006-09-23 Thread John Fouhy
On 24/09/06, Python <[EMAIL PROTECTED]> wrote:
> slices may be the best way to go
> listA = biglist[0::3]   # start from index 0 taking every third element
> listB = biglist[2::3]   # start from index 2 taking every third element

I'm not certain they would be.. If you do that, you will:

1. Create a really big list.
2. Go through the list, taking every third element.
3. Go through the list again, taking every third+2 element.

If the list is really big, step 1. might take some time and/or space,
and you would like to avoid it.

If we have:

f2= open('myfile','r')
listA = []
listB = []

then we can iterate through f2 as follows:

for i, line in enumerate(f2):
if i % 3 == 0 then
listA.append(line)
elif i % 3 == 2 then
listB.append(line)

This may be faster..
(although I should like to see evidence before committing to that
statement :-) )

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


Re: [Tutor] looping problem

2006-09-23 Thread Kent Johnson
kumar s wrote:
> hi, 
> 
> thank you. this is not a homework question. 
> 
> I have a very huge file of fasta sequence.
> 
> I want to create a dictionary where 'GeneName' as key
> and sequence of ATGC characters as value 
> 
> 
> biglist = dat.split('\t')
> ['GeneName ','','ATTAAGGCCAA'...]
> 
> Now I want to select ''GeneName ' into listA
> and 'ATTAAGGCCAA' into listB
> 
> so I want to select 0,3,6,9 elements into listA
> and 2,5,8,11 and so on elements into listB
> 
> then I can do dict(zip(listA,listB))
>
> however, the very loops concept is getting blanked out
> in my brain when I want to do this:
> 
> for j in range(len(biglist)):
> from here .. I cannot think anything..
> 
> may be it is just mental block.. thats the reason I
> seek help on forum. 

Lloyd has pointed you to slicing as the answer to your immediate 
question. However for the larger question of reading FASTA files, you 
might want to look at CoreBio, this is a new library of Python modules 
for computational biology that looks pretty good.
http://code.google.com/p/corebio/

CoreBio has built-in support for reading FASTA files into Seq objects. 
For example:

In [1]: import corebio.seq_io

In [2]: f=open(r'F:\Bio\BIOE48~1\KENTJO~1\SEQUEN~2\fasta\GI5082~1.FAS')

In [3]: seqs = corebio.seq_io.read(f)

seqs is now a list of Seq objects for each sequence in the original file
In this case there is only one sequence but it will work for your file also.

In [4]: for seq in seqs:
...: print seq.name
...: print seq
...:
...:
gi|50826|emb|CAA28242.1|
MIRTLLLSALVAGALSCGYPTYEVEDDVSRVVGGQEATPNTWPWQVSLQVLSSGRWRHNCGGSLVANNWVLTAAHCLSNYQTYRVLLGAHSLSNPGAGSAAVQVSKLVVHQRWNSQNVGNGYDIALIKLASPVTLSKNIQTACLPPAGTI
LPRNYVCYVTGWGLLQTNGNSPDTLRQGRLLVVDYATCSSASWWGSSVKSSMVCAGGDGVTSSCNGDSGGPLNCRASNGQWQVHGIVSFGSSLGCNYPRKPSVFTRVSNYIDWINSVMARN

In your case, you want a dict whose keys are the sequence name up to the 
first tab, and the values are the actual sequences. Something like this 
should work:
d = dict( (seq.name.split('\t')[0], seq) for seq in seqs)

The Seq class is a string subclass so putting the seq in the dict is 
what you want.

There is also an iterator to read sequences one at a time, this might be 
a little faster and more memory efficient because it doesn't have to 
create the big list of all sequences. Something like this (untested):

from corebio.seq_io.fasta_io import iterseq
f = open(...)
d = dict( (seq.name.split('\t')[0], seq) for seq in iterseq(f))

Kent

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


Re: [Tutor] looping problem

2006-09-23 Thread jim stockford
#!/usr/bin/python
# or whatever is the absolute path to python on your system

counter = 0
for  i  in "a","b","c","d","e","f","g" :
if counter%3 == 0 :
print i + " list one ", counter, counter%3
if counter%3 == 1 :
print i + " list two ", counter, counter%3
if counter%3 == 2 :
print i + " not used ", counter, counter%3
print "done"


On Sep 23, 2006, at 9:03 AM, kumar s wrote:

> hi,
>
> thank you. this is not a homework question.
>
> I have a very huge file of fasta sequence.
>
>> GeneName  \t 
> AATTAAGGAA..
>
> (1000 lines)
> AATAAGGA
>> GeneName  \t 
> GGAGAGAGATTAAGAA
> (15000 lines)
>
> when I read this as:
>
> f2= open('myfile','r')
> dat = f2.read().split('\n')
>
> turned out to be very expensive deal on computer.
>
> Instead I tried this:
>
> dat = f2.read()
>
> (reading into jumbo file of 19,100,442,1342 lines is
> easy but getting into what i want is a problem).
>
> I want to create a dictionary where 'GeneName' as key
> and sequence of ATGC characters as value
>
> biglist = dat.split('\t')
> ['GeneName ','','ATTAAGGCCAA'...]
>
> Now I want to select ''GeneName ' into listA
> and 'ATTAAGGCCAA' into listB
>
> so I want to select 0,3,6,9 elements into listA
> and 2,5,8,11 and so on elements into listB
>
> then I can do dict(zip(listA,listB))
>
> however, the very loops concept is getting blanked out
> in my brain when I want to do this:
>
> for j in range(len(biglist)):
> from here .. I cannot think anything..
>
> may be it is just mental block.. thats the reason I
> seek help on forum.
>
> Thanks
>
>
> --- jim stockford <[EMAIL PROTECTED]> wrote:
>
>> keep a counter in your loop. is this a homework
>> question?
>>
>> On Sep 23, 2006, at 8:34 AM, kumar s wrote:
>>
>>> hi,
>>>
>>> the reason could be that I did not quite
>> understand
>>> the concept of looping
>>>
>>> I have a list of 48 elements
>>>
>>> I want to create another two lists , listA and
>> listB
>>>
>>> I want to loop through the list with 48 elements
>> and
>>>
>>> select element with index 0,3,6,9,12 ..etc into
>> listA
>>>
>>> select elements with index 2,5,8,11 etc into
>> listB.
>>>
>>>
>>> Could any one help me how can I do that
>>>
>>> thankyou
>>>
>>> __
>>> Do You Yahoo!?
>>> Tired of spam?  Yahoo! Mail has the best spam
>> protection around
>>> http://mail.yahoo.com
>>> ___
>>> Tutor maillist  -  Tutor@python.org
>>> http://mail.python.org/mailman/listinfo/tutor
>>>
>>
>>
>
>
> __
> Do You Yahoo!?
> Tired of spam?  Yahoo! Mail has the best spam protection around
> http://mail.yahoo.com
>

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


Re: [Tutor] looping problem

2006-09-23 Thread Python
On Sat, 2006-09-23 at 09:03 -0700, kumar s wrote:
> hi, 
> 
> thank you. this is not a homework question. 
> 
> I have a very huge file of fasta sequence.
> 
> > GeneName  \t 
> AATTAAGGAA..
> 
> 
> 
> 
> 
> (1000 lines)
> AATAAGGA
> >GeneName  \t 
> GGAGAGAGATTAAGAA
> (15000 lines)
> 
> 
> 
> when I read this as:
> 
> f2= open('myfile','r')
> dat = f2.read().split('\n')
> 
> turned out to be very expensive deal on computer. 
> 
> 
> Instead I tried this:
> 
> dat = f2.read() 
> 
> (reading into jumbo file of 19,100,442,1342 lines is
> easy but getting into what i want is a problem). 
> 
> 
> I want to create a dictionary where 'GeneName' as key
> and sequence of ATGC characters as value 
> 
> 
> biglist = dat.split('\t')
> ['GeneName ','','ATTAAGGCCAA'...]
> 
> Now I want to select ''GeneName ' into listA
> and 'ATTAAGGCCAA' into listB
> 
> so I want to select 0,3,6,9 elements into listA
> and 2,5,8,11 and so on elements into listB
> 
> then I can do dict(zip(listA,listB))
> 
> 
> 
> however, the very loops concept is getting blanked out
> in my brain when I want to do this:
> 
> for j in range(len(biglist)):
> from here .. I cannot think anything..

slices may be the best way to go
listA = biglist[0::3]   # start from index 0 taking every third element
listB = biglist[2::3]   # start from index 2 taking every third element


> 
> may be it is just mental block.. thats the reason I
> seek help on forum. 
> 
> 
> Thanks
> 
> 
> 
> 
> 
> --- jim stockford <[EMAIL PROTECTED]> wrote:
> 
> > 
> > keep a counter in your loop. is this a homework
> > question?
> > 
> > On Sep 23, 2006, at 8:34 AM, kumar s wrote:
> > 
> > > hi,
> > >
> > > the reason could be that I did not quite
> > understand
> > > the concept of looping
> > >
> > > I have a list of 48 elements
> > >
> > > I want to create another two lists , listA and
> > listB
> > >
> > > I want to loop through the list with 48 elements
> > and
> > >
> > > select element with index 0,3,6,9,12 ..etc into
> > listA
> > >
> > > select elements with index 2,5,8,11 etc into
> > listB.
> > >
> > >
> > > Could any one help me how can I do that
> > >
> > > thankyou
> > >
> > > __
> > > Do You Yahoo!?
> > > Tired of spam?  Yahoo! Mail has the best spam
> > protection around
> > > http://mail.yahoo.com
> > > ___
> > > Tutor maillist  -  Tutor@python.org
> > > http://mail.python.org/mailman/listinfo/tutor
> > >
> > 
> > 
> 
> 
> __
> Do You Yahoo!?
> Tired of spam?  Yahoo! Mail has the best spam protection around 
> http://mail.yahoo.com 
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
-- 
Lloyd Kvam
Venix Corp

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


Re: [Tutor] looping problem

2006-09-23 Thread Bob Gailer
kumar s wrote:
> [snip]
> so I want to select 0,3,6,9 elements into listA
> and 2,5,8,11 and so on elements into listB
>
>   
Here's a hint:

for j in range(0, len(biglist), 3): # this will set j = 0, 3, 6, etc.

-- 
Bob Gailer
510-978-4454

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


Re: [Tutor] looping problem

2006-09-23 Thread kumar s
hi, 

thank you. this is not a homework question. 

I have a very huge file of fasta sequence.

> GeneName  \t 
AATTAAGGAA..





(1000 lines)
AATAAGGA
>GeneName  \t 
GGAGAGAGATTAAGAA
(15000 lines)



when I read this as:

f2= open('myfile','r')
dat = f2.read().split('\n')

turned out to be very expensive deal on computer. 


Instead I tried this:

dat = f2.read() 

(reading into jumbo file of 19,100,442,1342 lines is
easy but getting into what i want is a problem). 


I want to create a dictionary where 'GeneName' as key
and sequence of ATGC characters as value 


biglist = dat.split('\t')
['GeneName ','','ATTAAGGCCAA'...]

Now I want to select ''GeneName ' into listA
and 'ATTAAGGCCAA' into listB

so I want to select 0,3,6,9 elements into listA
and 2,5,8,11 and so on elements into listB

then I can do dict(zip(listA,listB))



however, the very loops concept is getting blanked out
in my brain when I want to do this:

for j in range(len(biglist)):
from here .. I cannot think anything..

may be it is just mental block.. thats the reason I
seek help on forum. 


Thanks





--- jim stockford <[EMAIL PROTECTED]> wrote:

> 
> keep a counter in your loop. is this a homework
> question?
> 
> On Sep 23, 2006, at 8:34 AM, kumar s wrote:
> 
> > hi,
> >
> > the reason could be that I did not quite
> understand
> > the concept of looping
> >
> > I have a list of 48 elements
> >
> > I want to create another two lists , listA and
> listB
> >
> > I want to loop through the list with 48 elements
> and
> >
> > select element with index 0,3,6,9,12 ..etc into
> listA
> >
> > select elements with index 2,5,8,11 etc into
> listB.
> >
> >
> > Could any one help me how can I do that
> >
> > thankyou
> >
> > __
> > Do You Yahoo!?
> > Tired of spam?  Yahoo! Mail has the best spam
> protection around
> > http://mail.yahoo.com
> > ___
> > Tutor maillist  -  Tutor@python.org
> > http://mail.python.org/mailman/listinfo/tutor
> >
> 
> 


__
Do You Yahoo!?
Tired of spam?  Yahoo! Mail has the best spam protection around 
http://mail.yahoo.com 
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] looping problem

2006-09-23 Thread jim stockford

keep a counter in your loop. is this a homework question?

On Sep 23, 2006, at 8:34 AM, kumar s wrote:

> hi,
>
> the reason could be that I did not quite understand
> the concept of looping
>
> I have a list of 48 elements
>
> I want to create another two lists , listA and listB
>
> I want to loop through the list with 48 elements and
>
> select element with index 0,3,6,9,12 ..etc into listA
>
> select elements with index 2,5,8,11 etc into listB.
>
>
> Could any one help me how can I do that
>
> thankyou
>
> __
> Do You Yahoo!?
> Tired of spam?  Yahoo! Mail has the best spam protection around
> http://mail.yahoo.com
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>

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


Re: [Tutor] Looping over lists of objects

2006-04-24 Thread Danny Yoo


On Mon, 24 Apr 2006, Etrade Griffiths wrote:

> just feeling my way into Python with a small app that reads data from 
> file, creates objects using that data, stores the objects in a list, 
> loops over the list doing comparison tests to filter out various 
> objects.  Here is a code snippet:
>
> class myObj:
>def __init__(self,a,b):
>self.a=a
>self.b=b
>
>def get_a(self):
>return self.a
>
>def get_b(self):
>return self.b

Hi Alun,

Looks ok so far.

Python specific tip: we can avoid writing getters and setters in Python. 
Python supports an alternative way to control how clients set and get 
attributes.  If you're interested, look for information on Python 
"properties".  So for now, I'd recommend simplifying this to:

##
class myObj:
def __init__(self,a,b):
self.a=a
self.b=b
##

until we get into a real need to set up explicit get/set methods.


> # Read data from file
>
> L1=[]
> nobj=0
>
> for line in input:
>L0=line.split()
>a=L0[1]
>b=L0[2]
>nobj=nobj+1
>
>an_obj=myObj(a,b)
>
>L1.append(an_obj)

There must be additional context here, in the sense that I don't know what 
'input' is.  I suspect this is a file of some sort.  So unfortunately, we 
won't be able to test the exact same situation that you have.


I'd recommend turning this into a function as well, just to make the 
commend superfluous:

##
def read_data_from_file(input):
 L1=[]
 nobj=0
 for line in input:
L0=line.split()
a=L0[1]
b=L0[2]
nobj=nobj+1
an_obj=myObj(a,b)
L1.append(an_obj)
 return L1, nobj
##

If we have this function, we can then test by doing:

#
L1, nobj = read_data_from_file(input)
#

and preserve the original behavior of our program.  (We may want to do 
some additional revision --- the nobj variable is also superfluous.)


> Trying to debug this using IDLE.  The calls x.get_a and x.get_b always 
> return zero so something is going wrong somewhere.  I think I'm either 
> not storing the objects correctly or retrieving them correctly but no 
> idea why!  All suggestions gratefully received!!!

I don't see anything horribly wrong with the code.  There are at least two 
possibilities when a problem comes up:

 * There's something wrong with the program (which might be the case,
   although I don't see it yet.)

 * The input to the program is weird.

I'll assume, for the moment, that the input may be weird.  *grin*


If we do have read_data_from_file() as function, we can test it by passing 
it hardcoded "files", and see that we get the myObj values we expect.

Here's one test to start you off:


import StringIO

def test1():
 sample_data = StringIO.StringIO("foo\tbar\tbaz\n")
 objs, nobjs = read_data_from_input(sample_data)
 assert (len(objs) == 1 == nobjs)
 first_object = objs[0]
 assert (first_object.a == "bar")
 assert (first_object.b == "baz")


(This uses the very useful StringIO module to disguise a string to make it 
look like a file.  See: 
http://www.python.org/doc/lib/module-StringIO.html)

Does this test case make sense to you?

If this test works out ok, then we've still made progress: we can at least 
know that our parser is working well.  That bolsters the possibility that 
the input we're getting from our other source is weird.


Good luck to you.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Looping over lists of objects

2006-04-24 Thread Etrade Griffiths
Ed

the problem is that my original code did not have the closing brackets for 
the method calls get_a and get_b whereas the code snippet I posted 
did.  That's probably why your version works and mine failed.  Thanks for 
your help!

Alun

At 17:19 24/04/2006, Ed Singleton wrote:
>On 24/04/06, Etrade Griffiths <[EMAIL PROTECTED]> wrote:
> >  Hi
> >
> >  just feeling my way into Python with a  small app that reads data from
> > file, creates objects using that data, stores the objects in a list, loops
> > over the list doing comparison tests to filter out various 
> objects.  Here is
> > a code snippet:
> >
>[snip]
> >
> >  Trying to debug this using IDLE.  The calls x.get_a and x.get_b always
> > return zero so something is going wrong somewhere.  I think I'm either not
> > storing the objects correctly or retrieving them correctly but no idea why!
> > All suggestions gratefully received!!!
>
>I added some test input to give the code below, and it works fine for
>me.  Can you give us some test input that fails for you?  Can you also
>show us your test() function as it may the code in there that is
>failing.
>
>Ed
>
>class myObj:
> def __init__(self,a,b):
> self.a=a
> self.b=b
>
> def get_a(self):
> return self.a
>
> def get_b(self):
> return self.b
>
>
>input = ["1 2 3", "4 5 6"]
>
>L1=[]
>nobj=0
>
>for line in input:
> L0=line.split()
> a=L0[1]
> b=L0[2]
> nobj=nobj+1
>
> an_obj=myObj(a,b)
>
> L1.append(an_obj)
>
># Filter data
>
>for i in range(1,nobj):
> for x in L1:# ... loop over all objects in list
> print "a -> ", x.get_a() # ... get value
>of a from current object
> print "b -> ", x.get_b()
>
>
>It returns:
>
>a ->  2
>b ->  3
>a ->  5
>b ->  6


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


Re: [Tutor] Looping over lists of objects

2006-04-24 Thread Ed Singleton
On 24/04/06, Etrade Griffiths <[EMAIL PROTECTED]> wrote:
>  Hi
>
>  just feeling my way into Python with a  small app that reads data from
> file, creates objects using that data, stores the objects in a list, loops
> over the list doing comparison tests to filter out various objects.  Here is
> a code snippet:
>
[snip]
>
>  Trying to debug this using IDLE.  The calls x.get_a and x.get_b always
> return zero so something is going wrong somewhere.  I think I'm either not
> storing the objects correctly or retrieving them correctly but no idea why!
> All suggestions gratefully received!!!

I added some test input to give the code below, and it works fine for
me.  Can you give us some test input that fails for you?  Can you also
show us your test() function as it may the code in there that is
failing.

Ed

class myObj:
def __init__(self,a,b):
self.a=a
self.b=b

def get_a(self):
return self.a

def get_b(self):
return self.b


input = ["1 2 3", "4 5 6"]

L1=[]
nobj=0

for line in input:
L0=line.split()
a=L0[1]
b=L0[2]
nobj=nobj+1

an_obj=myObj(a,b)

L1.append(an_obj)

# Filter data

for i in range(1,nobj):
for x in L1:# ... loop over all objects in list
print "a -> ", x.get_a() # ... get value
of a from current object
print "b -> ", x.get_b()


It returns:

a ->  2
b ->  3
a ->  5
b ->  6
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor