Re: [Tutor] List vs. Set:

2018-02-25 Thread Steven D'Aprano
On Sat, Feb 24, 2018 at 08:00:58PM +, James Lundy wrote:

> Could this be a bug in my Pycharm 3 compiler I have had mixed 
> experiences running the code.

As a general rule, any time you get an unexpected error and think "Could 
this be a bug in the compiler?", the chances are almost always "No".

Which is more likely?

- tens or hundreds of thousands of people have used this compiler, and 
never noticed this bug? or

- the bug is in my code?

Even for experts, the chances are that the bug is in their code. The 
difference between the expert and the beginner is that the expert has a 
good shot at recognising that one-in-a-million time that it actually is 
an undiscovered bug in the compiler.

In the case of your code, I think the problem is this line:

> gooddata.append({singleday[2], singleday[3], singleday[4], 
> singleday[5]})

In particular, the part between the curly brackets (braces):

# curly brackets make a set
{ singleday[2], ... }

makes a set. My guess is that you were intending a list:

# square brackets make a list
[ singleday[2], ... ]

But there's a better way to fix this. You are grabbing four items out of 
a list, in order. Python has a short-cut for doing that:

# the long way
[singleday[2], singleday[3], singleday[4], singleday[5]]

# the short (and faster!) way
singleday[2:6]

Notice that the first index (2) is included, but the second index (6) is 
excluded. While it might seem confusing at first, this actually helps 
prevent "off by one" errors.

So the troublesome line becomes:

gooddata.append(singleday[2:6])

and, I believe, that ought to fix the bug. Possibly, or possibly not, 
to reveal any more bugs... *smiles*


Regards,


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


Re: [Tutor] List vs. Set:

2018-02-25 Thread Mark Lawrence

On 24/02/18 20:00, James Lundy wrote:

To whom it may concern. This code is from Dr. John Keyser.


Please arrange for him to go on a programming course :-)




gooddata = []

for singleday in datalist:
 if (singleday[0] == day) and (singleday[1] == month):


Yuck, unneeded brackets disease.


 gooddata.append({singleday[2], singleday[3], singleday[4], 
singleday[5]})


That looks like a set to me.



# Perform analysis
minsofar = 120
maxsofar = -100
numgooddates = 1
sumofmin = 0
sumofmax = 0

# so singleday in datalist is a list while singleday in gooddata is a 
set?


Seems like it.



for singleday in gooddata:

 sumofmin += singleday[1]
 sumofmax += singleday[2]
 if singleday[1] < minsofar:
 minsofar = singleday[1]
 if singleday[2] > maxsofar:
 maxsofar = singleday[2]

Could this be a bug in my Pycharm 3 compiler I have had mixed experiences 
running the code.


I very much doubt that.



An insertion of a space after for singleday in gooddata: line 54 caused the 
program to run as desired, once, since other runs cause the error


Really, I don't see how?




Traceback (most recent call last):

   File "C:/Users/Dad/PycharmProjects/TopDownDesign/WeatherDataSpecialDay.py", line 
56, in 

 sumofmin += singleday[1]

TypeError: 'set' object does not support indexing

persist.

I will attach the code and test file. Please allow me to thank you in advance 
for answering this query. I am new with Python and would appreciate any advice.


Put print calls into the code that you don't show above.  This should 
show what gets written to the datalist and it's type, ditto for the 
gooddata list.  I think you'll find that the code "works" when an 
invalid day and month gets input, yet produces the traceback when a 
valid day and month is input.




God Bless:

James Lundy
jalu...@computer.org



--
My fellow Pythonistas, ask not what our language can do for you, ask
what you can do for our language.

Mark Lawrence

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


Re: [Tutor] List vs. Set:

2018-02-25 Thread Alan Gauld via Tutor
On 24/02/18 20:00, James Lundy wrote:
> To whom it may concern. This code is from Dr. John Keyser.

Since you don;t show us the complete program I will have
to make some assumptions...

> gooddata = []

This is degioned as a list by virtue of the []

> for singleday in datalist:
> if (singleday[0] == day) and (singleday[1] == month):
> gooddata.append({singleday[2], singleday[3], singleday[4], 
> singleday[5]})

This appends a set by virtue of the {}

The bracket type is what defines the data type.

> # Perform analysis
> minsofar = 120
> maxsofar = -100
> numgooddates = 1
> sumofmin = 0
> sumofmax = 0
> 
> # so singleday in datalist is a list while singleday in gooddata is a 
> set?

I don't know what singleday is since you don't show it's creation.
But singleday does not exist in gooddata. Instead you have created
a set that contains some elements from singleday. But those values
are copies that bear no relation to the original singleday elements.

> for singleday in gooddata:

This creates a new singleday object that is not related to the
original singleday. This one will be an instance of whatever
is in gooddata. In this case we know these are sets.

> sumofmin += singleday[1]

And you can't index a set. So you get an error.
If you want singleday to be a list you either need to insert
a list in the first loop or explicitly convert the set to
a list. But bear in mind that sets have no defined order
so you may not get the values out in the order you put
them in. And sets don;t allow duplicates so if two of
your original singleday values were identical one would
be thrown away.

I suspect you really wanted to use a list in the top
for loop:

if (singleday[0] == day) and (singleday[1] == month):
gooddata.append( [ singleday[2], singleday[3],
   singleday[4], singleday[5] ]
   )

Note however that the indexes will not be carried over, so in your
second loop singleday[1] refers to the old singleday[3].

If you want to retain the original indexes (and all the elements)
then just append singleday itself:

if (singleday[0] == day) and (singleday[1] == month):
gooddata.append( singleday )

> Could this be a bug in my Pycharm 3 compiler 

Nope, it is extremely unlikely that you will find a bug
in any compiler or interpreter(*). You should always assume
that the fault is in your code first and only consider
the compiler when all else has been eliminated.

(*)In 40 years of programming I've only once found
such a bug and it only manifested itself with a very
arcane - and slightly suspect - piece of code. Compilers
and interpreters tend to be very rigorously tested;
because they can be -  they have a very clearly defined
function.

> TypeError: 'set' object does not support indexing
> 
> persist.

Because you are creating a list of sets.
Change the set to a list and the problem will go away.

> I will attach the code and test file. 

The list server doesn't like attachments (although
text is usually OK) its better to paste things into
the message or provide a link to a web site)

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


[Tutor] List vs. Set:

2018-02-25 Thread James Lundy
To whom it may concern. This code is from Dr. John Keyser.


gooddata = []

for singleday in datalist:
if (singleday[0] == day) and (singleday[1] == month):
gooddata.append({singleday[2], singleday[3], singleday[4], 
singleday[5]})

# Perform analysis
minsofar = 120
maxsofar = -100
numgooddates = 1
sumofmin = 0
sumofmax = 0

# so singleday in datalist is a list while singleday in gooddata is a 
set?

for singleday in gooddata:

sumofmin += singleday[1]
sumofmax += singleday[2]
if singleday[1] < minsofar:
minsofar = singleday[1]
if singleday[2] > maxsofar:
maxsofar = singleday[2]

Could this be a bug in my Pycharm 3 compiler I have had mixed experiences 
running the code.

An insertion of a space after for singleday in gooddata: line 54 caused the 
program to run as desired, once, since other runs cause the error


Traceback (most recent call last):

  File "C:/Users/Dad/PycharmProjects/TopDownDesign/WeatherDataSpecialDay.py", 
line 56, in 

sumofmin += singleday[1]

TypeError: 'set' object does not support indexing

persist.

I will attach the code and test file. Please allow me to thank you in advance 
for answering this query. I am new with Python and would appreciate any advice.

God Bless:

James Lundy
jalu...@computer.org
## Read in Data 
# Open file
filename = input("Enter the name of the file: ")
infile = open(filename, 'r')
#print(infile.read())






# Read in data
datalist = []

for line in infile:
#get data form line
date, h, l, r = (line.split(','))
lowtemp = int(l)
hightemp = int(h)
rainfall = float(r)
m, d, y = date.split('/')
month = int(m)
day = int(d)
year = int(y)

#put data into list
datalist.append([day, month, year, lowtemp,hightemp, rainfall])



#Close file
infile.close()

## Analyze Data 
# Get Data of interest
month = int(input("For the date you care about, enter the month:"))
day = int(input("For the date you care about, enter the day: "))
# Fomd jostproca; data fpr date
gooddata = []

for singleday in datalist:
if (singleday[0] == day) and (singleday[1] == month):
gooddata.append({singleday[2], singleday[3], singleday[4], 
singleday[5]})

# Perform analysis
minsofar = 120
maxsofar = -100
numgooddates = 1
sumofmin = 0
sumofmax = 0

# so singleday in datalist is a list while singleday in gooddata is a 
set?

for singleday in gooddata:

sumofmin += singleday[1]
sumofmax += singleday[2]
if singleday[1] < minsofar:
minsofar = singleday[1]
if singleday[2] > maxsofar:
maxsofar = singleday[2]

avglow = sumofmin / numgooddates
avghigh = sumofmax / numgooddates


## Present results 
print ("There were", numgooddates,"days")
print ("The lowest", minsofar)
print ("The highet", maxsofar)
print ("The avaerage low has been", avglow)
print ("The average high", avghigh)


## Extra code for test #
# #greeting = "Howdy!How ar you today?I'm great!"
#lines = greeting.split('')
#for line in lines:
#print(line)

1/01/2000,79,37,0
1/02/2000,79,68,0
1/03/2000,73,60,0
1/04/2000,51,26,0
1/05/2000,57,19,0
1/06/2000,59,46,0.08
1/07/2000,58,35,2.08___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] list of functions

2017-03-30 Thread kay Cee
Greetings all,

I would like to use a list of functions for an automation project, and this
is the prototype I came up with
###
def func1():
print('func1')

def func2():
print('func2')

def func3():
print('func3')


func_list = ('func1', 'func2', 'func3')

for f in func_list:
eval(f)()
#

The output shows as intended, but I'd like to know if there are any safety
or performance issues using this prototype or if there is a better way to
acheive a list of functions.

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


[Tutor] Testing tutor list server

2016-09-20 Thread Alan Gauld via Tutor
Just checkin'

-- 
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] META: Moderation and subscription to the tutor list

2016-05-08 Thread Alan Gauld via Tutor
On 08/05/16 08:59, Alan Gauld via Tutor wrote:

> This means you can get
> - single emails (default)
> - emails plus digest

- digest and no emails

> - neither (this is my choice because I read via gmane)

Sorry, I missed an option...


-- 
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] META: Moderation and subscription to the tutor list

2016-05-08 Thread Steven D'Aprano
On Sun, May 08, 2016 at 08:59:01AM +0100, Alan Gauld via Tutor wrote:
> On 01/05/16 05:18, Steven D'Aprano wrote:
> 
> > ...(And I think we should default to 
> > individual emails, not daily digest.)
> 
> It took me a little while to find this one, but I've checked
> and the default is to receive individual emails. You need to
> opt-in to get the digests and opt-out to stop getting emails.

Thanks for checking!

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


Re: [Tutor] META: Moderation and subscription to the tutor list

2016-05-08 Thread Alan Gauld via Tutor
On 01/05/16 05:18, Steven D'Aprano wrote:

> ...(And I think we should default to 
> individual emails, not daily digest.)

It took me a little while to find this one, but I've checked
and the default is to receive individual emails. You need to
opt-in to get the digests and opt-out to stop getting emails.

This means you can get
- single emails (default)
- emails plus digest
- neither (this is my choice because I read via gmane)

-- 
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] "List" object is not callable

2016-05-01 Thread Jason N. via Tutor
Hello,
I figured out the issue. It was a silly mistake - i was not running the correct 
code; instead was running code from another program which was active on a 
second tab. Thank you. 

On Sunday, May 1, 2016 4:15 PM, Jason N. via Tutor  wrote:
 
 

 Thank you all for your responses. 
I am using Py 2.7 and this time I copied and pasted the code from here: 
http://www.opentechguides.com/how-to/article/python/57/python-ping-subnet.html 
to my system but received the same error when I ran it. 
You can see the error screenshot here: https://unsee.cc/sonezima/ Thank you. 

    On Saturday, April 30, 2016 11:12 PM, Steven D'Aprano  
wrote:
 
 

 On Sat, Apr 30, 2016 at 06:51:17PM +, Jason N. via Tutor wrote:
> Hello,
> I found this simple script online but when I execute it I get the 
> following error: "TypeError: 'list' object is not callable" Here is 
> the code sample:
>
> import subprocess
> ls_output= subprocess.check_output(['dir'])

The code snippet works fine.

Please check that the code you send is exactly the same as the code you 
are actually trying to run. Do not just retype the code from memory, 
copy and paste it.

Also, please copy and paste the full traceback that you get, not just 
the final error message. Everything from the first "Traceback" line to 
the end.

Finally, you should tell us what version of Python you are running, on 
what operating system (Linux, Mac OS, Windows XP, Windows 10, Android, 
something else), and whether you are using the standard Python 
interactive interpreter or something else (IDLE, iPython, Anaconda, 
PyCharm, etc.).


-- 
Steve
___
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


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


Re: [Tutor] "List" object is not callable

2016-05-01 Thread Jason N. via Tutor
Thank you all for your responses. 
I am using Py 2.7 and this time I copied and pasted the code from here: 
http://www.opentechguides.com/how-to/article/python/57/python-ping-subnet.html 
to my system but received the same error when I ran it. 
You can see the error screenshot here: https://unsee.cc/sonezima/ Thank you. 

On Saturday, April 30, 2016 11:12 PM, Steven D'Aprano  
wrote:
 
 

 On Sat, Apr 30, 2016 at 06:51:17PM +, Jason N. via Tutor wrote:
> Hello,
> I found this simple script online but when I execute it I get the 
> following error: "TypeError: 'list' object is not callable" Here is 
> the code sample:
>
> import subprocess
> ls_output= subprocess.check_output(['dir'])

The code snippet works fine.

Please check that the code you send is exactly the same as the code you 
are actually trying to run. Do not just retype the code from memory, 
copy and paste it.

Also, please copy and paste the full traceback that you get, not just 
the final error message. Everything from the first "Traceback" line to 
the end.

Finally, you should tell us what version of Python you are running, on 
what operating system (Linux, Mac OS, Windows XP, Windows 10, Android, 
something else), and whether you are using the standard Python 
interactive interpreter or something else (IDLE, iPython, Anaconda, 
PyCharm, etc.).


-- 
Steve
___
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] META: Moderation and subscription to the tutor list

2016-05-01 Thread Alan Gauld via Tutor
On 01/05/16 07:23, boB Stepp wrote:

> I am in agreement with this as well.  I have often wondered if
> newcomers are subscribed or not

Most are. Several who are not, subscribe very soon
after - presumably in response to the intro message.

>  as after subscription one receives a
> very helpful email which addresses most of the common post formatting
> issues that we seem to endlessly rehash.  Or perhaps I am one of the
> few who actually read it upon subscribing?

Probably most don't read it (all). But many simply are not
technically savvy enough to know how to post in plain text,
or avoid top posting etc. There are foreign concepts to many
of the modern generation of internet users.

> I wonder no matter which way the current matter gets decided, if it
> might be time to rewrite the automated response email.  

I'm open to suggestions on this. It has gradually grown over
the years as new caveats get added. A rewrite is something
that is within our remit and abilities without involving
the list admins.

> mentioned.  It probably should be added.  I feel that the interleaved
> writing style employed by many lists is completely foreign to
> newcomers to programming.

Absolutely. In fact even some programmers have never come
across it because it's not how most web forums (fora?) work.
And business email is now almost universally on Outlook/Exchange
and top posting is the norm.

-- 
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] META: Moderation and subscription to the tutor list

2016-05-01 Thread Alan Gauld via Tutor
On 01/05/16 10:06, Alan Gauld via Tutor wrote:

> Quite a lot of people use the digest service, especially lurkers.
> (A quick scan of the members lists suggests around 35-40%
> of all members use digest). I'd be reluctant to remove a
> service that is so widely used.

I've just had a look at the digest options and one possible option
is to send a Mime format digest rather than plain text. I'm not sure
what that would mean in practice but from experience on other
lists it may mean users see individual messages that they can reply to.
This would potentially avoid the long multi-message replies we currently
see. I don't know how it would affect threading.

I therefore propose to switch on MIME digest mode as a trial
at the end of next week if I don't hear a compelling reason
not to...

Hopefully most modern mail tools can handle MIME digests nowadays.

-- 
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] META: Moderation and subscription to the tutor list

2016-05-01 Thread Alan Gauld via Tutor
On 01/05/16 06:35, c...@zip.com.au wrote:

> There seems to me a subjectly large number of very short threads with a 
> question from someone, a couple of responses from list members, and no 
> further 
> reply.
> 
> To me this argues that either newcomers are not subscribed and probably do 
> not 
> see any responses, or that sufficient are discourteous enough or naive enough 
> to nothing bother to acknowledge help.

I suspect the latter...

-- 
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] META: Moderation and subscription to the tutor list

2016-05-01 Thread Alan Gauld via Tutor
On 01/05/16 05:18, Steven D'Aprano wrote:

> What's your policy here on the tutor list? 

I don't really have a policy. The list policy, set by
my predecessors, is to allow anyone to send mail and
encourage them to subscribe. All unsubscribed mail
goes to moderation (and there is not very much of it).

New subscribers are automatically put on moderation.
They are manually removed from moderation when they
post often enough that I recognize their ID and have
enough time/energy to visit the members page...

Replies can be seen by non subscribers in several
places including python.org, activestate.com and gmane.

> I think we should require 
> subscription before people can post. 

That doesn't achieve much since several lists servers
like gmane are subscribed so anyone on gmane etc can post
(albeit they go into the moderation queue). And the hassle
of subscribing may put some newbies off posting at all,
which we don't want.

> (And I think we should default to individual emails, 
> not daily digest.)

Quite a lot of people use the digest service, especially lurkers.
(A quick scan of the members lists suggests around 35-40%
of all members use digest). I'd be reluctant to remove a
service that is so widely used.

While modern mail tools generally have filters that can do
a similar job I do sympathise with digest users since I used
to be one of them and it was a useful way to keep the mail
count down. But they should take the time to post replies
'nicely'...


-- 
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] META: Moderation and subscription to the tutor list

2016-05-01 Thread boB Stepp
On Sun, May 1, 2016 at 12:35 AM,  <c...@zip.com.au> wrote:
> On 01May2016 14:18, Steven D'Aprano <st...@pearwood.info> wrote:
>>
>> Hi Alan,
>>
>> I thought I'd mention that the list-owners of "python-list" have now
>> decided to only allow people to post if they are subscribed to the list:
>>
>> https://mail.python.org/pipermail/python-list/2016-April/707571.html
>>
>> The motivation is to ensure that if people ask a question, and people
>> reply only to the list, the original poster has at least a chance of
>> seeing the replies.
>>
>> Of course, in the case of python-list, non-subscribers can just use the
>> Usenet interface (comp.lang.python, or Google Groups, or gmane). But
>> anyone using Usenet is presumably savvy enough to check for replies
>> using Usenet.
>>
>> What's your policy here on the tutor list? I think we should require
>> subscription before people can post. (And I think we should default to
>> individual emails, not daily digest.)
>
>
> I am not Alan, but personally I am +0.8 and +1 on these.
>
> I think requiring subscription ensures that users see responses. I don't
> know if tutor is already like that, and requiring subscription _does_ raise
> the bar for people coming for help. I would hope that any "please subscribe
> in order to post" list responses to newcomers was both welcoming and very
> clear on how to do it.

I am in agreement with this as well.  I have often wondered if
newcomers are subscribed or not as after subscription one receives a
very helpful email which addresses most of the common post formatting
issues that we seem to endlessly rehash.  Or perhaps I am one of the
few who actually read it upon subscribing?

I wonder no matter which way the current matter gets decided, if it
might be time to rewrite the automated response email.  I just got one
(again) after sending a different post and looking it over, it is
overly long and wordy, perhaps discouraging newcomers from actually
reading it?  Also, I note that the verboten "top posting" is never
mentioned.  It probably should be added.  I feel that the interleaved
writing style employed by many lists is completely foreign to
newcomers to programming.

> There seems to me a subjectly large number of very short threads with a
> question from someone, a couple of responses from list members, and no
> further reply.

> Finally, I would like to see digest simply not offered. They are a disaster.
> They break subject lines, threading and bury responses in noise.

+ infinity!

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


Re: [Tutor] META: Moderation and subscription to the tutor list

2016-05-01 Thread cs

On 01May2016 14:18, Steven D'Aprano <st...@pearwood.info> wrote:

Hi Alan,

I thought I'd mention that the list-owners of "python-list" have now
decided to only allow people to post if they are subscribed to the list:

https://mail.python.org/pipermail/python-list/2016-April/707571.html

The motivation is to ensure that if people ask a question, and people
reply only to the list, the original poster has at least a chance of
seeing the replies.

Of course, in the case of python-list, non-subscribers can just use the
Usenet interface (comp.lang.python, or Google Groups, or gmane). But
anyone using Usenet is presumably savvy enough to check for replies
using Usenet.

What's your policy here on the tutor list? I think we should require
subscription before people can post. (And I think we should default to
individual emails, not daily digest.)


I am not Alan, but personally I am +0.8 and +1 on these.

I think requiring subscription ensures that users see responses. I don't know 
if tutor is already like that, and requiring subscription _does_ raise the bar 
for people coming for help. I would hope that any "please subscribe in order to 
post" list responses to newcomers was both welcoming and very clear on how to 
do it.


There seems to me a subjectly large number of very short threads with a 
question from someone, a couple of responses from list members, and no further 
reply.


To me this argues that either newcomers are not subscribed and probably do not 
see any responses, or that sufficient are discourteous enough or naive enough 
to nothing bother to acknowledge help.


Finally, I would like to see digest simply not offered. They are a disaster.  
They break subject lines, threading and bury responses in noise.


Cheers,
Cameron Simpson <c...@zip.com.au>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] META: Moderation and subscription to the tutor list

2016-04-30 Thread Steven D'Aprano
Hi Alan,


I thought I'd mention that the list-owners of "python-list" have now 
decided to only allow people to post if they are subscribed to the list:

https://mail.python.org/pipermail/python-list/2016-April/707571.html


The motivation is to ensure that if people ask a question, and people 
reply only to the list, the original poster has at least a chance of 
seeing the replies.

Of course, in the case of python-list, non-subscribers can just use the 
Usenet interface (comp.lang.python, or Google Groups, or gmane). But 
anyone using Usenet is presumably savvy enough to check for replies 
using Usenet.

What's your policy here on the tutor list? I think we should require 
subscription before people can post. (And I think we should default to 
individual emails, not daily digest.)



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


Re: [Tutor] "List" object is not callable

2016-04-30 Thread Steven D'Aprano
On Sat, Apr 30, 2016 at 06:51:17PM +, Jason N. via Tutor wrote:
> Hello,
> I found this simple script online but when I execute it I get the 
> following error: "TypeError: 'list' object is not callable" Here is 
> the code sample:
>
> import subprocess
> ls_output= subprocess.check_output(['dir'])

The code snippet works fine.

Please check that the code you send is exactly the same as the code you 
are actually trying to run. Do not just retype the code from memory, 
copy and paste it.

Also, please copy and paste the full traceback that you get, not just 
the final error message. Everything from the first "Traceback" line to 
the end.

Finally, you should tell us what version of Python you are running, on 
what operating system (Linux, Mac OS, Windows XP, Windows 10, Android, 
something else), and whether you are using the standard Python 
interactive interpreter or something else (IDLE, iPython, Anaconda, 
PyCharm, etc.).


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


Re: [Tutor] "List" object is not callable

2016-04-30 Thread bob gailer

On 4/30/2016 3:27 PM, Alex Kleider wrote:



On 2016-04-30 11:51, Jason N. via Tutor wrote:

Hello,
I found this simple script online but when I execute it I get the
following error: "TypeError: 'list' object is not callable"
Here is the code sample:import subprocess

ls_output= subprocess.check_output(['dir'])

It works on my system: Ubuntu 14.04LTS

Works on my Windows 10 also.

Always post the traceback. The problem must lie in check_output as there 
is nothing in your code that could raise that exception.


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


Re: [Tutor] "List" object is not callable

2016-04-30 Thread Alex Kleider



On 2016-04-30 11:51, Jason N. via Tutor wrote:

Hello,
I found this simple script online but when I execute it I get the
following error: "TypeError: 'list' object is not callable"
Here is the code sample:import subprocess

ls_output= subprocess.check_output(['dir'])

It works on my system: Ubuntu 14.04LTS

(venv)alex@X301:~$ python
Python 3.4.3 (default, Oct 14 2015, 20:33:09)
[GCC 4.8.4] on linux
Type "help", "copyright", "credits" or "license" for more information.

import subprocess
ls_output= subprocess.check_output(['dir'])
ls_output
b'Airbnb\tBookSite  CURRENT  Documents  examples.desktop\tJs\t   
nextWIFI\t OpenWRT   Py\t   Solar  ToDo\t  WARNING\nARM\tC\t  debk\t 
  double gnupg.other\tLEFTOFFnode_modules  Pathagar  Rachel  
Templates  toDoAtLoft  wishes\nAVR\tclosures  Desktop  Downloads  
GPL\t\tLibreboot  Notes\t Pictures  SaskTest   Videos\t  
WWW\nbin\tContacts  Docbook  Encrypted  HTML5\t\tMusic\t   OLPC\t\t 
Publicski\t   tmp\t  vim_rewrap\n'

exit()

(venv)alex@X301:~$ dir
Airbnb	BookSite  CURRENT  Documents  examples.desktop	Js	   nextWIFI	 
OpenWRT   Py	   Solar  ToDo	  WARNING
ARM	C	  debk	   double gnupg.other	LEFTOFFnode_modules  Pathagar 
 Rachel  Templates  toDoAtLoft  wishes
AVR	closures  Desktop  Downloads  GPL		Libreboot  Notes	 Pictures  Sask  
  Test   Videos	  WWW
bin	Contacts  Docbook  Encrypted  HTML5		Music	   OLPC		 Publicski	  
 tmp	  vim_rewrap

(venv)alex@X301:~$ man dir


Perhaps you are using a linux command on a non linux (?Windows) system.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] "List" object is not callable

2016-04-30 Thread Jason N. via Tutor
Hello,
I found this simple script online but when I execute it I get the following 
error: "TypeError: 'list' object is not callable"
Here is the code sample:import subprocess

ls_output= subprocess.check_output(['dir'])
I searched online and found a another similar code sample 
(http://www.opentechguides.com/how-to/article/python/57/python-ping-subnet.html)
 but when I run it on my system I get the same error.Any feedback is very much 
appreciated.  Thank you.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] List of tuples

2016-04-20 Thread Alan Gauld via Tutor
On 19/04/16 21:56, isaac tetteh wrote:
> I have a list like this 

> [
> ("name",2344,34, "boy"),("another",345,47,"boy", "last")
> ]

Assuming this is list_tuple...

> for row in list_tuple:
> for row2 in row:
> return row

This can't work because return needs to be inside a function.
So you obviously are not showing us all of your code.
Also the code above would not give the error you report.

So we need to see the whole code and the whole error message.

Also can you explain how you want the output presented.
Do you want values returned from a function or do you want
them printed on screen or do you want them represented
by a string? Your mail suggests you wanted them printed
but your code suggests you want them returned from a
function. Which is it?


-- 
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] List of tuples

2016-04-20 Thread isaac tetteh
This a flask app that I am connecting to the mysql 

@app.route("/viewSingle", methods=['POST','GET'])
def SingleView():
formB=singleView()
data=[]
if request.method=="POST":
if formB.validate_on_submit:
#if request.form['submit']=="View CONTINENT":
c,conn = connection()
c.execute('''select * from Country''')
data = c.fetchall()
data=list(data)
for row in data:
for a in row:
return row  //this is the problem
#return str(data) 
#data=list(data)
c.close ()
conn.close ()
#return data
return render_template("view.html",data=data,formB=formB)

error 
ValueErrorValueError: too many values to unpackTraceback (most recent call 
last)File 
"/home/isaac/flasky/project_1/lib/python2.7/site-packages/flask/app.py", line 
1836, in __call__return self.wsgi_app(environ, start_response)File 
"/home/isaac/flasky/project_1/lib/python2.7/site-packages/flask/app.py", line 
1820, in wsgi_appresponse = self.make_response(self.handle_exception(e))File 
"/home/isaac/flasky/project_1/lib/python2.7/site-packages/flask/app.py", line 
1403, in handle_exceptionreraise(exc_type, exc_value, tb)File 
"/home/isaac/flasky/project_1/lib/python2.7/site-packages/flask/app.py", line 
1817, in wsgi_appresponse = self.full_dispatch_request()File 
"/home/isaac/flasky/project_1/lib/python2.7/site-packages/flask/app.py", line 
1478, in full_dispatch_requestresponse = self.make_response(rv)File 
"/home/isaac/flasky/project_1/lib/python2.7/site-packages/flask/app.py", line 
1563, in make_responserv, status, headers = rv + (None,) * (3 - 
len(rv))ValueError: too many values to unpack


> From: d...@hashcollision.org
> Date: Tue, 19 Apr 2016 15:01:41 -0700
> Subject: Re: [Tutor] List of tuples
> To: itette...@hotmail.com
> CC: tutor@python.org
> 
> On Tue, Apr 19, 2016 at 1:56 PM, isaac tetteh <itette...@hotmail.com> wrote:
> > I have a list like this
> > [
> > ("name",2344,34, "boy"),("another",345,47,"boy", "last")
> > ]
> > How do u get each value from it like
> > Output
> > name
> > 2344
> > 34
> > ...
> >
> > What i did was
> > for row in list_tuple:
> > for row2 in row:
> > return row
> >
> > But i get error  too many value to unpack
> 
> 
> Hi Issac,
> 
> Can you copy and paste the exact error message and stack trace that
> you're seeing?  Try not to paraphrase it: we need to see exactly the
> text is saying.  In some cases, we'll even pay attention to whitespace
> and other insanely silly details.  :P
> 
> Since that's tedious for you to retype, just use copy-and-paste.
> Include everything that the error message says, even if it doesn't
> make sense to you.  We'll try to help you interpret what the error is
> saying.  Unfortunately, you paraphrased the error message above too
> much: I have no good guesses from what you've presented so far.
> 
> Also, try to show the entire program that you ran as well.  The
> snippet you showed us is incomplete, because we don't know how the
> program defines "list_tuple".  Generally, you want to include enough
> detail when asking for help that it's really easy for the tutors here
> to "reproduce" your problem.  That way, we can see the same problem
> that you see.  That's important.
> 
> 
> My best guess so far, from all that you've shown us, is that a
> *different* part of the program is responsible for the error you're
> showing us.  That's why we need more details: I think something else
> other than what you're showing us is producing that error.  The reason
> I think so is because no part of the program you're showing us is
> doing tuple unpacking, at least from what I can tell.
  
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] List of tuples

2016-04-19 Thread Danny Yoo
Sorry for typos in response: on cell phone at the moment.  ;p
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] List of tuples

2016-04-19 Thread Danny Yoo
Okay, in the context of a function, the error you're seeing makes more
sense.

You need to ensure that the return value of the function is of the right
type.  In  SingleView, the intended return value appears to be a structured
response value.

Given that, then any other return statements in the body of the function
are suspect: return is a statement that will finish a function.

If a function returns a value of a tour that it isn't supposed to, expect
that to produce very strange error messages.  That's essentially what
you're seeing.

Looking at the construction of the response at the end:

> return render_template("view.html",data=data,formB=formB)
>

I'm wondering: perhaps you can collect the extracted column and add it as
an additional value in you're template?

If you have questions, please feel free to ask.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] List of tuples

2016-04-19 Thread Danny Yoo
On Tue, Apr 19, 2016 at 1:56 PM, isaac tetteh  wrote:
> I have a list like this
> [
> ("name",2344,34, "boy"),("another",345,47,"boy", "last")
> ]
> How do u get each value from it like
> Output
> name
> 2344
> 34
> ...
>
> What i did was
> for row in list_tuple:
> for row2 in row:
> return row
>
> But i get error  too many value to unpack


Hi Issac,

Can you copy and paste the exact error message and stack trace that
you're seeing?  Try not to paraphrase it: we need to see exactly the
text is saying.  In some cases, we'll even pay attention to whitespace
and other insanely silly details.  :P

Since that's tedious for you to retype, just use copy-and-paste.
Include everything that the error message says, even if it doesn't
make sense to you.  We'll try to help you interpret what the error is
saying.  Unfortunately, you paraphrased the error message above too
much: I have no good guesses from what you've presented so far.

Also, try to show the entire program that you ran as well.  The
snippet you showed us is incomplete, because we don't know how the
program defines "list_tuple".  Generally, you want to include enough
detail when asking for help that it's really easy for the tutors here
to "reproduce" your problem.  That way, we can see the same problem
that you see.  That's important.


My best guess so far, from all that you've shown us, is that a
*different* part of the program is responsible for the error you're
showing us.  That's why we need more details: I think something else
other than what you're showing us is producing that error.  The reason
I think so is because no part of the program you're showing us is
doing tuple unpacking, at least from what I can tell.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] List of tuples

2016-04-19 Thread isaac tetteh
I have a list like this 
[
("name",2344,34, "boy"),("another",345,47,"boy", "last")
]
How do u get each value from it like 
Output 
name
2344
34
...

What i did was 
for row in list_tuple:
for row2 in row:
return row

But i get error  too many value to unpack 

Please help

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


Re: [Tutor] my membership and access to the Tutor list

2015-05-12 Thread Alan Gauld

Forwarding to the list for comment.
Always use Reply All9Or Reply List if your mailer supports it)
when including the list members.

Alan G

On 12/05/15 11:24, Stewart Lawton wrote:

Hi Alan
 I have worked though the file permissions cogniscent of  your 
comments to see if  I can find what
is failing in apache access to a python created unix socket. Points 1) 
,..., 12) give the results.
In particular I do not understand how to set the user of uds_socket to 
apache or set the write permission of
uds_socket group to rwx. I think that either change should enable 
successful operation, comments please!

In answer to your other questions:
I chose Unix Sockets since I had very similar access problems with IP 
sockets.
I would like to remote control an embedded device from a laptop. The 
target will be Raspberrypi that in turn communicates to ARM Cortex M3 
devices that are capable of  correct Nyquist sampling, that Unix based 
devices cannot guarantee. I chose Python since it is so widely used 
and I need to learn that language processor. I appreciate there are 
many ways other ways of achieving this end but I think this one ought 
to work!

Many Thanks for your help,
Stewart Lawton

1) /etc/httpd/conf/httpd.conf species the apache server user and group 
as:-


# User/Group: The name (or #number) of the user/group to run httpd as.
# It is usually good practice to create a dedicated user and group for
# running httpd, as with most system services.
#
User apache
Group apache
2)apache is started with command sudo ./startapache that contains:-
systemctl start httpd.service

3) the process status of apache is found by command ps -el
the following is taken from the status report:-
F S   UID   PID  PPID  C PRI  NI ADDR SZ WCHAN  TTY TIME CMD
4 S 0  2226 1  0  80   0 -  7493 poll_s ? 00:00:00 httpd
5 S48  2227  2226  0  80   0 -  7493 inet_c ? 00:00:00 httpd
5 S48  2228  2226  0  80   0 -  7493 inet_c ? 00:00:00 httpd
5 S48  2229  2226  0  80   0 -  7493 inet_c ? 00:00:00 httpd
5 S48  2230  2226  0  80   0 -  7493 inet_c ? 00:00:00 httpd
5 S48  2233  2226  0  80   0 -  7493 inet_c ? 00:00:00 httpd
4) The user identity UID ,48,is used to find the user and group given 
in /etc/passwd :-

apache:x:48:48:Apache:/usr/share/httpd:/sbin/nologin
The user and group identies are given as 48:48 so the user and group 
are apache and apache.
5)The above hopefully establishes that the server has permissions on 
user and groups named as apache.
6)I created a test directory at /test to be used to contain the file 
node uds_socket.

drwxrwxr-x.   2 apache apache  4096 May 11 20:15 test
7) on starting the Socket server that listens for an incoming connection
the new uds_socket is created with user and group permissions as shown:-
srwxr-xr-x. 1 johnlawton apache 0 May 12 10:22 /test/uds_socket
8)I do not understand what function the s bit performs here.
  I note that group access cannot write the file.
9) When I execute the myUnix2.cgi script from /var/www/cgi_bin with 
johnlawton as user with primary group apache the script executes and 
the listening server responds correctly. I note johnlawton has rwx 
access but the group apache access is limited  to r-x.
10) When the apache server executes the myUnix2.cgi script failure 
results in failing to access the socket.
11) Summary. I think the server fails as it can only get group access 
and group access is limited to

r-x NO w permission.
12) How can I get UDS_Socket to be created with apache as user(hence 
allowing rwx) or enable apache group access with w permission?





*From:* Alan Gauld alan.ga...@btinternet.com
*To:* Stewart Lawton jstewartlaw...@yahoo.co.uk; tutor 
tutor@python.org

*Sent:* Friday, 8 May 2015, 10:33
*Subject:* Re: my membership and access to the Tutor list

On 08/05/15 09:09, Stewart Lawton wrote:
 Hi Alan
 Thank you very much for your response to my Tutor@python.org 
mailto:Tutor@python.org question.

 I thought my membership was complete and that I could log in to answer
 your comments.

The tutor list is a mailing list not a web forum. You don't login to 
answer

comments you  send an email reply. Use Reply to send to the individual
(as you've just done with me) or, more usually, use ReplyAll (or ReplyList
if your mail tool has that feature) to reply to everyone on the list.

Use plain text to preserve code layout and use interleaved posting
(as I'm doing here) rather than top-posting.

 I found I could not login again. PLEASE can you help to get my
 password reset?

Only you can change the password, its purely web based. I only
approve messages in the moderation queue, virtually nothing else.
But the password just gives you access to your admin settings.

 I think I am failing to understand what user and or group permissions
 are required between apache python, and the python myUnix2.cgi program
 I am using.

OK, I'm no expert here but several things about

Re: [Tutor] my membership and access to the Tutor list

2015-05-08 Thread Alan Gauld

On 08/05/15 09:09, Stewart Lawton wrote:

Hi Alan
Thank you very much for your response to my Tutor@python.org question.
I thought my membership was complete and that I could log in to answer 
your comments.


The tutor list is a mailing list not a web forum. You don't login to answer
comments you  send an email reply. Use Reply to send to the individual
(as you've just done with me) or, more usually, use ReplyAll (or ReplyList
if your mail tool has that feature) to reply to everyone on the list.

Use plain text to preserve code layout and use interleaved posting
(as I'm doing here) rather than top-posting.

I found I could not login again. PLEASE can you help to get my 
password reset?


Only you can change the password, its purely web based. I only
approve messages in the moderation queue, virtually nothing else.
But the password just gives you access to your admin settings.

I think I am failing to understand what user and or group permissions 
are required between apache python, and the python myUnix2.cgi program 
I am using.


OK, I'm no expert here but several things about your program
have me puzzled.

First remember that the web server will have its own user account
and thus your code is effectively being run by another user. So any
permissions on your files need to allow that user to have access.
This is obviously a security risk and the reason its best not to have
web programs accessing files in a users area but to copy any files
needed into the web server space.


This program script is listed below, hopefully with spaces corrected


Spacing is now legal, but you should increase the indentation to
make it more readable. Consider 2 spaces as the absolute minimum,
most people use 3 or 4. If you ever submit code to the Python
standard library it must use 4 spaces. One space makes the
indentation hard to line up and almost defeats the point of
having it.


path to uds_socket corrected as Felix Dietricl suggested may be and Issue.




1) From my user directory I issued the script Unix2.cgi to
a listening Unix sockets server and this worked OK.
2) the permissions of Unix2.cgi are:-
-rwxrwxrwx. 1 johnlawton johnlawton  987 May  7 17:55 myUnix2.cgi
This is not good from security but surely proves the script can execute if
permissions are not considered.
3)This file is copied to the apache cgi directory /var/www/cgi-bin 
with the permissions

forced as
-rwxrwxrwx. 1 johnlawton johnlawton 987 May  7 18:19 
../../../var/www/cgi-bin/myUnix2.cgi

4) Execution of the cgi script directly works OK.


OK, Permissions of the cgi script are not critical they just need to be
executable to the web server. So you could have ---r-xrwx and it should
be more secure and work OK. What is important is that you change
ownership to whatever the apache user account is (local config, I can't
help there you'll need to look at the files).


5) http is enabled in the fedora firewall
6)The apache server is started using sudo systemctl start httpd.service.
When firefox is used to have Unix2.cgi executed the localhost receives 
the following error report.


Traceback (most recent call last):

  File /var/www/cgi-bin/myUnix2.cgi, line 37, in module
creSockettoServer()
  File /var/www/cgi-bin/myUnix2.cgi, line 26, in creSockettoServer
sys.exit(1)
SystemExit: 1

7) The copy process of myUnix2.cgi from my user directory to 
/var/www/cgi-bin

but setting user and group to root with full permissions results in
-rwxrwxrwx. 1 root root 987 May  7 18:45 
../../../var/www/cgi-bin/myUnix2.cgi


OK, But I sincerely hope the web server is NOT running as root, that 
would be

a security disaster and a crackers paradise!

8)When firefox is used to have Unix2.cgi executed the localhost 
receives the

same error report given under 6).
9) summary since the 'o' permissions are forced to rwx the script 
should execute

no matter what use group are specified?
10) How do I establish neccessary cgi permissions?

The problems are not with your script but with the socket you are trying to
create, or the path to it. Its those permissions that likely need to be 
changed.

#!/usr/bin/env python
import cgi
import socket
import sys
def htmlTop():
 print(Content-type:text/html\n\n
 DOCTYPE html
 html lang=en
   head
   meta charset=utf-8 /
   title MyServer Template /title
   /head
   body)

def htmlTail():
 print(body/
   /html)

def creSockettoServer():
sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
server_address = '/home/johnlawton/workspace/myUnixSock/uds_socket'


I confess I've never used a socket like this, indeed I was only
vaguely aware of their existence! I assume you have previous
experience of using UNIX domain sockets (in C?) since there
is relatively little tutorial help out there.

I've always used sockets for IP and given an IP address to the socket.
So I can only guess what's going on in your case. Can I ask what you
are trying to do in your program that you need UNIX sockets? Just curious

Re: [Tutor] list semantics

2015-04-11 Thread Joel Goldstick
On Sat, Apr 11, 2015 at 1:41 PM, Jim Mooney cybervigila...@gmail.com wrote:
 Why does the first range convert to a list, but not the second?

 p = list(range(1,20)), (range(40,59))
 p
 ([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19],
  range(40, 59))

Assuming you are using python 3.x range is a generator, so it only
produces values if you iterate over it
 --
 Jim

 Stop, Harold! That bagel has radishes!
 Thank God, Mary - you've saved me again!
 ___
 Tutor maillist  -  Tutor@python.org
 To unsubscribe or change subscription options:
 https://mail.python.org/mailman/listinfo/tutor



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


Re: [Tutor] list semantics

2015-04-11 Thread Joel Goldstick
On Sat, Apr 11, 2015 at 3:21 PM, Steven D'Aprano st...@pearwood.info wrote:
 On Sun, Apr 12, 2015 at 05:09:43AM +1000, Steven D'Aprano wrote:

 Almost correct, but not quite. range, like xrange in Python 2, is not a
 generator, but a custom-made lazy sequence object.

 py gen()  # This actually is a generator.
 generator object gen at 0xb7bd7914
 py range(1, 10)  # This is not.
 range(1, 10)

 Oops, I forgot to show where gen() came from. Sorry about that, just a
 cut-and-paste error.

 py def gen():
 ... yield 1
 ...
 py gen()  # This actually is a generator.
 generator object gen at 0xb7bd7914

Thanks for the tip Steve


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



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


Re: [Tutor] list semantics

2015-04-11 Thread Timo

Op 11-04-15 om 19:41 schreef Jim Mooney:

Why does the first range convert to a list, but not the second?


p = list(range(1,20)), (range(40,59))
p

([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19],
  range(40, 59))




I'm not sure I understand correctly. This is what the top of help(range) 
says:



Help on class range in module builtins:

class range(object)
 |  range(stop) - range object
 |  range(start, stop[, step]) - range object
 |
 |  Return a virtual sequence of numbers from start to stop by step.


So range() returns a range object. In your example you convert the first 
one to a list with list(), but not the second, so it prints the range 
object.


 range(2)
range(0, 2)
 list(range(2))
[0, 1]

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


Re: [Tutor] list semantics

2015-04-11 Thread Steven D'Aprano
On Sat, Apr 11, 2015 at 10:41:28AM -0700, Jim Mooney wrote:
 Why does the first range convert to a list, but not the second?
 
  p = list(range(1,20)), (range(40,59))
  p
 ([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19],
  range(40, 59))

Why would the second convert to a list? You don't call list() on it.

You create a tuple, p, with two items. The first item is:

list(range(1, 20))

and the second item is:

range(40, 59)

so you end up with p being a tuple ([1, 2, 3, ..., 19], range(40, 59)).

The fact that you surround the second item with round brackets 
(parentheses) means nothing -- they just group the range object on its 
own. A bit like saying 1 + (2), which still evaluates as 3.



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


Re: [Tutor] list semantics

2015-04-11 Thread Steven D'Aprano
On Sun, Apr 12, 2015 at 05:09:43AM +1000, Steven D'Aprano wrote:

 Almost correct, but not quite. range, like xrange in Python 2, is not a 
 generator, but a custom-made lazy sequence object.
 
 py gen()  # This actually is a generator.
 generator object gen at 0xb7bd7914
 py range(1, 10)  # This is not.
 range(1, 10)

Oops, I forgot to show where gen() came from. Sorry about that, just a 
cut-and-paste error.

py def gen():
... yield 1
...
py gen()  # This actually is a generator.
generator object gen at 0xb7bd7914



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


[Tutor] list semantics

2015-04-11 Thread Jim Mooney
Why does the first range convert to a list, but not the second?

 p = list(range(1,20)), (range(40,59))
 p
([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19],
 range(40, 59))

-- 
Jim

Stop, Harold! That bagel has radishes!
Thank God, Mary - you've saved me again!
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] List comprehensions to search a list--amazing!

2015-03-23 Thread boB Stepp
On Thu, Mar 19, 2015 at 4:52 AM, Peter Otten __pete...@web.de wrote:
 Dave Angel wrote:

[...]
 By the way, if you were to use a plain old loop the expected speedup over
 the listcomp would be 2. You can break out of the loop when you have found
 the gap, after iterating over one half of the list on average.

 So for-loops are twice as amazing ;)

Actually, this was my first approach to solving the problem.

 The catch to a list comprehension is it has to visit all the elements,
 while a binary search would visit log-base-2 of them.  So instead of
 1 elements, you'd be searching about 14 items.

 For large lists, it'd probably be much quicker to use the bisect module.
 https://docs.python.org/3.4/library/bisect.html


 Check out bisect.bisect_left() and bisect.bisect_right()

 I don't see how to directly use those functions on a list which is
 reverse-sorted, but the source is available.  On my install, it's
 located at:

 /usr/lib/python3.4/bisect.py


 To back Dave's suggestion with some empirical data here are two ways to make
 bisect() work with a descending list (though if possible I would recommend
 that you change your script to use ascending lists).

I could easily do this, though the data naturally presents itself as I
stated originally.

 $ cat reverse_bisect2.py
 import bisect
 import random

 def break_listcomp(L, Vt):
 S = [i for i, V in enumerate(L) if L[i] = Vt = L[i + 1]]
 return S[0]

 def break_bisect_reverse(L, Vt):
 L.reverse()
 result = bisect.bisect(L, Vt)
 L.reverse()
 return len(L) - result -1

 class Items:
 def __init__(self, items):
 self.items = items
 def __len__(self):
 return len(self.items)
 def __getitem__(self, index):
 return self.items[len(self.items) - 1 - index]

 def break_bisect_virt(L, Vt):
 return len(L) - 1 - bisect.bisect(Items(L), Vt)

 random.seed(42)
 N = 10**6
 data = [random.randrange(N) for i in range(10**5)]
 data = data + data
 data.sort(reverse=True)
 sample = random.sample(data, 10)
 $

 break_bisect_reverse() reverses the list before and after applying bisect.
 This is still O(N), but the actual work is done in C.

 break_bisect_virt() wraps the actual list in a class that translates

 items[0] to items[len(items)-1]
 items[1] to items[len(items)-2]

Thank you for taking time to write this. I may have questions later.

 and so on, thus providing a reversed view of the list without moving any
 values. This severely slows down access to a single value, but as bisect
 needs much fewer lookups than the listcomp the overall result is still a
 massive speedup. The actual timings:

 $ python3 -m timeit -s 'from reverse_bisect2 import data, sample,
 break_listcomp as f' '[f(data, v) for v in sample]'
 10 loops, best of 3: 781 msec per loop

 $ python3 -m timeit -s 'from reverse_bisect2 import data, sample,
 break_bisect_reverse as f' '[f(data, v) for v in sample]'
 100 loops, best of 3: 15 msec per loop

 $ python3 -m timeit -s 'from reverse_bisect2 import data, sample,
 break_bisect_virt as f' '[f(data, v) for v in sample]'
 1000 loops, best of 3: 221 usec per loop

 So reverse/bisect is 50 times faster than the listcomp, and
 bisect/virt is 3500 times faster than the listcomp.

You present a compelling case!

 I expect that a prepackaged linear interpolation function from numpy/scipy
 can still do better, and also handle the corner cases correctly. To use such
 a function you may have to reverse order of the values.

This is not an option for me as I would not be allowed to install numpy/scipy.



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


Re: [Tutor] List comprehensions to search a list--amazing!

2015-03-23 Thread Dave Angel

On 03/23/2015 10:17 PM, Dave Angel wrote:

On 03/23/2015 09:42 PM, boB Stepp wrote:




Not really.  See Steve's


OOPS.  Peter's

 response for some numbers. If I had to guess,

I'd say that for lists over 100 items, you should use bisect or
equivalent.  But I'd also say you should have one algorithm in your
final code, even if it's sub-optimal for tiny lists.  If even a fraction
of the searches are going to be on a list of 10k items, you should
switch to a bisect approach.




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


Re: [Tutor] List comprehensions to search a list--amazing!

2015-03-23 Thread Steven D'Aprano
On Mon, Mar 23, 2015 at 08:42:23PM -0500, boB Stepp wrote:
 On Thu, Mar 19, 2015 at 12:10 AM, Dave Angel da...@davea.name wrote:
  The catch to a list comprehension is it has to visit all the elements, while
  a binary search would visit log-base-2 of them.  So instead of 1
  elements, you'd be searching about 14 items.
 
 I suspected as much, but had not verified this. Nonetheless, this may
 prove sufficiently fast. I will have to test this with my final data
 files. Right now I am using test cases, while I continue to design,
 check, rewrite, etc.
 
  For large lists, it'd probably be much quicker to use the bisect module.
  https://docs.python.org/3.4/library/bisect.html
 
 Can you give me a ballpark number for large, where this would start
 making a meaningful difference?

Tell us what you consider a meaningful difference :-)

What counts as too slow will depend on:

- what you are doing
- how often you are doing it
- what else you're doing at the same time
- what hardware you have to run it on
- whether you are running the program only once, or repeatedly

etc. E.g. taking 30 seconds to iterate over a billion items in a list is 
insignificant if this is part of a bigger program which takes twenty 
minutes to run, but critical if you are hoping to run the program 
thirty times a second, hundreds of times a day.

But I've never heard anyone complain that a program was too fast :-)

(Actually, that's not quite true. Sometimes if the user is expecting 
a program function to take a while, say Rebuild database, and it 
actually runs near instantaneously, it is indeed *too fast* because it 
can give the user the idea that the rebuild function isn't working. But 
that's a UI issue, not a speed issue.)

But if you twist my arm, and force me to pluck some round numbers from 
thin air, I would guess:

- for under ten items, a linear search will be insignificantly faster;

- for under a hundred items, there's no meaningful difference;

- for under a million items, binary search will be typically better but 
a linear search still acceptable (everything is fast for small N);

- for over a million items, linear search will typically be 
unacceptably slow.

For certain definitions of what's acceptable or not :-)



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


Re: [Tutor] List comprehensions to search a list--amazing!

2015-03-23 Thread boB Stepp
On Thu, Mar 19, 2015 at 12:10 AM, Dave Angel da...@davea.name wrote:
 The catch to a list comprehension is it has to visit all the elements, while
 a binary search would visit log-base-2 of them.  So instead of 1
 elements, you'd be searching about 14 items.

I suspected as much, but had not verified this. Nonetheless, this may
prove sufficiently fast. I will have to test this with my final data
files. Right now I am using test cases, while I continue to design,
check, rewrite, etc.

 For large lists, it'd probably be much quicker to use the bisect module.
 https://docs.python.org/3.4/library/bisect.html

Can you give me a ballpark number for large, where this would start
making a meaningful difference?

 Check out bisect.bisect_left() and bisect.bisect_right()

It looks like this should work. Thanks! I will investigate.

 I don't see how to directly use those functions on a list which is
 reverse-sorted, but the source is available.  On my install, it's located
 at:

 /usr/lib/python3.4/bisect.py

And I see this is available on my oldest Python installlation, 2.4.4, too.

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


Re: [Tutor] List comprehensions to search a list--amazing!

2015-03-23 Thread Dave Angel

On 03/23/2015 09:42 PM, boB Stepp wrote:

On Thu, Mar 19, 2015 at 12:10 AM, Dave Angel da...@davea.name wrote:

The catch to a list comprehension is it has to visit all the elements, while
a binary search would visit log-base-2 of them.  So instead of 1
elements, you'd be searching about 14 items.


I suspected as much, but had not verified this. Nonetheless, this may
prove sufficiently fast. I will have to test this with my final data
files. Right now I am using test cases, while I continue to design,
check, rewrite, etc.


For large lists, it'd probably be much quicker to use the bisect module.
https://docs.python.org/3.4/library/bisect.html


Can you give me a ballpark number for large, where this would start
making a meaningful difference?



Not really.  See Steve's response for some numbers. If I had to guess, 
I'd say that for lists over 100 items, you should use bisect or 
equivalent.  But I'd also say you should have one algorithm in your 
final code, even if it's sub-optimal for tiny lists.  If even a fraction 
of the searches are going to be on a list of 10k items, you should 
switch to a bisect approach.


I'd have to measure it, same as anyone.  And because of the 
reverse-ordering problem, you have to weigh the advantages of using a 
standard library (which is unlikely to be buggy), versus making an 
edited version which works directly on reversed lists.


It also can matter how many times you're searching the same list.  If 
you're going to be many lookups, it's worth keeping a reversed copy. 
You can reverse as simply as   rlist = mylist[::-1]




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


Re: [Tutor] List comprehensions to search a list--amazing!

2015-03-23 Thread Steven D'Aprano
On Mon, Mar 23, 2015 at 10:17:11PM -0400, Dave Angel wrote:
 On 03/23/2015 09:42 PM, boB Stepp wrote:

 Can you give me a ballpark number for large, where this would start
 making a meaningful difference?
 
 
 Not really.  See Steve's response for some numbers.

o_O

Have you borrowed Guido's Time Machine? I hadn't even finished writing 
my post???



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


Re: [Tutor] List comprehensions to search a list--amazing!

2015-03-20 Thread Peter Otten
Patrick Thunstrom wrote:

 The generalized problem:

 L = [V0, V1, ..., Vn], where V0 = V1 = V2 = ... = Vn .
 Find index i, such that V[i] = Vt = V[i + 1], where Vt is the test
 value being searched for. I need to know the indices i and i + 1,
 which I need to interpolate based on where Vt falls.

 The solution (As a sublist, S)  I worked out tonight after
 experimenting with comprehension syntax is:
 S = [i for i, V in enumerate(L) if L[i] = Vt = L[i + 1]]

 And, of course, the index i I need is:
 i = S[0]

 I tested this out with concrete examples in the interpreter, such as
 with a list, L:

 L = [item for item in range(1, 0, -1)]

 and trying different test values. It was blazingly fast, too!

 All I can say is: WOW!!!

 By the way, if you were to use a plain old loop the expected speedup over
 the listcomp would be 2. You can break out of the loop when you have
 found the gap, after iterating over one half of the list on average.

 So for-loops are twice as amazing ;)
 
 For the same basic speed up, a generator expression with a call to
 next() will produce similar results. Without the additional code to
 get the indexed item.
 
 index = (i for i, _ in enumerate(original_list) if original_list[i] =
 target = original_list[i + 1]).next()
 
 The only catch is it raises a StopIteration exception if no element
 fits the test.

In new code you shouldn't call the next() method (renamed __next__() in 
Python 3) explicitly. Use the next() builtin instead which also allows you 
to provide a default:


 exhausted = iter(())
 next(exhausted)
Traceback (most recent call last):
  File stdin, line 1, in module
StopIteration
 next(exhausted, default_value)
'default_value'


That said, rather than polishing the implementation of the inferior 
algorithm pick the better one.

Ceterum censeo bisect is the way to go here ;)

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


Re: [Tutor] List comprehensions to search a list--amazing!

2015-03-19 Thread Peter Otten
Dave Angel wrote:

 On 03/19/2015 12:20 AM, boB Stepp wrote:
 I hope extolling the beauty and power of Python on this list is
 allowed, because I have had a large WOW!!! moment tonight. I had a
 problem I was working on at work this afternoon. I have a list of ~
 10,000 floating point numbers, which run from largest to smallest.
 There are duplicates scattered throughout, so I might have something
 like: [5942.6789, 5942.6789, 5941.03, 5941.01, 5941.01, ... ],
 etc. I wanted to search the list for a test value, which, depending on
 the particular list (I can have many such lists, each different from
 the other.), could conceivably be anywhere within the given list. I
 needed to return the index where the list values change from being
 just greater than the test value to just less than the test value at
 the very next index position. I spent a good chunk of my afternoon
 writing a binary search function and wondering what theoretically the
 optimum search algorithm would be, got interrupted (as usual on this
 project), and decided to look at my books at home to see if a better
 solution would be staring at me from some book (Like there usually
 is!).

 I haven't studied list comprehensions formally yet, but a snippet of
 code in a book caught my eye where the author was discussing filtering
 data in a list. This led me to try:

 The generalized problem:

 L = [V0, V1, ..., Vn], where V0 = V1 = V2 = ... = Vn .
 Find index i, such that V[i] = Vt = V[i + 1], where Vt is the test
 value being searched for. I need to know the indices i and i + 1,
 which I need to interpolate based on where Vt falls.

 The solution (As a sublist, S)  I worked out tonight after
 experimenting with comprehension syntax is:
 S = [i for i, V in enumerate(L) if L[i] = Vt = L[i + 1]]

 And, of course, the index i I need is:
 i = S[0]

 I tested this out with concrete examples in the interpreter, such as
 with a list, L:

 L = [item for item in range(1, 0, -1)]

 and trying different test values. It was blazingly fast, too!

 All I can say is: WOW!!!

By the way, if you were to use a plain old loop the expected speedup over 
the listcomp would be 2. You can break out of the loop when you have found 
the gap, after iterating over one half of the list on average.

So for-loops are twice as amazing ;)

 That's very innovative.
 
 The catch to a list comprehension is it has to visit all the elements,
 while a binary search would visit log-base-2 of them.  So instead of
 1 elements, you'd be searching about 14 items.
 
 For large lists, it'd probably be much quicker to use the bisect module.
 https://docs.python.org/3.4/library/bisect.html
 
 
 Check out bisect.bisect_left() and bisect.bisect_right()
 
 I don't see how to directly use those functions on a list which is
 reverse-sorted, but the source is available.  On my install, it's
 located at:
 
 /usr/lib/python3.4/bisect.py
 

To back Dave's suggestion with some empirical data here are two ways to make 
bisect() work with a descending list (though if possible I would recommend 
that you change your script to use ascending lists).

$ cat reverse_bisect2.py
import bisect
import random

def break_listcomp(L, Vt):
S = [i for i, V in enumerate(L) if L[i] = Vt = L[i + 1]]
return S[0]

def break_bisect_reverse(L, Vt):
L.reverse()
result = bisect.bisect(L, Vt)
L.reverse()
return len(L) - result -1

class Items:
def __init__(self, items):
self.items = items
def __len__(self):
return len(self.items)
def __getitem__(self, index):
return self.items[len(self.items) - 1 - index]

def break_bisect_virt(L, Vt):
return len(L) - 1 - bisect.bisect(Items(L), Vt)

random.seed(42)
N = 10**6
data = [random.randrange(N) for i in range(10**5)]
data = data + data
data.sort(reverse=True)
sample = random.sample(data, 10)
$

break_bisect_reverse() reverses the list before and after applying bisect. 
This is still O(N), but the actual work is done in C.

break_bisect_virt() wraps the actual list in a class that translates

items[0] to items[len(items)-1]
items[1] to items[len(items)-2]

and so on, thus providing a reversed view of the list without moving any 
values. This severely slows down access to a single value, but as bisect 
needs much fewer lookups than the listcomp the overall result is still a 
massive speedup. The actual timings:

$ python3 -m timeit -s 'from reverse_bisect2 import data, sample, 
break_listcomp as f' '[f(data, v) for v in sample]'
10 loops, best of 3: 781 msec per loop

$ python3 -m timeit -s 'from reverse_bisect2 import data, sample, 
break_bisect_reverse as f' '[f(data, v) for v in sample]'
100 loops, best of 3: 15 msec per loop

$ python3 -m timeit -s 'from reverse_bisect2 import data, sample, 
break_bisect_virt as f' '[f(data, v) for v in sample]'
1000 loops, best of 3: 221 usec per loop

So reverse/bisect is 50 times faster than the listcomp, and
bisect/virt is 3500 times faster than the listcomp.

I expect 

Re: [Tutor] List comprehensions to search a list--amazing!

2015-03-19 Thread Patrick Thunstrom
 The generalized problem:

 L = [V0, V1, ..., Vn], where V0 = V1 = V2 = ... = Vn .
 Find index i, such that V[i] = Vt = V[i + 1], where Vt is the test
 value being searched for. I need to know the indices i and i + 1,
 which I need to interpolate based on where Vt falls.

 The solution (As a sublist, S)  I worked out tonight after
 experimenting with comprehension syntax is:
 S = [i for i, V in enumerate(L) if L[i] = Vt = L[i + 1]]

 And, of course, the index i I need is:
 i = S[0]

 I tested this out with concrete examples in the interpreter, such as
 with a list, L:

 L = [item for item in range(1, 0, -1)]

 and trying different test values. It was blazingly fast, too!

 All I can say is: WOW!!!

 By the way, if you were to use a plain old loop the expected speedup over
 the listcomp would be 2. You can break out of the loop when you have found
 the gap, after iterating over one half of the list on average.

 So for-loops are twice as amazing ;)

For the same basic speed up, a generator expression with a call to
next() will produce similar results. Without the additional code to
get the indexed item.

index = (i for i, _ in enumerate(original_list) if original_list[i] =
target = original_list[i + 1]).next()

The only catch is it raises a StopIteration exception if no element
fits the test.

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


Re: [Tutor] List comprehensions to search a list--amazing!

2015-03-18 Thread Mark Lawrence

On 19/03/2015 04:20, boB Stepp wrote:

I hope extolling the beauty and power of Python on this list is
allowed, because I have had a large WOW!!! moment tonight. I had a
problem I was working on at work this afternoon. I have a list of ~
10,000 floating point numbers, which run from largest to smallest.
There are duplicates scattered throughout, so I might have something
like: [5942.6789, 5942.6789, 5941.03, 5941.01, 5941.01, ... ],
etc. I wanted to search the list for a test value, which, depending on
the particular list (I can have many such lists, each different from
the other.), could conceivably be anywhere within the given list. I
needed to return the index where the list values change from being
just greater than the test value to just less than the test value at
the very next index position. I spent a good chunk of my afternoon
writing a binary search function and wondering what theoretically the
optimum search algorithm would be, got interrupted (as usual on this
project), and decided to look at my books at home to see if a better
solution would be staring at me from some book (Like there usually
is!).

I haven't studied list comprehensions formally yet, but a snippet of
code in a book caught my eye where the author was discussing filtering
data in a list. This led me to try:

The generalized problem:

L = [V0, V1, ..., Vn], where V0 = V1 = V2 = ... = Vn .
Find index i, such that V[i] = Vt = V[i + 1], where Vt is the test
value being searched for. I need to know the indices i and i + 1,
which I need to interpolate based on where Vt falls.

The solution (As a sublist, S)  I worked out tonight after
experimenting with comprehension syntax is:
S = [i for i, V in enumerate(L) if L[i] = Vt = L[i + 1]]

And, of course, the index i I need is:
i = S[0]

I tested this out with concrete examples in the interpreter, such as
with a list, L:

L = [item for item in range(1, 0, -1)]

and trying different test values. It was blazingly fast, too!

All I can say is: WOW!!!




How does the performance of your code compare to the bisect module 
https://docs.python.org/3/library/bisect.html#module-bisect ?


--
My fellow Pythonistas, ask not what our language can do for you, ask
what you can do for our language.

Mark Lawrence

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


[Tutor] List comprehensions to search a list--amazing!

2015-03-18 Thread boB Stepp
I hope extolling the beauty and power of Python on this list is
allowed, because I have had a large WOW!!! moment tonight. I had a
problem I was working on at work this afternoon. I have a list of ~
10,000 floating point numbers, which run from largest to smallest.
There are duplicates scattered throughout, so I might have something
like: [5942.6789, 5942.6789, 5941.03, 5941.01, 5941.01, ... ],
etc. I wanted to search the list for a test value, which, depending on
the particular list (I can have many such lists, each different from
the other.), could conceivably be anywhere within the given list. I
needed to return the index where the list values change from being
just greater than the test value to just less than the test value at
the very next index position. I spent a good chunk of my afternoon
writing a binary search function and wondering what theoretically the
optimum search algorithm would be, got interrupted (as usual on this
project), and decided to look at my books at home to see if a better
solution would be staring at me from some book (Like there usually
is!).

I haven't studied list comprehensions formally yet, but a snippet of
code in a book caught my eye where the author was discussing filtering
data in a list. This led me to try:

The generalized problem:

L = [V0, V1, ..., Vn], where V0 = V1 = V2 = ... = Vn .
Find index i, such that V[i] = Vt = V[i + 1], where Vt is the test
value being searched for. I need to know the indices i and i + 1,
which I need to interpolate based on where Vt falls.

The solution (As a sublist, S)  I worked out tonight after
experimenting with comprehension syntax is:
S = [i for i, V in enumerate(L) if L[i] = Vt = L[i + 1]]

And, of course, the index i I need is:
i = S[0]

I tested this out with concrete examples in the interpreter, such as
with a list, L:

L = [item for item in range(1, 0, -1)]

and trying different test values. It was blazingly fast, too!

All I can say is: WOW!!!


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


Re: [Tutor] List comprehensions to search a list--amazing!

2015-03-18 Thread Dave Angel

On 03/19/2015 12:20 AM, boB Stepp wrote:

I hope extolling the beauty and power of Python on this list is
allowed, because I have had a large WOW!!! moment tonight. I had a
problem I was working on at work this afternoon. I have a list of ~
10,000 floating point numbers, which run from largest to smallest.
There are duplicates scattered throughout, so I might have something
like: [5942.6789, 5942.6789, 5941.03, 5941.01, 5941.01, ... ],
etc. I wanted to search the list for a test value, which, depending on
the particular list (I can have many such lists, each different from
the other.), could conceivably be anywhere within the given list. I
needed to return the index where the list values change from being
just greater than the test value to just less than the test value at
the very next index position. I spent a good chunk of my afternoon
writing a binary search function and wondering what theoretically the
optimum search algorithm would be, got interrupted (as usual on this
project), and decided to look at my books at home to see if a better
solution would be staring at me from some book (Like there usually
is!).

I haven't studied list comprehensions formally yet, but a snippet of
code in a book caught my eye where the author was discussing filtering
data in a list. This led me to try:

The generalized problem:

L = [V0, V1, ..., Vn], where V0 = V1 = V2 = ... = Vn .
Find index i, such that V[i] = Vt = V[i + 1], where Vt is the test
value being searched for. I need to know the indices i and i + 1,
which I need to interpolate based on where Vt falls.

The solution (As a sublist, S)  I worked out tonight after
experimenting with comprehension syntax is:
S = [i for i, V in enumerate(L) if L[i] = Vt = L[i + 1]]

And, of course, the index i I need is:
i = S[0]

I tested this out with concrete examples in the interpreter, such as
with a list, L:

L = [item for item in range(1, 0, -1)]

and trying different test values. It was blazingly fast, too!

All I can say is: WOW!!!




That's very innovative.

The catch to a list comprehension is it has to visit all the elements, 
while a binary search would visit log-base-2 of them.  So instead of 
1 elements, you'd be searching about 14 items.


For large lists, it'd probably be much quicker to use the bisect module.
https://docs.python.org/3.4/library/bisect.html


Check out bisect.bisect_left() and bisect.bisect_right()

I don't see how to directly use those functions on a list which is 
reverse-sorted, but the source is available.  On my install, it's 
located at:


/usr/lib/python3.4/bisect.py

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


Re: [Tutor] List of ints

2015-03-04 Thread Albert-Jan Roskam


- Original Message -

 From: Mark Lawrence breamore...@yahoo.co.uk
 To: tutor@python.org
 Cc: 
 Sent: Wednesday, March 4, 2015 10:20 AM
 Subject: Re: [Tutor] List of ints
 
 On 04/03/2015 00:25, Steven D'Aprano wrote:
  On Tue, Mar 03, 2015 at 04:50:41PM +1000, Phil wrote:
 
  count [0] += 1
 
  This fails with the following error;
 
  TypeError: 'int' object is not iterable
 
  I know that others have already solved the problem, but here is
  something which might help you solve similar problems in the future.
  The way to debug simple things like this is quite simple:
 
  print count[0]
 
  which will show you that count[0] is a list [0], not an int 0, and you
  are trying to add [0]+1 which doesn't work.
 
  Never under-estimate the usefulness of a few print calls when debugging.
 
 
 
 About time we threw in the use of the interactive interpreter for trying 
 code snippets as well, just for good measure :)


Perhaps both at the same time using the PDB debugger from within IPython?

%run -d -b line number myscript.py

d = debug, b = breakpoint

inside pdb: c = continue, q = quit, p = print, r = return value of current 
function, s = step, and more: https://docs.python.org/2/library/pdb.html
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] List of ints

2015-03-04 Thread Alan Gauld

On 03/03/15 23:44, Mark Lawrence wrote:


Having never heard of QPython I've just looked it up, so for those who
don't know from http://qpython.com/ it's a script engine which runs
Python programs on android devices.  I doubt if there is much
experience on this list with it although you might get lucky.



I have QPython on my Android phone. It's not much good for development 
but its ok for running a few basic Python scripts. Obviously GUIs etc 
won't work but file processing and the like are fine.


But I certainly wouldn't try programming in it! But then I don't
do any programming on my phone anyway. On my tablet I use vim as editor 
and Qpython to run the code but its still not an experience I recommend.


--
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] List of ints

2015-03-04 Thread Mark Lawrence

On 04/03/2015 00:25, Steven D'Aprano wrote:

On Tue, Mar 03, 2015 at 04:50:41PM +1000, Phil wrote:


count [0] += 1

This fails with the following error;

TypeError: 'int' object is not iterable


I know that others have already solved the problem, but here is
something which might help you solve similar problems in the future.
The way to debug simple things like this is quite simple:

print count[0]

which will show you that count[0] is a list [0], not an int 0, and you
are trying to add [0]+1 which doesn't work.

Never under-estimate the usefulness of a few print calls when debugging.




About time we threw in the use of the interactive interpreter for trying 
code snippets as well, just for good measure :)


--
My fellow Pythonistas, ask not what our language can do for you, ask
what you can do for our language.

Mark Lawrence

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


Re: [Tutor] List of ints

2015-03-03 Thread Phil

On 03/03/15 17:46, Mark Lawrence wrote:


You are trying to increment the first element of count which is itself a
list containing one element.  You actually need:-

count[0][0] +=1



Thank you Lawrence, Alan, and Danny,

The solution is embarrassingly obvious. It's been a long time since I've 
attempted any programming and I'd even forgotten that I needed a nested 
loop to access the cells in a two-dimensional array, or list. In this 
case I didn't need a two-dimensional array anyway.


I'd been away from home for five weeks and during a quiet period I 
installed QPython on my tablet with the aim of porting a programme that 
I'd written in C++ 15 years ago to Python. Cutting and pasting and even 
moving around the IDE turned out to be a truly frustrating exercise.


I wonder if it was just my clumsiness or if others have had the same 
experience?


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


Re: [Tutor] List of ints

2015-03-03 Thread Mark Lawrence

On 03/03/2015 23:09, Phil wrote:

On 03/03/15 17:46, Mark Lawrence wrote:


You are trying to increment the first element of count which is itself a
list containing one element.  You actually need:-

count[0][0] +=1



Thank you Lawrence, Alan, and Danny,

The solution is embarrassingly obvious. It's been a long time since I've
attempted any programming and I'd even forgotten that I needed a nested
loop to access the cells in a two-dimensional array, or list. In this
case I didn't need a two-dimensional array anyway.

I'd been away from home for five weeks and during a quiet period I
installed QPython on my tablet with the aim of porting a programme that
I'd written in C++ 15 years ago to Python. Cutting and pasting and even
moving around the IDE turned out to be a truly frustrating exercise.

I wonder if it was just my clumsiness or if others have had the same
experience?



Having never heard of QPython I've just looked it up, so for those who 
don't know from http://qpython.com/ it's a script engine which runs 
Python programs on android devices.  I doubt if there is much 
experience on this list with it although you might get lucky.


I am aware though of http://bugs.python.org/issue23496 Steps for 
Android Native Build of Python 3.4.2 which may be of interest.


--
My fellow Pythonistas, ask not what our language can do for you, ask
what you can do for our language.

Mark Lawrence

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


Re: [Tutor] List of ints

2015-03-03 Thread Steven D'Aprano
On Tue, Mar 03, 2015 at 04:50:41PM +1000, Phil wrote:

 count [0] += 1
 
 This fails with the following error;
 
 TypeError: 'int' object is not iterable

I know that others have already solved the problem, but here is 
something which might help you solve similar problems in the future. 
The way to debug simple things like this is quite simple:

print count[0]

which will show you that count[0] is a list [0], not an int 0, and you 
are trying to add [0]+1 which doesn't work.

Never under-estimate the usefulness of a few print calls when debugging.


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


Re: [Tutor] List of ints

2015-03-03 Thread Steven D'Aprano
On Wed, Mar 04, 2015 at 09:09:03AM +1000, Phil wrote:

 I'd been away from home for five weeks and during a quiet period I 
 installed QPython on my tablet with the aim of porting a programme that 
 I'd written in C++ 15 years ago to Python. Cutting and pasting and even 
 moving around the IDE turned out to be a truly frustrating exercise.

I don't actually know QPython, but in general, using a tablet or a smart 
phone is only acceptable for the most trivial actions. Fine if you're 
taping out a 15 character tweet with one finger, not so useful if you 
want to get real work done.



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


Re: [Tutor] List of ints

2015-03-03 Thread Alan Gauld

On 03/03/15 06:50, Phil wrote:


I'd like to set up a two dimensional list of counters as follows;

count = [ [0], [0], [0] ]

And then increment the first counter as follows;

count [0] += 1


Are you trying to increment the zero to make it 1?
Or are you trying to add a new value, 1, to the first sublist?
ie Do you want the output to be:

count = [ [1], [0], [0] ]

OR

count = [ [0,1], [0], [0] ]

To do the first you need to increment the *value* of
the first sublist not the sublist:

count[0][0] += 1

To do the second you must use append():

count[0].append(1)


The array module looks like the answer because it seems to function in
the same way as an array under C.


The array module is pretty specialized, in most cases a simple
list is a better solution.


Is there a way to add a value to a list of ints?


Yes, see above.

--
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] List of ints

2015-03-03 Thread Danny Yoo
On Mon, Mar 2, 2015 at 10:50 PM, Phil phil_...@bigpond.com wrote:
 Thank you for reading this.
 Python 3 under Linux.

 I'd like to set up a two dimensional list of counters as follows;

 count = [
 [0],
 [0],
 [0]
 ]



Can you explain why the list is two-dimensional?  It's not quite clear
why.  Do you have a particular use case in mind?



 Is there a way to add a value to a list of ints?

Can you give an example of what you'd like to see?  Unfortunately, the
word add is too ambiguous to know what the expectations are.  If you
can disambiguate with concrete examples, that may help us.


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


Re: [Tutor] List of ints

2015-03-02 Thread Mark Lawrence

On 03/03/2015 06:50, Phil wrote:

Thank you for reading this.
Python 3 under Linux.

I'd like to set up a two dimensional list of counters as follows;

count = [
 [0],
 [0],
 [0]
 ]

And then increment the first counter as follows;

count [0] += 1

This fails with the following error;

TypeError: 'int' object is not iterable

The array module looks like the answer because it seems to function in
the same way as an array under C. However, it seems to me that I should
be able to do the same thing with a list.

Is there a way to add a value to a list of ints?



You are trying to increment the first element of count which is itself a 
list containing one element.  You actually need:-


count[0][0] +=1

--
My fellow Pythonistas, ask not what our language can do for you, ask
what you can do for our language.

Mark Lawrence

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


[Tutor] List of ints

2015-03-02 Thread Phil

Thank you for reading this.
Python 3 under Linux.

I'd like to set up a two dimensional list of counters as follows;

count = [
[0],
[0],
[0]
]

And then increment the first counter as follows;

count [0] += 1

This fails with the following error;

TypeError: 'int' object is not iterable

The array module looks like the answer because it seems to function in 
the same way as an array under C. However, it seems to me that I should 
be able to do the same thing with a list.


Is there a way to add a value to a list of ints?

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


Re: [Tutor] list comprehension with else

2015-01-19 Thread Sydney Shall

On 19/01/2015 00:55, Steven D'Aprano wrote:

On Sun, Jan 18, 2015 at 02:20:55PM -0800, Danny Yoo wrote:

Just to add, log(0) is mathematically undefined.
https://en.m.wikipedia.org/wiki/Logarithm.


For the record, IEEE-754 specifies that log(0.0) should return -INF.
That's what Decimal does:

py from decimal import Decimal
py Decimal(0).log10()
Decimal('-Infinity')


Alas, Python's math module only has partial support for the IEEE-754
standard.



So depending on the problem's context, it might be worth asking why log is
being applied on this input.  Is such input expected?  Make sure the code
isn't trying to correct for input that shouldn't be there in the first
place.


Correct. Replacing too small values with 0.0 is the wrong solution.
Using -INF is better, or a very large negative number. Otherwise,
sticking 0 in the result is equivalent to replacing the negative values
with 1.

data = [0.5, 1.0, 0.0]  # Good value, good value, bad value.
# This is the wrong way:
[0.0 if x == 0.0 else math.log(x) for x in data]
= returns [-0.6931471805599453, 0.0, 0.0]

That is mathematically equivalent to x = 0.0 being replaced with x = 1.0
before taking the log, and that makes no sense.


Thanks to both Steven and Danny. I will have to examine my logic again.
Superficially, just setting the very occasional 0.0 value to 0 served, 
but it is clearly inappropriate. I will try and find the correct answer 
to my problem. I may return for advice, although it is not strictly python.

Many thanks to you both.

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


Re: [Tutor] list comprehension with else

2015-01-18 Thread Steven D'Aprano
On Sun, Jan 18, 2015 at 02:20:55PM -0800, Danny Yoo wrote:
 Just to add, log(0) is mathematically undefined.
 https://en.m.wikipedia.org/wiki/Logarithm.

For the record, IEEE-754 specifies that log(0.0) should return -INF. 
That's what Decimal does:

py from decimal import Decimal
py Decimal(0).log10()
Decimal('-Infinity')


Alas, Python's math module only has partial support for the IEEE-754 
standard.

 
 So depending on the problem's context, it might be worth asking why log is
 being applied on this input.  Is such input expected?  Make sure the code
 isn't trying to correct for input that shouldn't be there in the first
 place.

Correct. Replacing too small values with 0.0 is the wrong solution. 
Using -INF is better, or a very large negative number. Otherwise, 
sticking 0 in the result is equivalent to replacing the negative values 
with 1.

data = [0.5, 1.0, 0.0]  # Good value, good value, bad value.
# This is the wrong way:
[0.0 if x == 0.0 else math.log(x) for x in data]
= returns [-0.6931471805599453, 0.0, 0.0]

That is mathematically equivalent to x = 0.0 being replaced with x = 1.0 
before taking the log, and that makes no sense.

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


Re: [Tutor] list comprehension with else

2015-01-18 Thread Alan Gauld

On 18/01/15 13:20, Sydney Shall wrote:

I am a beginner and I have a question of syntax.


Please don't hijack an existing thread.
Simply changing the subject line is not enough.
Always send a new mail to tutor@python.org to
start a new discussion.

Otherwise the new discussion gets interleaved with the
old in the archoives and makes it messy to find in searches
and for those using threaded mail/news readers.

--
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] list comprehension with else

2015-01-18 Thread Sydney Shall

On 18/01/2015 13:20, Sydney Shall wrote:

I am a beginner and I have a question of syntax.

I am just learning to use list comprehension, which oc course, I find
very helpful indeed.

However, I am stuck with a specific problem of how to incorporate an
else in a list comp-rehension. I cannot do it.

The following snippet of code does what I need. But, perhaps I am
solving this math error problem incorrectly.
The problem is I am occasionally getting exactly zeros when I need to
obtain the logarithm of the number.

for i in range(len(cap)):
 if cap[i] == 0.0:
 tmp = math.log(1.0)
 lncap.append(tmp)
 else:
 lncap.append(math.log(cap[i]))

I have set mu options to plain text.


I apoligise. I should have added:
MAC OS OSX 10.9.5
python 2.7.6 (Enthought)

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


Re: [Tutor] list comprehension with else

2015-01-18 Thread Asokan Pichai
On Sun, Jan 18, 2015 at 6:50 PM, Sydney Shall s.sh...@virginmedia.com
wrote:

 I am a beginner and I have a question of syntax.

Welcome!



 I am just learning to use list comprehension, which oc course, I find very
 helpful indeed.

 However, I am stuck with a specific problem of how to incorporate an else
 in a list comp-rehension. I cannot do it.

 The following snippet of code does what I need. But, perhaps I am solving
 this math error problem incorrectly.
 The problem is I am occasionally getting exactly zeros when I need to
 obtain the logarithm of the number.

 for i in range(len(cap)):

Using a for loop like this is generally a poor idea.

for aCap in cap:

is the more pythonic way. And also will help you translate to a list
comprehension easily



 if cap[i] == 0.0:
 tmp = math.log(1.0)
 lncap.append(tmp)

Possibly lncap.append(math.log(1.0)) or even lncap.append(0) is simpler


 else:
 lncap.append(math.log(cap[i]))


Having said that above your present code, let me try to explain the thought
process behind constructing the list comprehension for your purpose. It is
possible that what you need is not an else in the list comprehension

lncap = [ f(aCap) for aCap in cap]

will be the starting point;  where f() will need to provide either
math.log(aCap) or 0 as we saw earlier.

You can actually write an auxiliary function f that does just that; like say
def f(p):
  if p == 0.0:
  return 0.0
  return math.log(p)

Or write the list comprehension as:

lncap = [ (math.log(aCap) if aCap  0 else 0.0) for aCap in cap]

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


Re: [Tutor] list comprehension with else

2015-01-18 Thread Alan Gauld

On 18/01/15 13:20, Sydney Shall wrote:


The problem is I am occasionally getting exactly zeros when I need to
obtain the logarithm of the number.

for i in range(len(cap)):


Its usually better to iterate over the collection rather than use indexing:

for item in cap:


 if cap[i] == 0.0:


Its usually a bad idea to compare floats for equality. It's better to 
define a small limit value and check if they are within the range.

like this

e = 0.01  # or whatever

if val-e = cap[[i] = val+e:
do something.

In your case where you test against zero it simplifies to

if -e  cap[i]  e:
do something


 tmp = math.log(1.0)


log(1) is a constant (0) so you might as well just say


 lncap.append(tmp)


lncap.append(0.0)


 else:
 lncap.append(math.log(cap[i]))


But won't this cause you to have really dodgy results? How do you 
distinguish genuine log(1) values from your pseudo log(0) values?

Or does it not matter?


I have set mu options to plain text.


Thanks, always appreciated.

While you can make comprehensions do what you want its not always a good 
idea. Sometimes its better to revert to explicit loops if the complexity 
of the comprehension gets too great.


But in your case its fairly simple to use a conditional expression:

lncap = [ 0.0 if (-e  item  e) else math.log(item) for item in cap]


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


[Tutor] list comprehension with else

2015-01-18 Thread Sydney Shall

I am a beginner and I have a question of syntax.

I am just learning to use list comprehension, which oc course, I find 
very helpful indeed.


However, I am stuck with a specific problem of how to incorporate an 
else in a list comp-rehension. I cannot do it.


The following snippet of code does what I need. But, perhaps I am 
solving this math error problem incorrectly.
The problem is I am occasionally getting exactly zeros when I need to 
obtain the logarithm of the number.


for i in range(len(cap)):
if cap[i] == 0.0:
tmp = math.log(1.0)
lncap.append(tmp)
else:
lncap.append(math.log(cap[i]))

I have set mu options to plain text.
--
Sydney
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] list comprehension with else

2015-01-18 Thread Sydney Shall

On 18/01/2015 13:41, Asokan Pichai wrote:


On Sun, Jan 18, 2015 at 6:50 PM, Sydney Shall s.sh...@virginmedia.com
mailto:s.sh...@virginmedia.com wrote:

I am a beginner and I have a question of syntax.

Welcome!


I am just learning to use list comprehension, which oc course, I
find very helpful indeed.

However, I am stuck with a specific problem of how to incorporate an
else in a list comp-rehension. I cannot do it.

The following snippet of code does what I need. But, perhaps I am
solving this math error problem incorrectly.
The problem is I am occasionally getting exactly zeros when I need
to obtain the logarithm of the number.

for i in range(len(cap)):

Using a for loop like this is generally a poor idea.

for aCap in cap:

is the more pythonic way. And also will help you translate to a list
comprehension easily

 if cap[i] == 0.0:
 tmp = math.log(1.0)
 lncap.append(tmp)

Possibly lncap.append(math.log(1.0)) or even lncap.append(0) is simpler

 else:
 lncap.append(math.log(cap[i]))


Having said that above your present code, let me try to explain the
thought process behind constructing the list comprehension for your
purpose. It is possible that what you need is not an else in the list
comprehension

lncap = [ f(aCap) for aCap in cap]

will be the starting point;  where f() will need to provide either
math.log(aCap) or 0 as we saw earlier.

You can actually write an auxiliary function f that does just that; like say
def f(p):
   if p == 0.0:
   return 0.0
   return math.log(p)

Or write the list comprehension as:

lncap = [ (math.log(aCap) if aCap  0 else 0.0) for aCap in cap]

Hope this helps

Thanks. perfect. Thanks especialy for the explanation.

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


Re: [Tutor] list comprehension with else

2015-01-18 Thread Danny Yoo
Just to add, log(0) is mathematically undefined.
https://en.m.wikipedia.org/wiki/Logarithm.

So depending on the problem's context, it might be worth asking why log is
being applied on this input.  Is such input expected?  Make sure the code
isn't trying to correct for input that shouldn't be there in the first
place.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] List and dictionary comprehensions

2014-09-29 Thread Armindo Rodrigues
Hi everyone,

This is my first post so I don't know if I am asking the correct way so let
me know if I messed anything up.

***Please note. My code contains a list of quotes that has many lines. I
have noted the beginning and end of the quotes list so you can easily skip
and go straight to the code section. ***


This is technically NOT a homework assignment. I am the teaching assistant
for the Python course at my school. The teacher doesn't give me the
homework ahead of time so I typically try the homework myself so I can help
anyone else out that may be confused. The assignment has come and gone but
I want to challenge myself with making this thing more efficient and learn
comprehensions along the way.

The assignment was as follows:
The teacher provided the class with a list of quotes called data_list. We
were to implement a very simple search algorithm that took in a user's
query and we searched based on those words. If the user entered an OR then
we searched for quotes that contained either of the words. Any other
combination of AND OR will be an AND search.

Once we completed the search algorithm, the assignment called for
pre-processing that would make the search more efficient and faster. I
created a dictionary based on each word in the quotes list as the key and
then searched against those words. I greatly increased the search time.

MY QUESTION:
Can anyone look at this and explain how I could create a list comprehension
and a dictionary comprehension if possible? Also any suggestions with
making the search faster would be appreciated.


import re
from datetime import datetime
import time


###  DATA LIST STARTS HERE

data_list=[And now here is my secret, a very simple secret: It is only
with the heart that one can see rightly; what is essential is invisible to
the eye.,
All grown-ups were once children... but only few of them remember it.,
People have forgotten this truth,\ the fox said. \But you mustn?t forget
it. You become responsible forever for what you?ve tamed. You?re
responsible for your rose.,
It is the time you have wasted for your rose that makes your rose so
important.,
The most beautiful things in the world cannot be seen or touched, they are
felt with the heart.,
What makes the desert beautiful,' said the little prince, 'is that
somewhere it hides a well...,
You - you alone will have the stars as no one else has them...In one of
the stars I shall be living. In one of them I shall be laughing. And so it
will be as if all the stars were laughing, when you look at the sky at
night...You - only you - will have stars that can laugh.,
Well, I must endure the presence of a few caterpillars if I wish to become
acquainted with the butterflies.,
You see, one loves the sunset when one is so sad.,
You're beautiful, but you're empty...One couldn't die for you. Of course,
an ordinary passerby would think my rose looked just like you. But my rose,
all on her own, is more important than all of you together, since she's the
one I've watered. Since she's the one I put under glass, since she's the
one I sheltered behind the screen. Since she's the one for whom I killed
the caterpillars (except the two or three butterflies). Since she's the one
I listened to when she complained, or when she boasted, or even sometimes
when she said nothing at all. Since she's my rose.,
If you love a flower that lives on a star, it is sweet to look at the sky
at night. All the stars are a-bloom with flowers...,
And when your sorrow is comforted (time soothes all sorrows) you will be
content that you have known me. You will always be my friend. You will want
to laugh with me. And you will sometimes open your window, so, for that
pleasure . . . And your friends will be properly astonished to see you
laughing as you look up at the sky! Then you will say to them, 'Yes, the
stars always make me laugh!' And they will think you are crazy. It will be
a very shabby trick that I shall have played on you...,
You become responsible, forever, for what you have tamed.,
Of course I?ll hurt you. Of course you?ll hurt me. Of course we will hurt
each other. But this is the very condition of existence. To become spring,
means accepting the risk of winter. To become presence, means accepting the
risk of absence.,
Where are the people?\ resumed the little prince at last. \It?s a little
lonely in the desert\ \It is lonely when you?re among people, too,\ said
the snake.,
All men have stars, but they are not the same things for different people.
For some, who are travelers, the stars are guides. For others they are no
more than little lights in the sky. For others, who are scholars, they are
problems... But all these stars are silent. You-You alone will have stars
as no one else has them... In one of the stars I shall be living. In one of
them I shall be laughing. And so it will be as if all the stars will be
laughing when you look at the sky at night..You, only you, will have stars
that can laugh! And when your sorrow is 

Re: [Tutor] List and dictionary comprehensions

2014-09-29 Thread Alan Gauld

On 28/09/14 03:36, Armindo Rodrigues wrote:


have noted the beginning and end of the quotes list so you can easily skip
and go straight to the code section. ***


It would probably have been better to just delete all but a nfew of the 
quotes. We don't need all of them to evaluate your code.



import re
from datetime import datetime
import time


###  DATA LIST STARTS HERE

data_list=[And now here is my secret, a very simple secret: It is only
with the heart that one can see rightly; what is essential is invisible to
the eye.,
All grown-ups were once children... but only few of them remember it.,

...

If you love a flower that lives on a star, then it's good at night, to
look up at the sky. All the stars are blossoming.]


## CODE STARTS HERE

#Create a list of words taken from each individual word in the datalist
word_list = []
for item in data_list:
 for word in item.split( ):
 word = re.sub('^[^a-zA-z]*|[^a-zA-Z]*$','', word)


word.strip() would be better here. You can specify a string of chars to 
be stripped if its not only whitespace. Consider regular expressions as 
a weapon of last resort.



 word_list.append(word)
word_list = sorted(list(set(word_list))) #Remove repeated words


You don't need to convert the set into a list. sorted() works
with sets too.


quotesDict = {}
for word in word_list:
 quotesDict.setdefault(word,[]) #Create a dictionary with keys based on
each word in the word list


By putting the words in the dictionary you lose the sorting you did 
above. So the sorting was a waste of time.



for key, value in quotesDict.items():
 indexofquote = 0
 for quote in data_list:


You should use enumerate for this. It will automatically give you the 
index and quote and be less error prone than maintaining the index yourself.



 if key in quote:
 quotesDict[key].append(indexofquote) #Append the index of the
found quotes to the dictionary key
 indexofquote+=1

query=input(query: )
query = query.strip( ).split( )
query = list(set(query))



I don;t think you need the conversion to list here either.
You can just use the set.


start_time = time.time()

FoundQuotes = []

# Right now the OR search just prints out the index of the found quotes.
if (or in query) and (and not in query):


The logic here can be simplified by testing for 'and' first

if 'and' in query
   remove 'or'
   process and
elif 'or' in query
   process 'or'
else process simple query




 query.remove(or)
 print(Performing OR search for: , query)
 for item in query:
 if (item in quotesDict):
 print(FOUND ,len(quotesDict[item]),   , item, QUOTES: ,
quotesDict.get(item))
 print(\n--- Execution ---\n, (time.time() - start_time) * 1000,
microseconds\n)

else:
 if and in query:
 query.remove(and)
 if or in query:
 query.remove(or)
 print(Performing AND search for: , query)


This looks wrong. What about the case where neither and/or are in the query?


 for item in query:
 if (item in quotesDict):
 FoundQuotes = FoundQuotes + (quotesDict.get(item))
 FoundQuotes = list(set([x for x in FoundQuotes if FoundQuotes.count(x)

1]))


This doesn't look right either.
Foundquotes is a list of indexes. The comprehension builds a list of all 
the indexes that appear more than once - what about a quote that was 
only found once?


It then eliminates all the duplicates(set()) and returns it back to a 
list(why not leave it as a set?)


I'd have expected a simple conversion of FoundQuotes to a set would be 
what you wanted.



 for x in FoundQuotes:
 print(data_list[x])
 print(\n--- Execution ---\n, (time.time() - start_time) * 1000,
microseconds\n)


The other problem is that you are serching the dictionary
several times, thus losing some of the speed advantage of
using a dictionary.

You would get more benefit from the dictionary if you adopt a try/except 
approach and just access the key directly. So, instead of:


  for item in query:
  if (item in quotesDict):
  FoundQuotes = FoundQuotes + (quotesDict.get(item))

for item in query:
  try: FoundQuotes = FoundQuotes + quotesDict[item]
  except KeyError: pass

Or better still use the default value of get:

for item in query:
FoundQuotes = FoundQuotes + quotesDict.get(item,[])

There are a few other things that could be tidied up but that should 
give you something to get started with.


--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
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] List and dictionary comprehensions

2014-09-29 Thread Peter Otten
Armindo Rodrigues wrote:

 Hi everyone,
 
 This is my first post so I don't know if I am asking the correct way so
 let me know if I messed anything up.
 
 ***Please note. My code contains a list of quotes that has many lines. I
 have noted the beginning and end of the quotes list so you can easily skip
 and go straight to the code section. ***
 
 
 This is technically NOT a homework assignment. I am the teaching assistant
 for the Python course at my school. The teacher doesn't give me the
 homework ahead of time so I typically try the homework myself so I can
 help anyone else out that may be confused. The assignment has come and
 gone but I want to challenge myself with making this thing more efficient
 and learn comprehensions along the way.
 
 The assignment was as follows:
 The teacher provided the class with a list of quotes called data_list. We
 were to implement a very simple search algorithm that took in a user's
 query and we searched based on those words. If the user entered an OR then
 we searched for quotes that contained either of the words. Any other
 combination of AND OR will be an AND search.
 
 Once we completed the search algorithm, the assignment called for
 pre-processing that would make the search more efficient and faster. I
 created a dictionary based on each word in the quotes list as the key and
 then searched against those words. I greatly increased the search time.

That is very unlikely. Note that you include the print() calls into your 
measurement. These will dominate the time you measure, i. e. searches with 
more matching text will appear to take longer and searches with little or no 
text will appear to be fast.

 MY QUESTION:
 Can anyone look at this and explain how I could create a list
 comprehension and a dictionary comprehension if possible? 

I tried to solve the problem myself below -- and did not find a place where 
list comprehensions would fit in naturally.

 Also any
 suggestions with making the search faster would be appreciated.

As hinted above, your code does not have speed issues; you can simplify and 
clean it a bit (I stopped halfway), put every separate step into a function 
with an informative name, avoid global variables, follow the naming 
conventions of PEP 8 http://python.org/dev/peps/pep-0008/ -- and that's 
it.

My most significant modifications:

- Use the strings directly instead of indices into the list
- Build the word-to-quote lookup directly without the intermediate list of
  all words.

#!/usr/bin/env python3
import re
import time
from itertools import zip_longest
from sys import exit

data_list = [...] # won't repeat your data

RED = \033[31m
BLUE = \033[34m

EMPTY = frozenset()


def colored(s, color):
# if the coloring attempt messes up your screen
# change this to
# return s
return %s%s\033[0m % (color, s)


def find(term):
return quotes_dict.get(term.lower(), EMPTY)


def mark_terms(phrase, terms):
def mark(m):
return colored(m.group(), RED)

expr = r\b(%s)\b % |.join(terms)
return re.compile(expr).sub(mark, phrase)


def clean(word):
return re.sub('^[^a-zA-z]*|[^a-zA-Z]*$', '', word)


quotes_dict = {}
for item in data_list:
for word in item.split():
quotes_dict.setdefault(clean(word), set()).add(item)

query = input(query: )

start_time = time.time()

query = query.split()
if not query:
exit(no search term)

terms = query[::2]
found_quotes = find(query[0])
for operator, term in zip_longest(query[1::2], query[2::2]):
if term is None:
exit(dangling operator  + operator)
operator = operator.lower()
if operator == or:
found_quotes |= find(term)
elif operator == and:
found_quotes = find(term)
else:
print(unknown operator, operator)
exit(1)

print(
\n--- Execution ---\n,
(time.time() - start_time) * 1000, microseconds\n)

for index, quote in enumerate(found_quotes):
print(colored({} .format(index), BLUE), mark_terms(quote, terms))

Note that my handling of the operators does not follow your teacher's spec. 
It simply `or`s or `and`s the next match to what is in the current set of 
matches.

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


Re: [Tutor] List of Lists for three Frames

2014-05-19 Thread Wolfgang Maier

On 17.05.2014 15:26, Alan Gauld wrote:

On 17/05/14 08:01, ani wrote:

So I thought it would be cool to read a sequence at three different
frames,


A sequence of what?
And whats a frame in this context?


...I've come across a conundrum: how to make a list of lists.


outerlist = []
innerlist = [1,2,3]
outerlist.append(innerlist)
outerlist.append([4,5,6])


print (outerlist[1][1])  # prints 5


type of frame with a + or a - to signify the direction of the read
(+1,+2,
+3, -1, -2, -3),


What does 'direction of the read mean'?


the numerical position of each start codon a


Whats a codon?

This is a list for programmers learning python.
Do not assume any specialized domain knowledge.
If you can explain the problem in terms of
plain English and basic math then we can probably help.
If you use terms that are either ambiguous or too
specialized we will be lost and unable to assist.




The OP is asking about a representation of DNA sequences in Python.
More specifically, his question is about protein coding segments of DNA
that are transcribed into messenger RNA, then translated into protein
using the so-called triplet code (three RNA nucleotides are encoding one
amino acid of the protein). So the question involves a lot of basic
biology (Alan's questions: since three nucleotides stand for one amino
acid there are three different reading frames for any messenger RNA
starting with the first, second and third nucleotide, respectively; the
orignal DNA is an anti-parallel double strand and either strand may be
transcribed, so 'direction' refers to this; a codon is a specific
triplet of nucleotides).

Ani: While I could help you with your question, I agree with Peter that
you need to define much more clearly what you are trying to do before we
can discuss any code here. In principle, he's also right that you should
look into biopython because that package might well be the right thing
for you, but that, again, is hard to tell without knowing the details of
what you are trying to do.

Best wishes,
Wolfgang

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


[Tutor] List of Lists for three Frames

2014-05-17 Thread ani
So I thought it would be cool to read a sequence at three different frames, 
which I have pasted below. However, I've come across a conundrum: how to 
make a list of lists. See, I'd like a final output that displays data of the 
type of frame with a + or a - to signify the direction of the read (+1,+2, 
+3, -1, -2, -3), the numerical position of each start codon along with its 
stop codon, and the length between the start and stop codons. (I am only 
looking for the longest ORFs) An example of the output would look like this:

 +1 57166..61908  4743. 
The reason why I'd like a list of lists is so that I can take all the Starts 
I found in the code below, store it, then be able to place it in to the 
output somehow. I thought that maybe a list of lists would be the best way 
of getting this information from three different frames. However, I'm not 
sure how to go about this... could someone give me a way to start? The while 
loops work fine, last time I checked. Thanks.

def codons(self, frame_one, frame_two, frame_three): 
while frame_one =len(self.seq): 
yield (self.seq[frame_one:frame_one+3]) 
frame_one += 3

while frame_two =len(self.seq):
yield (self.seq[frame_two:frame_two+3])
frame_two += 3

while frame_three =len(self.seq):
yield (self.seq[frame_three:frame_three+3])
frame_three += 3

val = seq.codons(0,1,2)

for i in val:
return(i)

self.startlist.append[[frame_one], [frame_two], [frame_three]]

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


Re: [Tutor] List of Lists for three Frames

2014-05-17 Thread Peter Otten
ani wrote:

 So I thought it would be cool to read a sequence at three different
 frames, which I have pasted below. However, I've come across a conundrum:
 how to make a list of lists. See, I'd like a final output that displays
 data of the type of frame with a + or a - to signify the direction of the
 read (+1,+2, +3, -1, -2, -3), the numerical position of each start codon
 along with its stop codon, and the length between the start and stop
 codons. (I am only looking for the longest ORFs) An example of the output
 would look like this:
 
  +1 57166..61908  4743.
 The reason why I'd like a list of lists is so that I can take all the
 Starts I found in the code below, store it, then be able to place it in to
 the output somehow. I thought that maybe a list of lists would be the best
 way of getting this information from three different frames. However, I'm
 not sure how to go about this... could someone give me a way to start? The
 while loops work fine, last time I checked. Thanks.
 
 def codons(self, frame_one, frame_two, frame_three):
 while frame_one =len(self.seq):
 yield (self.seq[frame_one:frame_one+3])
 frame_one += 3
 
 while frame_two =len(self.seq):
 yield (self.seq[frame_two:frame_two+3])
 frame_two += 3
 
 while frame_three =len(self.seq):
 yield (self.seq[frame_three:frame_three+3])
 frame_three += 3
 
 val = seq.codons(0,1,2)
 
 for i in val:
 return(i)
 
 self.startlist.append[[frame_one], [frame_two], [frame_three]]

While making a list of lists is easy, just append the inner lists to the 
outer,

 items = []
 items.append([1, 2, 3])
 items.append([4, 5, 6])
 items
[[1, 2, 3], [4, 5, 6]]

I'd say it is far too early for you to write any real code. Go through a 
tutorial to get familiar with Python's syntax first.

Then write a detailed description in plain English of what you are trying to 
do. We can help you with Python, but most of us lack the domain knowledge to 
even decipher what you are up to from the exposition you give above. More 
importantly, a detailed plan will help you writing the corresponding script.

Now for the best part: once you have written working code you will usually 
throw it away and switch to a library like biopython. See 
http://biopython.org/DIST/docs/tutorial/Tutorial.html#sec360


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


Re: [Tutor] List of Lists for three Frames

2014-05-17 Thread Alan Gauld

On 17/05/14 08:01, ani wrote:

So I thought it would be cool to read a sequence at three different frames,


A sequence of what?
And whats a frame in this context?


...I've come across a conundrum: how to make a list of lists.


outerlist = []
innerlist = [1,2,3]
outerlist.append(innerlist)
outerlist.append([4,5,6])


print (outerlist[1][1])  # prints 5


type of frame with a + or a - to signify the direction of the read (+1,+2,
+3, -1, -2, -3),


What does 'direction of the read mean'?


the numerical position of each start codon a


Whats a codon?

This is a list for programmers learning python.
Do not assume any specialized domain knowledge.
If you can explain the problem in terms of
plain English and basic math then we can probably help.
If you use terms that are either ambiguous or too
specialized we will be lost and unable to assist.


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

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


[Tutor] List issues

2014-04-17 Thread Wheeler, Gabriel
Hi

Im having trouble completing this function with lists. Im supposed to create a 
function that will let me know if there are repeating elements so I wrote this 
and am not sure where the error lies. It is supposed to count the number of 
times a number appears and if its greater than 1 then it will say True.


#Problem 3

list = [1,2,2,2,3,4]

def duplicate(list):

for i in range(len[list]):

if list.count(i)  1:

return True


print duplicate(list)



Gabe Wheeler
(512)964-5421
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] List issues

2014-04-17 Thread Peter Otten
Wheeler, Gabriel wrote:

 Im having trouble completing this function with lists. Im supposed to
 create a function that will let me know if there are repeating elements so
 I wrote this and am not sure where the error lies. 

It helps you (and us) a lot if you clearly state the error you are seeing. 
If your script bails out with an error post the complete traceback. If all 
appears to be working, but you get a wrong or unexpected result say what you 
get and what you expected. 

Running your code I get

$ cat check_dupes.py 
list = [1,2,2,2,3,4]

def duplicate(list):
for i in range(len[list]):
if list.count(i)  1:
return True

print duplicate(list)
$ python check_dupes.py 
Traceback (most recent call last):
  File check_dupes.py, line 8, in module
print duplicate(list)
  File check_dupes.py, line 4, in duplicate
for i in range(len[list]):
TypeError: 'builtin_function_or_method' object has no attribute 
'__getitem__'

Looking at the line shown in the traceback

for i in range(len[list]):

what could be the function you are not calling but asking for that strange 
__getitem__ attribute? Hint:

 def hello(name):
... print Hello,, name
... 
 hello(Gabriel)
Hello, Gabriel
 hello[Gabriel]
Traceback (most recent call last):
  File stdin, line 1, in module
TypeError: 'function' object has no attribute '__getitem__'

That sure looks similar to your error message.

Once you have fixed that I recommend that you add a print statement

def duplicate(list):
for i in range(len[list]): # must be fixed
print looking for, i
if list.count(i)  1:
return True

You'll see that you are looking for items that are not in the list? Can you 
figure out why?

If not, call the function with another list

duplicate([a, b, b, b, c, d])

 It is supposed to count
 the number of times a number appears and if its greater than 1 then it
 will say True.
 
 
 #Problem 3
 
 list = [1,2,2,2,3,4]
 
 def duplicate(list):
 for i in range(len[list]):
 if list.count(i)  1:
 return True
 
 
 print duplicate(list)


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


Re: [Tutor] List issues

2014-04-17 Thread Dave Angel
Wheeler, Gabriel wheel...@seattleu.edu Wrote in message:


(not much I could read there. This is a text mailing list, so
 please tell your mail program to send in text mode, not html.
 Only parts of your code were visible here, and your question not
 at all. Fortunately, Peter quoted all or most of your message. 
 His comments are all good.  Mine are in addition,  not instead.
 

Your code:

list = [1,2,2,2,3,4]

def duplicate(list):
   for i in range(len[list]):
       if list.count(i)  1:
           return True

print duplicate(list)



Peter's hints should fix your main bugs. Then:

When an if-test doesn't seem to be doing what you expect,  add a
 print statement right before it of the exact expression it's
 testing.  Or even make a new variable of the expression so you
 can be sure you're looking at the same thing. 

When a standard method seems to be misbehaving,  look up its
 definition.  What should the argument to count be?

list is a typename in the standard library,  so it really
 shouldn't be used to name your own objects. I'd use something
 like mylist.

Whenever you see a loop like 
   for i in range(len[list]):

be suspicious of it. Usually you want the items, not the indices. 
for item in mylist:

This function doesn't return any value if the if test always
 fails. Is that what you wanted? 




-- 
DaveA

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


Re: [Tutor] List issues

2014-04-17 Thread Albert-Jan Roskam
 

- Original Message -
 From: Dave Angel da...@davea.name
 To: tutor@python.org
 Cc: 
 Sent: Thursday, April 17, 2014 12:03 PM
 Subject: Re: [Tutor] List issues
 
 quot;Wheeler, Gabriel wheel...@seattleu.edu Wrote in message:
 
 
 (not much I could read there. This is a text mailing list, so
 please tell your mail program to send in text mode, not html.
 Only parts of your code were visible here, and your question not
 at all. Fortunately, Peter quoted all or most of your message. 
 His comments are all good.  Mine are in addition,  not instead.
 
 
 Your code:
 
 list = [1,2,2,2,3,4]
 
 def duplicate(list):
    for i in range(len[list]):
        if list.count(i)  1:
            return True
 
 print duplicate(list)
 
 
 
 Peter's hints should fix your main bugs. Then:
 
 When an if-test doesn't seem to be doing what you expect,  add a
 print statement right before it of the exact expression it's
 testing.  

and/or use the pdb debugger (still on my own todo list, but I know it is 
useful!): http://pymotw.com/2/pdb/
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] List issues

2014-04-17 Thread Danny Yoo
Hi Gabriel,

Try lists of non-numbers as your input, and the error should be a
little clearer to see.  You should see the conceptual error you're
making if not everything in your program is numeric.

Try:

words = ['hello', 'world', 'hello']
print(words.count(0))
print(words.count('hello'))

First write down what you'd expect to see from this.  Then execute
this snippet.  Does your expectations match what you see?

---

A main bug in your program is that parts of your program are using
numbers for list indices, and other parts of your program are using
numbers as elements, but there's a little confusion in using one
notion for the other.

---

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


Re: [Tutor] list comprehension equivalent to map(function, list item)

2013-12-14 Thread Bo Morris
Thank you for your assistance. Based on your direction, I figured it out.

*This... *

def add(number):
 print 1 + int(number)

x = ['2', '4', '6', '8', '10', '12']

[add(item) for item in x]

 *Is the same as... *


def add(number):
 print 1 + int(number)

x = ['2', '4', '6', '8', '10', '12']

map(add, x)

They both yield the same results. Is there a benefit to using one way over
the other? In larger computations, does one way calculate faster or is it
merely a preference? Again, thank you.

AngryNinja


On Fri, Dec 13, 2013 at 9:24 PM, Amit Saha amitsaha...@gmail.com wrote:

 On Sat, Dec 14, 2013 at 11:03 AM, Bo Morris crushe...@gmail.com wrote:
  i have the following simple function that iterates over the list. It
 passes
  the list item into the function and adds the numbers. What would be the
  equivalent way of writing the map portion with list comprehension? My
 code
  is as follows:
 
  def add(number):
  print 1 + int(number)
 
 
 
  x = ['2', '4', '6', '8', '10', '12']
 
  map(add, x)

 Think of a list comprehension as:

 [ dosomething(item) for item in alist]

 And, comparing it with your map implementation, here is what you get:

  [1+int(item) for item in x]
 [3, 5, 7, 9, 11, 13]


 Here, dosomething(item) corresponds to 1+int(item).

 Hope that helps.

 -Amit.


 --
 http://echorand.me

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


Re: [Tutor] list comprehension equivalent to map(function, list item)

2013-12-14 Thread Peter Otten
Bo Morris wrote:

 Thank you for your assistance. Based on your direction, I figured it out.
 
 *This... *
 
 def add(number):
  print 1 + int(number)
 
 x = ['2', '4', '6', '8', '10', '12']
 
 [add(item) for item in x]
 
  *Is the same as... *
 
 
 def add(number):
  print 1 + int(number)
 
 x = ['2', '4', '6', '8', '10', '12']
 
 map(add, x)
 
 They both yield the same results. Is there a benefit to using one way over
 the other? In larger computations, does one way calculate faster or is it
 merely a preference? Again, thank you.

For built-in functions map(f, items) is a bit faster. List-comps are more 
flexible; you can inline the function

 [int(s) + 1 for s in x]
[3, 5, 7, 9, 11, 13]

or add a filter:

 [int(s) + 1 for s in x if set(12)  set(s)]
[3, 11, 13]


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


Re: [Tutor] list comprehension equivalent to map(function, list item)

2013-12-14 Thread spir

On 12/14/2013 10:12 AM, Bo Morris wrote:

Thank you for your assistance. Based on your direction, I figured it out.

*This... *

def add(number):
  print 1 + int(number)

x = ['2', '4', '6', '8', '10', '12']

[add(item) for item in x]

  *Is the same as... *


def add(number):
  print 1 + int(number)

x = ['2', '4', '6', '8', '10', '12']

map(add, x)

They both yield the same results.


Have you tried your own code? If I add one print() for each result and run the 
code, here is the output by me:


3
5
7
9
11
13
[None, None, None, None, None, None]
map object at 0x7fa4fb7fd550

Certainly these are not the same results. And probably neither of them is the 
result you expected. I guess you go on using very imprecise, in fact wrong, 
terminology, and this drives you into thinking wrongly.


There also are worng terms in your code itself, already signaled bu other (but 
you did not correct or even take into account, apparently), and consequent 
errors of thinking:

* the add function does not add
* in fact it does not _produce_ anything (instead it is an action that performs 
an effect, namely writing something onto the terminal) ...
* ...so that using it as loop function in map simply makes no sense: map collect 
the results (products) of a function -- if that function produces results
* this is why we get [None, None...]: a function (the term is wrong, it's 
actually say an action) that does not produce but performs an effect return 
None by convention in Python.
* number is not a number, but hopefully) the written expression of a number, 
whay is technically called a numeral (see wikipedia)



 Is there a benefit to using one way over
the other? In larger computations, does one way calculate faster or is it
merely a preference? Again, thank you.

AngryNinja


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


[Tutor] list comprehension equivalent to map(function, list item)

2013-12-13 Thread Bo Morris
i have the following simple function that iterates over the list. It passes
the list item into the function and adds the numbers. What would be the
equivalent way of writing the map portion with list comprehension? My
code is as follows:

def add(number):
print 1 + int(number)



x = ['2', '4', '6', '8', '10', '12']

map(add, x)

thanks for the help and thank you for this mailing list.

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


Re: [Tutor] list comprehension equivalent to map(function, list item)

2013-12-13 Thread Mark Lawrence

On 14/12/2013 01:03, Bo Morris wrote:

i have the following simple function that iterates over the list. It
passes the list item into the function and adds the numbers. What would
be the equivalent way of writing the map portion with list
comprehension? My code is as follows:

def add(number):
 print 1 + int(number)

x = ['2', '4', '6', '8', '10', '12']

map(add, x)

thanks for the help and thank you for this mailing list.

AngryNinja



I don't see any function that iterates over anything.  I do see a 
function that takes something called number (IMHO a very poor name), 
converts it into an int, adds 1 to it, prints it out and then returns 
None, the default when no return statement is given in a function.  So 
change print to return, add it all up (very loud groan :) and you have.


def add(number):
return 1 + int(number)

y = [add(z) for z in x]

--
My fellow Pythonistas, ask not what our language can do for you, ask 
what you can do for our language.


Mark Lawrence

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


Re: [Tutor] list comprehension equivalent to map(function, list item)

2013-12-13 Thread Amit Saha
On Sat, Dec 14, 2013 at 11:03 AM, Bo Morris crushe...@gmail.com wrote:
 i have the following simple function that iterates over the list. It passes
 the list item into the function and adds the numbers. What would be the
 equivalent way of writing the map portion with list comprehension? My code
 is as follows:

 def add(number):
 print 1 + int(number)



 x = ['2', '4', '6', '8', '10', '12']

 map(add, x)

Think of a list comprehension as:

[ dosomething(item) for item in alist]

And, comparing it with your map implementation, here is what you get:

 [1+int(item) for item in x]
[3, 5, 7, 9, 11, 13]


Here, dosomething(item) corresponds to 1+int(item).

Hope that helps.

-Amit.


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


Re: [Tutor] list comprehension equivalent to map(function, list item)

2013-12-13 Thread Steven D'Aprano
On Fri, Dec 13, 2013 at 08:03:57PM -0500, Bo Morris wrote:

 i have the following simple function that iterates over the list. 

Actually, no it doesn't. One important skill of being a programmer is 
precision of language. The function add you show below does not 
iterate over the list, it is the *map* function which does the 
iteration.


 It passes the list item into the function and adds the numbers. 

Again, not so much. When you talk about adding up the numbers, given 
numbers like 5, 3, 2 I would expect to get 10 as the answer. That is not 
what your function does: it adds one to *each* number, alone.

Now that I've lectured you pedantically on precision of language, which 
I hope you'll take in the constructive spirit it is intended, let me 
answer your actual question:


 What would be the
 equivalent way of writing the map portion with list comprehension? My
 code is as follows:
 
 def add(number):
 print 1 + int(number)
 
 x = ['2', '4', '6', '8', '10', '12']
 map(add, x)


Converting a map to a list comprehension is simple:

map(function, items)

becomes:

[function(item) for item in items]


So your example simply becomes [add(s) for s in list_of_strings]


A couple of other points:

(1) The more work a variable is used for, the more descriptive its name 
should be. Variables which are used once can be a single letter. 
Temporary variables which don't last very long also can be a single 
letter. It is conventional to use a few single letter names:

i, j, k: loop variables
n, m: integers
x, y: floats or decimals
s: strings

but only when they represent generic values. If possible, you should 
give variables names which explain *what they are* (such as 
list_of_strings) or even better, *what they are used for* (such as 
scores, width, number_of_pages, etc.)


(2) In your example, your add function actually does two things:

- it *calculates* a result (adding one to a number);
- it *displays* that result (print).

In general, it is best to keep those two parts separate. Why? Because 
good, effective programming involves putting parts together to make 
bigger parts. Once you introduce a print into a function, you can't 
really combine that part into a new more powerful part. You are now 
committed to *only* printing the calculation result, even if what you 
actually want to do is to perform more calculations on it.

An example: suppose that, after adding one, you then want to double the 
result. You might think that you could do this:

def double(number):
print 2*number

double(add(20))


That's exactly the sort of putting building blocks together that 
programming is all about. But if you try it, you'll see that it doesn't 
work. You'll get a mysterious error something like this:

TypeError: unsupported operand type(s) for *: 'int' and 'NoneType'

Why? Because your add function takes the calculated result and prints 
it, then throws the result away. Since the function doesn't return a 
value for later use, Python automatically returns the special None 
value, which you can think of as meaning something like nothing at 
all. What happens when you try to double None? You get an error.

The way to fix this and write functions which can be used as building 
blocks is to use return instead of print, then call print at the 
end, only when you want to actually see something:


def add(number):
return 1 + int(number)

x = ['2', '4', '6', '8', '10', '12']
print map(add, x)

def double(number):
return 2*number

print double(add(20))


If you have any questions, please don't hesitate to ask!


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


Re: [Tutor] List Python Question..Please help

2013-09-28 Thread Jacqueline Canales
Thank you guys so much i was able to figure it out. I definitely thought to
much into the the problem and made it harder on myself. Cant thank you
enough for assisting me. I have one more problem with the coding tho.

composers = ['Antheil', 'Saint-Saens', 'Beethoven', 'Easdale', 'Nielsen']
new_list = []
person = new_list
for person in composers:
if person[0].lower() == person[-1].lower():
print(person)

Output:
Saint-Saens
Easdale
Nielsen

composers = ['Antheil', 'Saint-Saens', 'Beethoven', 'Easdale', 'Nielsen']
new_list = []
person = new_list
for person in composers:
if person[0].lower() == person[-1].lower():
new_list.append(person)
print(new_list)

output:
['Saint-Saens']
['Saint-Saens', 'Easdale']
['Saint-Saens', 'Easdale', 'Nielsen']

How can i make the output of the names into just one individual list.


On Fri, Sep 27, 2013 at 9:11 PM, Amit Saha amitsaha...@gmail.com wrote:

 Hi Jacqueline,

 On Sat, Sep 28, 2013 at 3:04 AM, Jacqueline Canales
 jackiexxd...@gmail.com wrote:
  composers = ['Antheil', 'Saint-Saens', 'Beethoven', 'Easdale', 'Nielsen']
  x = 'Antheil'
  s = 'Saint-Saens'
  h = 'Beethoven'
  y = 'Easdale'
  k = 'Nielsen'
 
  if s[0] == 'S' or s[0] == 's' == s[-1] == 'S' or s[-1] == 's':
  if y[0] == 'E' or y[0] == 'e' == y[-1] == 'E' or y[-1] == 'e':
  if k[0] == 'N' or k[0] == 'n' == k[-1] == 'N' or k[-1] == 'n':
  print(s,k,y)
  else:
  print( )
 
  Answer i Got Below
 
  Saint-Saens Nielsen Easdale
 
 
  Is this what i was going for in the direction i was a bit confused if we
  were suppose create loops or if statements that are verified in the
 actual
  composers list. I don't know i feel as if i know what i need to do i just
  cant put it together.

 Nothing to worry. Let us break the problem down.

 In your first post, you mentioned this for loop:

 composers = ['Antheil', 'Saint-Saens', 'Beethoven', 'Easdale', 'Nielsen']
 for person in composers:
 print(person)

 What does this do? It prints all the composers' names. However, what
 you want is to print *only* the composer whose name starts and ends
 with the first letter. So, what can you do?

 I shall try to explain with an example from every day life. Let us
 say, the management in your local cinema theatre says that you can
 choose to see all of the films playing there. So, you can see all of:
 'Turbo', 'Planes' and 'The Smurfs 2'. Now, let is say that your cinema
 management became a little shrewd and tells you that you can only
 watch the films starting with 'P'. So what do you do? In your mind,
 you think which of 'Turbo',' Planes' and 'The Smurfs 2' starts with
 'P'. So, you first check, 'Turbo' and you see that it fails the
 condition, but 'Planes' agree with the condition and 'The Smurfs 2'
 also fails. Thus, you choose 'Planes'.

 So, your above program is in the right direction. What you have to now
 do is, before printing the 'person', you need to check if the person's
 name starts and ends with the same letter. I already showed you how
 you can do so.

 You may find the lower() method helpful here. It returns you a capital
 letter into a lower one:

  'A'.lower()
 'a'

 Does that make it easier?

 Good luck.
 -Amit


 --
 http://echorand.me

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


Re: [Tutor] List Python Question..Please help

2013-09-28 Thread Jacqueline Canales
THANK YOU!!! All of you were very helpful!! Will definitely use you
guys again for any other issues, glad you challenged me to think rather
than giving me the answer!!!


On Sat, Sep 28, 2013 at 12:39 AM, Amit Saha amitsaha...@gmail.com wrote:

 On Sat, Sep 28, 2013 at 3:36 PM, Jacqueline Canales
 jackiexxd...@gmail.com wrote:
  Thank you guys so much i was able to figure it out. I definitely thought
 to
  much into the the problem and made it harder on myself. Cant thank you
  enough for assisting me. I have one more problem with the coding tho.
 
  composers = ['Antheil', 'Saint-Saens', 'Beethoven', 'Easdale', 'Nielsen']
  new_list = []
  person = new_list
  for person in composers:
  if person[0].lower() == person[-1].lower():
  print(person)
 
  Output:
  Saint-Saens
  Easdale
  Nielsen

 Great work!

 
  composers = ['Antheil', 'Saint-Saens', 'Beethoven', 'Easdale', 'Nielsen']
  new_list = []
  person = new_list
  for person in composers:
  if person[0].lower() == person[-1].lower():
  new_list.append(person)
  print(new_list)
 
  output:
  ['Saint-Saens']
  ['Saint-Saens', 'Easdale']
  ['Saint-Saens', 'Easdale', 'Nielsen']



 
  How can i make the output of the names into just one individual list.

 You mean, just print it once? The last line of your output?

 Just print after the loop is over.





 --
 http://echorand.me

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


Re: [Tutor] List Python Question..Please help

2013-09-28 Thread Steven D'Aprano
On Sat, Sep 28, 2013 at 12:36:13AM -0500, Jacqueline Canales wrote:
 Thank you guys so much i was able to figure it out. I definitely thought to
 much into the the problem and made it harder on myself. Cant thank you
 enough for assisting me. I have one more problem with the coding tho.
 
 composers = ['Antheil', 'Saint-Saens', 'Beethoven', 'Easdale', 'Nielsen']
 new_list = []
 person = new_list

This line above (person = new_list) is unnecessary, since it never gets 
used before the next line sets it to something else.

 for person in composers:
 if person[0].lower() == person[-1].lower():
 print(person)
 
 Output:
 Saint-Saens
 Easdale
 Nielsen
 
 composers = ['Antheil', 'Saint-Saens', 'Beethoven', 'Easdale', 'Nielsen']
 new_list = []
 person = new_list
 for person in composers:
 if person[0].lower() == person[-1].lower():
 new_list.append(person)
 print(new_list)

Here you print the content of new_list each time through the loop, so 
you see it growing. Instead, get rid of the indentation so that it runs 
when the loop is finished:

for person in composers:
if person[0].lower() == person[-1].lower():
new_list.append(person)

print(new_list)


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


[Tutor] List Python Question..Please help

2013-09-27 Thread Jacqueline Canales
So I have been trying to do this program using ifs and or loops.
I am having a hard time solving this question, If you could please assist
me in the right direction.

Write a program that lists all the composers on the list ['Antheil',
'Saint-Saens', 'Beethoven', 'Easdale', 'Nielsen'] whose name starts and
ends with the same letter (so Nielsen gets lsited, but Antheil doesn't).

I know below it prints the entire list of composers but i dont know  how to
do the program above. I think I am thinking to much into but ive looked at
all my notes and online resources and having a hard time coming up with
anything.
Please help!

composers = ['Antheil', 'Saint-Saens', 'Beethoven', 'Easdale', 'Nielsen']
for person in composers:
print(person)
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] List Python Question..Please help

2013-09-27 Thread Amit Saha
On Fri, Sep 27, 2013 at 3:48 PM, Jacqueline Canales
jackiexxd...@gmail.com wrote:
 So I have been trying to do this program using ifs and or loops.
 I am having a hard time solving this question, If you could please assist me
 in the right direction.

 Write a program that lists all the composers on the list ['Antheil',
 'Saint-Saens', 'Beethoven', 'Easdale', 'Nielsen'] whose name starts and ends
 with the same letter (so Nielsen gets lsited, but Antheil doesn't).

 I know below it prints the entire list of composers but i dont know  how to
 do the program above. I think I am thinking to much into but ive looked at
 all my notes and online resources and having a hard time coming up with
 anything.
 Please help!

 composers = ['Antheil', 'Saint-Saens', 'Beethoven', 'Easdale', 'Nielsen']
 for person in composers:
 print(person)

So, here you are printing every compose as you rightly state above.
What you now need to do is:

For each of the composers (`person'), you need to check if the first
letter and the last letter are the same. Here;s a hint:

 s='abba'

The first letter:

 s[0]
'a'

The last letter:

 s[-1]
'a'


If you now compare these, you will know if they are the same and hence
you print him/her.

Hope that helps.
-Amit.


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


Re: [Tutor] List Python Question..Please help

2013-09-27 Thread Dharmit Shah
Also, comparison is case sensitive. Meaning, 'A' and 'a' are not the same.

Hope that helps. :)

On Fri, Sep 27, 2013 at 1:14 PM, Amit Saha amitsaha...@gmail.com wrote:
 On Fri, Sep 27, 2013 at 3:48 PM, Jacqueline Canales
 jackiexxd...@gmail.com wrote:
 So I have been trying to do this program using ifs and or loops.
 I am having a hard time solving this question, If you could please assist me
 in the right direction.

 Write a program that lists all the composers on the list ['Antheil',
 'Saint-Saens', 'Beethoven', 'Easdale', 'Nielsen'] whose name starts and ends
 with the same letter (so Nielsen gets lsited, but Antheil doesn't).

 I know below it prints the entire list of composers but i dont know  how to
 do the program above. I think I am thinking to much into but ive looked at
 all my notes and online resources and having a hard time coming up with
 anything.
 Please help!

 composers = ['Antheil', 'Saint-Saens', 'Beethoven', 'Easdale', 'Nielsen']
 for person in composers:
 print(person)

 So, here you are printing every compose as you rightly state above.
 What you now need to do is:

 For each of the composers (`person'), you need to check if the first
 letter and the last letter are the same. Here;s a hint:

 s='abba'

 The first letter:

 s[0]
 'a'

 The last letter:

 s[-1]
 'a'


 If you now compare these, you will know if they are the same and hence
 you print him/her.

 Hope that helps.
 -Amit.


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



-- 
Dharmit Shah
www.about.me/dharmit
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] List Python Question..Please help

2013-09-27 Thread Alan Gauld

On 27/09/13 06:48, Jacqueline Canales wrote:

So I have been trying to do this program using ifs and or loops.
I am having a hard time solving this question, If you could please
assist me in the right direction.


Happy to. We won't do the homework for you but we will ask leading 
questions and give hints.



I know below it prints the entire list of composers but i dont know  how
to do the program above.


OK, breaking it into three parts:

1) print names from the list - you can do that already

2) test if a name starts and ends with the same letter
   - Amit has shown you how to get the letters, do you
 know how to test for equality (using the == operator)?

3) Filter the printout based on the test in (2)
   - Do you know how to use an if statement to take
 action depending on the outcome of a test?

Your code should then look like

for person in persons:
if your test here
   print person


If there are still things you are unclear about
ask here and we will break it down further.

--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
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] List Python Question..Please help

2013-09-27 Thread Steven D'Aprano
Hi Jacqueline, and welcome!

Further information below...

On Fri, Sep 27, 2013 at 12:48:26AM -0500, Jacqueline Canales wrote:

 Write a program that lists all the composers on the list ['Antheil',
 'Saint-Saens', 'Beethoven', 'Easdale', 'Nielsen'] whose name starts and
 ends with the same letter (so Nielsen gets lsited, but Antheil doesn't).

 composers = ['Antheil', 'Saint-Saens', 'Beethoven', 'Easdale', 'Nielsen']
 for person in composers:
 print(person)


One of the secrets to programming is to write out the instructions to 
solve the problem in English (or whatever your native language is), as 
if you were giving instructions to some other person, telling them what 
to do. Then you just need to make those instructions more and more 
precise, more and more detailed, as computers are much dumber than any 
person.

For instance, you might start off with:

Look at each composer's name, and print it only if it begins and ends 
with the same letter.

The computer doesn't understand look at each composer's name, but you 
know how to tell the computer the same thing:


composers = ['Antheil', 'Saint-Saens', 'Beethoven', 'Easdale', 'Nielsen']
for person in composers:


so you're already half-way there. print it only if needs to be written 
the other way around:

if it begins and ends with the same letter, print it


The computer doesn't know what it is, so you have to spell it out 
explicitly:

if person begins and ends with the same letter, print person


Change the syntax to match what the Python programming language expects:

if person begins and ends with the same letter:
print person


Now the only bit still to be solved is to work out the begins and ends 
part. I'm not going to give you the answer to this, but I will give you 
a few hints. If you copy and paste the following lines into the Python 
interpreter and see what they print, they should point you in the right 
direction:


name = Beethovan
print The FIRST letter of his name is, name[0]
print The LAST letter of his name is, name[-1]

print Are the SECOND and THIRD letters equal?, name[1] == name[2]

print Does X equal x?, 'X' == 'x'

print Convert a string to lowercase:, name.lower()



Good luck, and don't hesitate to come back if you need any further help.



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


Re: [Tutor] List Python Question..Please help

2013-09-27 Thread 罗彭
Maybe the length of each name matters, too. You should consider whether to
skip null('') and single-character('a').


On Fri, Sep 27, 2013 at 3:57 PM, Dharmit Shah shahdhar...@gmail.com wrote:

 Also, comparison is case sensitive. Meaning, 'A' and 'a' are not the same.

 Hope that helps. :)

 On Fri, Sep 27, 2013 at 1:14 PM, Amit Saha amitsaha...@gmail.com wrote:
  On Fri, Sep 27, 2013 at 3:48 PM, Jacqueline Canales
  jackiexxd...@gmail.com wrote:
  So I have been trying to do this program using ifs and or loops.
  I am having a hard time solving this question, If you could please
 assist me
  in the right direction.
 
  Write a program that lists all the composers on the list ['Antheil',
  'Saint-Saens', 'Beethoven', 'Easdale', 'Nielsen'] whose name starts and
 ends
  with the same letter (so Nielsen gets lsited, but Antheil doesn't).
 
  I know below it prints the entire list of composers but i dont know
  how to
  do the program above. I think I am thinking to much into but ive looked
 at
  all my notes and online resources and having a hard time coming up with
  anything.
  Please help!
 
  composers = ['Antheil', 'Saint-Saens', 'Beethoven', 'Easdale',
 'Nielsen']
  for person in composers:
  print(person)
 
  So, here you are printing every compose as you rightly state above.
  What you now need to do is:
 
  For each of the composers (`person'), you need to check if the first
  letter and the last letter are the same. Here;s a hint:
 
  s='abba'
 
  The first letter:
 
  s[0]
  'a'
 
  The last letter:
 
  s[-1]
  'a'
 
 
  If you now compare these, you will know if they are the same and hence
  you print him/her.
 
  Hope that helps.
  -Amit.
 
 
  --
  http://echorand.me
  ___
  Tutor maillist  -  Tutor@python.org
  To unsubscribe or change subscription options:
  https://mail.python.org/mailman/listinfo/tutor



 --
 Dharmit Shah
 www.about.me/dharmit
 ___
 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] List Python Question..Please help

2013-09-27 Thread Jacqueline Canales
composers = ['Antheil', 'Saint-Saens', 'Beethoven', 'Easdale', 'Nielsen']
x = 'Antheil'
s = 'Saint-Saens'
h = 'Beethoven'
y = 'Easdale'
k = 'Nielsen'

if s[0] == 'S' or s[0] == 's' == s[-1] == 'S' or s[-1] == 's':
if y[0] == 'E' or y[0] == 'e' == y[-1] == 'E' or y[-1] == 'e':
if k[0] == 'N' or k[0] == 'n' == k[-1] == 'N' or k[-1] == 'n':
print(s,k,y)
else:
print( )

Answer i Got Below

Saint-Saens Nielsen Easdale


Is this what i was going for in the direction i was a bit confused if we
were suppose create loops or if statements that are verified in the actual
composers list. I don't know i feel as if i know what i need to do i just
cant put it together.


On Fri, Sep 27, 2013 at 3:14 AM, 罗彭 luopeng...@gmail.com wrote:

 Maybe the length of each name matters, too. You should consider whether to
 skip null('') and single-character('a').


 On Fri, Sep 27, 2013 at 3:57 PM, Dharmit Shah shahdhar...@gmail.comwrote:

 Also, comparison is case sensitive. Meaning, 'A' and 'a' are not the same.

 Hope that helps. :)

 On Fri, Sep 27, 2013 at 1:14 PM, Amit Saha amitsaha...@gmail.com wrote:
  On Fri, Sep 27, 2013 at 3:48 PM, Jacqueline Canales
  jackiexxd...@gmail.com wrote:
  So I have been trying to do this program using ifs and or loops.
  I am having a hard time solving this question, If you could please
 assist me
  in the right direction.
 
  Write a program that lists all the composers on the list ['Antheil',
  'Saint-Saens', 'Beethoven', 'Easdale', 'Nielsen'] whose name starts
 and ends
  with the same letter (so Nielsen gets lsited, but Antheil doesn't).
 
  I know below it prints the entire list of composers but i dont know
  how to
  do the program above. I think I am thinking to much into but ive
 looked at
  all my notes and online resources and having a hard time coming up with
  anything.
  Please help!
 
  composers = ['Antheil', 'Saint-Saens', 'Beethoven', 'Easdale',
 'Nielsen']
  for person in composers:
  print(person)
 
  So, here you are printing every compose as you rightly state above.
  What you now need to do is:
 
  For each of the composers (`person'), you need to check if the first
  letter and the last letter are the same. Here;s a hint:
 
  s='abba'
 
  The first letter:
 
  s[0]
  'a'
 
  The last letter:
 
  s[-1]
  'a'
 
 
  If you now compare these, you will know if they are the same and hence
  you print him/her.
 
  Hope that helps.
  -Amit.
 
 
  --
  http://echorand.me
  ___
  Tutor maillist  -  Tutor@python.org
  To unsubscribe or change subscription options:
  https://mail.python.org/mailman/listinfo/tutor



 --
 Dharmit Shah
 www.about.me/dharmit
 ___
 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] List Python Question..Please help

2013-09-27 Thread Dave Angel
On 27/9/2013 13:04, Jacqueline Canales wrote:

 composers = ['Antheil', 'Saint-Saens', 'Beethoven', 'Easdale', 'Nielsen']
 x = 'Antheil'
 s = 'Saint-Saens'
 h = 'Beethoven'
 y = 'Easdale'
 k = 'Nielsen'

 if s[0] == 'S' or s[0] == 's' == s[-1] == 'S' or s[-1] == 's':
 if y[0] == 'E' or y[0] == 'e' == y[-1] == 'E' or y[-1] == 'e':
 if k[0] == 'N' or k[0] == 'n' == k[-1] == 'N' or k[-1] == 'n':
 print(s,k,y)
 else:
 print( )

 Answer i Got Below

 Saint-Saens Nielsen Easdale


 Is this what i was going for in the direction i was a bit confused if we
 were suppose create loops or if statements that are verified in the actual
 composers list. I don't know i feel as if i know what i need to do i just
 cant put it together.


At this stage of your experience, don't try to solve the whole thing in
one monolithic piece of code.

Those names shouldn't be in separate variables.  For now, just write a
function that takes a name as a parameter, and attempts to return either
True or False, to indicate whether it matches.

Then after you've debugged that, put those names back into a list, and
write a loop which calls the function you just wrote.



SNIP

 /div/divspanfont color=#88--br
 Dharmit Shahbr
 a href=http://www.about.me/dharmit; 
 target=_blankwww.about.me/dharmit/abr
 /font/spandivdiv___br
 Tutor maillist  -  a href=mailto:Tutor@python.org; 
 target=_blankTutor@python.org/abr
 To unsubscribe or change subscription options:br
 a href=https://mail.python.org/mailman/listinfo/tutor; 
 target=_blankhttps://mail.python.org/mailman/listinfo/tutor/abr
 /div/div/blockquote/divbr/div
 /div/div/blockquote/divbr/div


Please post in text mode.  html mail will mess you up, sooner or later. 
Besides, it adds unnecessary bulk to the message, which matters to those
of us who pay by the byte.

-- 
DaveA


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


Re: [Tutor] List Python Question..Please help

2013-09-27 Thread Mark Lawrence

On 27/09/2013 18:04, Jacqueline Canales wrote:

composers = ['Antheil', 'Saint-Saens', 'Beethoven', 'Easdale', 'Nielsen']
x = 'Antheil'
s = 'Saint-Saens'
h = 'Beethoven'
y = 'Easdale'
k = 'Nielsen'

if s[0] == 'S' or s[0] == 's' == s[-1] == 'S' or s[-1] == 's':
 if y[0] == 'E' or y[0] == 'e' == y[-1] == 'E' or y[-1] == 'e':
 if k[0] == 'N' or k[0] == 'n' == k[-1] == 'N' or k[-1] == 'n':
 print(s,k,y)
 else:
 print( )

Answer i Got Below
 
Saint-Saens Nielsen Easdale
 

Is this what i was going for in the direction i was a bit confused if we
were suppose create loops or if statements that are verified in the
actual composers list. I don't know i feel as if i know what i need to
do i just cant put it together.



Yuck :(  What happens if the list changes?  I suggest that you reread 
the post from Steven D'Aprano but slightly restate your original post 
such that you are looking for names where the final letter is the lower 
case equivalent of the first letter.  In that way your code should 
consist of four lines, the list of names, one for loop, one if statement 
and one print function, the latter assuming Python 3.


Hope this helps.

--
Cheers.

Mark Lawrence

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


Re: [Tutor] List Python Question..Please help

2013-09-27 Thread wesley chun
hello,

well, i have to say that you've at least made a good start at a solution.
right now you're thinking about it very much like a human. try to put
yourself into the shoes of a computer: how can we solve this task for just
ONE name?

once you have that solution, then you can apply the same solution for all
names by looping over or iterating through them. in your solution, you
tried to do everything at once using brute force.

i recommend you take the lessons learned you borrow some of that code and
solve it for a single name. for example, take a look at this pseudocode:

name = 'Guido'
if name first letter == name last letter: # turn this into real Python
using what you have
print 'match'
else:
print 'not a match'

then add the collection and a loop, and you'll be at your solution!

best of luck!
--wesley


On Fri, Sep 27, 2013 at 10:04 AM, Jacqueline Canales jackiexxd...@gmail.com
 wrote:

 composers = ['Antheil', 'Saint-Saens', 'Beethoven', 'Easdale', 'Nielsen']
 x = 'Antheil'
 s = 'Saint-Saens'
 h = 'Beethoven'
 y = 'Easdale'
 k = 'Nielsen'

 if s[0] == 'S' or s[0] == 's' == s[-1] == 'S' or s[-1] == 's':
 if y[0] == 'E' or y[0] == 'e' == y[-1] == 'E' or y[-1] == 'e':
 if k[0] == 'N' or k[0] == 'n' == k[-1] == 'N' or k[-1] == 'n':
 print(s,k,y)
 else:
 print( )

 Answer i Got Below
 
 Saint-Saens Nielsen Easdale
 

 Is this what i was going for in the direction i was a bit confused if we
 were suppose create loops or if statements that are verified in the actual
 composers list. I don't know i feel as if i know what i need to do i just
 cant put it together.


 On Fri, Sep 27, 2013 at 3:14 AM, 罗彭 luopeng...@gmail.com wrote:

 Maybe the length of each name matters, too. You should consider whether
 to skip null('') and single-character('a').


 On Fri, Sep 27, 2013 at 3:57 PM, Dharmit Shah shahdhar...@gmail.comwrote:

 Also, comparison is case sensitive. Meaning, 'A' and 'a' are not the
 same.

 Hope that helps. :)

 On Fri, Sep 27, 2013 at 1:14 PM, Amit Saha amitsaha...@gmail.com
 wrote:
  On Fri, Sep 27, 2013 at 3:48 PM, Jacqueline Canales
  jackiexxd...@gmail.com wrote:
  So I have been trying to do this program using ifs and or loops.
  I am having a hard time solving this question, If you could please
 assist me
  in the right direction.
 
  Write a program that lists all the composers on the list ['Antheil',
  'Saint-Saens', 'Beethoven', 'Easdale', 'Nielsen'] whose name starts
 and ends
  with the same letter (so Nielsen gets lsited, but Antheil doesn't).
 
  I know below it prints the entire list of composers but i dont know
  how to
  do the program above. I think I am thinking to much into but ive
 looked at
  all my notes and online resources and having a hard time coming up
 with
  anything.
  Please help!
 
  composers = ['Antheil', 'Saint-Saens', 'Beethoven', 'Easdale',
 'Nielsen']
  for person in composers:
  print(person)
 
  So, here you are printing every compose as you rightly state above.
  What you now need to do is:
 
  For each of the composers (`person'), you need to check if the first
  letter and the last letter are the same. Here;s a hint:
 
  s='abba'
 
  The first letter:
 
  s[0]
  'a'
 
  The last letter:
 
  s[-1]
  'a'
 
 
  If you now compare these, you will know if they are the same and hence
  you print him/her.
 
  Hope that helps.
  -Amit


-- 
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
A computer never does what you want... only what you tell it.
+wesley chun http://google.com/+WesleyChun : wescpy at gmail :
@wescpyhttp://twitter.com/wescpy
Python training  consulting : http://CyberwebConsulting.com
Core Python books : http://CorePython.com
Python blog: http://wescpy.blogspot.com
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


  1   2   3   4   5   6   7   >