Re: [Tutor] python lists/nested lists

2013-04-13 Thread Steven D'Aprano

On 14/04/13 06:53, Soliman, Yasmin wrote:

How can I calculate the average of a list of numbers (eg [2,5,8,7,3] ) and then 
subtract the avg from the original numbers in the list and print?



You calculate the average by summing the list, then dividing by the number of 
items.

To sum a list of numbers, use the sum() function.

total = sum(some_list)


To get the number of items, use the len() function.

num = len(some_list)


To divide, use the / operator. BUT beware, if you are using Python 2, there is 
a small problem with division: by default, Python will do integer division, 
which is not what you want. (Python 3 fixes this problem).

For example, if you say 17/3 in Python 2, you will get 5, instead of 
5.667. You can fix that two ways: put this line at the very top of 
your program, before anything except comments:

from __future__ import division


Or, use floats instead of ints. If you say 17.0/3 you will get 
5.667 as expected.

If you have a variable, you can convert it into a float using the float() 
function.


Once you have the average, you can print the differences like this:

for value in some_list:
print value - average




Also, if I have a nested list:
sick_patients=[['Sam', 'M', 65, 'chest pain', 101.6], [['Sarah', 'F', 73, 
'dizziness', 98.6], [['Susie', 'F', 34, 'headache', 99.7], [['Scott', 'M', 12, 
'stom ache', 102.3]

and I would like to print out all the patients with a temp > 100 how would I do 
so?



for record in sick_patients:
temp = ... # you have to fill this in, replace the dots with code
if temp > 100:
print record


How would you extract the temperature from the internal lists?


(Hint: the patient's name is record[0], their sex is record[1].)



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


Re: [Tutor] creating dictionary from a list

2013-04-13 Thread Steven D'Aprano

On 14/04/13 05:30, Saad Bin Javed wrote:

This is what I'm using:

for item in lst:
 if item.startswith(('Mon','Tue','Wed','Thu','Fri','Sat','Sun'__))__:
 dict[item] = []
 saveItem = item
 else:
 dict[saveItem].append(item.strip())

gives:
  File "gcalcli_agenda_test.py", line 39
 if item.startswith(('Mon','Tue','Wed','Thu','Fri','Sat','Sun'__))__:
   ^
SyntaxError: invalid syntax



Notice the little caret ^ on the line above "SyntaxError"? It points to where
Python discovers a problem with the syntax of your code.

The underscores do not belong there. They were added by your email program. Why,
I have no idea. Take them out. Likewise with the following underscores.

And with the 'Wed' string. This should be your first hint that something is
wrong. The days of the week start Mon, Tue, Wed, not Mon, Tue, Wed.


(I have no idea what your email program will do with these underscores. If in
doubt, your mail client should give you a way to look at the raw, untouched 
message
source. In Thunderbird, I can go to the View menu and select "Message Source", 
and
that will show the complete email, including all headers and raw attachments. 
That
at least ought to show you the text without any mangling. Hopefully.)




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


Re: [Tutor] creating dictionary from a list

2013-04-13 Thread Steven D'Aprano

On 14/04/13 04:19, Saad Javed wrote:


This creates a dictionary whose keys are out of order in terms of dates.



Dictionaries are unordered. That is to say, they have no defined order, when
you print them, or iterate over them, items will appear in whatever order
they happen. If you modify a dict, the order can even change.

This is by design: access to items in the dict is extremely fast, especially
for large dicts, because Python doesn't have to search through the items one
at a time. Dicts are a type of "hash table", which is why dictionary keys must
be hashable.

(If you don't know what a hash table is, please ask.)

So you cannot rely on dicts being in any specific order.

There is an OrderedDict in the collections module which remembers the order
that items are inserted into the OrderedDict. But that's not quite the same
as items being sorted.



{'Thu Apr 04': ['Weigh In'], 'Sat Apr 06': ['Collect NIC', 'Finish PTI
Video'], 'Wed Apr 10': ['Serum uric acid test'], 'Sun Apr 14': ['Download
Louis CK Oh My God', '4:00pm', 'UPS Guy'], 'Sat Apr 13': ['1:00pm', 'Get
flag from dhariwal']}

Sat Apr 13 is appearing after Sun Apr 14. How do you sort this?



You cannot sort a dictionary directly, but you can sort the keys, then iterate
over them in that order.

keys = sorted(mydict.keys())
for key in keys:
print mydict[key]




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


Re: [Tutor] creating dictionary from a list

2013-04-13 Thread Steven D'Aprano

On 14/04/13 03:38, Saad Javed wrote:


What just happened here? :)

I am trying to learn python so i'm sorry if my mistakes seem trivial.



I have to ask the same question -- what just happened here? Why are you
upset? Mark has given you some good advice, and even added some
light-hearted joviality about somebody fighting an actual python in
real life.

Mark's advice about not "fighting" Python the language is excellent advice,
but of course as a beginner you aren't expected to know what are the most
natural ways to write Python code. If Mark had just stopped there, you
would have reason to be annoyed. But he didn't, he gave you some ideas for
how to re-write the code to be more "Pythonic" (natural for the language).

Mark is correct -- you will very rarely need to use indexing in a for-loop.

# don't do this
for i in range(len(some_list)):
 value = some_list[i]
 process(value)


# instead do this
for value in some_list:
 process(value)


When you need both the value and the index, the most Pythonic way to do so
is to use the built-in function "enumerate":

for index, value in enumerate(some_list):
some_list[index] = process(value)


Also, beware your email program, whatever it is (Outlook?). It has the
unfortunate habit of adding extra characters into the text. Mark wrote
these six lines:

# there are no asterisks or underscores in the following:
for item in lst:
if item.startswith(('Mon','Tue','Wed','Thu','Fri','Sat','Sun')):
myDict[item] = []
saveItem = item
else:
myDict[saveItem].append(item.strip())


but by the time it came back from you quoted, it contains extra asterisks
added:


# mangled by your email client, three lots of double asterisks added:
for item in lst:
if item.startswith(('Mon','Tue','**Wed','Thu','Fri','Sat','Sun'))**:
myDict[item] = []
saveItem = item
else:
myDict[saveItem].append(item.**strip())


and in a later email from you, somehow those asterisks had turned into
underscores! So beware of email clients that try to be "clever", and
mangle what is written.



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


Re: [Tutor] Chapter 3 Projects

2013-04-13 Thread Mariel Jane Sanchez
Thank you for the help, it was really convenient. 



 From: ALAN GAULD 
To: Mariel Jane Sanchez  
Cc: "tutor@python.org"  
Sent: Tuesday, April 9, 2013 6:29:57 PM
Subject: Re: [Tutor] Chapter 3 Projects
 


Forwarded to group. Please use ReplyAll when responding to tutor posts.


>
> From: Mariel Jane Sanchez 
>To: Alan Gauld  
>Sent: Wednesday, 10 April 2013, 1:06
>Subject: Re: [Tutor] Chapter 3 Projects
> 
>
>
>Thank you so much, I finally figured out the 2nd project. I still have 
>problems with 1 and 3 so I'll try to be more clear. 
>
>It would help if you posted your code. It shouldn't be long and its much 
>easier to see where you are getting confused if we can see the code!
Chapter 3 Booklet PDF is attached
>
>Chapter 3 
>Project 1 on page 90 on the PDF
>"1. Write a program that gets a score from the player and rates it on the 
>following:
>- Given a score between 0-999, the program should display the message, 
>'Nothing to brag about."
>- Given a score between 1000-, the program should display the message, 
>'Good score.'
>- Given a score over , the program should display the message, 'Very 
>impressive!"
>- If the score is a negative number, the program should display the message, 
>'That is not a legal score!'"
>
>I'd do it like this

score = raw_input('score? ')
if score < 0: print 'That is not a legal score'
elif score > : print 'Very impressive'
elif  >= score >= 1000: print 'Good score.'
elif  # student to complete...


>
>I tried using range as another tutor suggested which would make sense since 
>it's dealing with ranges but I still get the same result as before. Can you 
>explain how to do this step by step, if you don't mind?
>
>You can use range by substituting the elif lines above with:

elif score in range(1000,1): print 'Good score.'

Project 3 (Guess My Number code on page 35)
>"Modify the Guess My Number program from the chapter so that the player has 
>only five guesses. If the player runs out of guesses, the program should end 
>the game and display an appropriately chastising message"
>For my case, I somehow, accidentally programmed it to have only 5 tries and 
>also put a message that says " You ran out of tries," which I think is a good 
>progress. However, on the last try; when I put my guess, hit enter and got the 
>guess wrong, the message loops. 
>
>I  showed you the structure for this last time.
Without seeing your code I have no idea what you did wrong.


When you first started on Python, how did you do this project so there's no 
loop at the end?
>
>I did not do those projects because I did not do the course that you are 
>doing. 
I did not in fact do any courses, I just read the official documents and made 
up my own projects. So I can't tell you how I did it. I can only comment on how 
I might 
do it now.
 
Alan Gauld
Author of the Learn To Program website

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


Re: [Tutor] python lists/nested lists

2013-04-13 Thread Alan Gauld

On 13/04/13 21:53, Soliman, Yasmin wrote:

How can I calculate the average of a list of numbers (eg [2,5,8,7,3] )

> and then subtract the avg from the original numbers
> in the list and print?

This sounds like homework which we don;t do for you.

However to calculate the average take the sum and divide by the count.
Do you know how to do those two things?

Once you have the average you need to iterate over your list and 
subtract the average you calculated (and stored) and print the result.



Also, if I have a nested list:
sick_patients=[

['Sam', 'M', 65, 'chest pain', 101.6],
[   ['Sarah', 'F', 73, 'dizziness', 98.6],
[   ['Susie', 'F', 34, 'headache', 99.7],
[   ['Scott', 'M', 12, 'stom ache', 102.3]

I don't think that's really the structure you intended?
but if it is there is a bunch of missing brackets at the end...


and I would like to print out all the patients with a temp > 100 how would I do 
so?


You would iterate over the list testing the temperature element of each 
sublist against 100 and if necessary printing the result.


Now try writing some code and if it doesn't work show us what you've 
done including any error messages(in full) that you get.


PS. As a matter of style your patient records should probably be tuples 
or dictionaries rather than lists. But that's a nicety to keep for 
another time...


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

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


Re: [Tutor] creating dictionary from a list

2013-04-13 Thread eryksun
On Fri, Apr 12, 2013 at 7:52 PM, Saad Bin Javed  wrote:
> Hi, I'm using a script to fetch my calendar events. I split the output at
> newline which produced a list 'lst'. I'm trying to clean it up and create a
> dictionary with date:event key value pairs. However this is throwing up a
> bunch of errors.
>
> lst = ['', 'Thu Apr 04   Weigh In', '', 'Sat Apr 06 Collect NIC', \
> ' Finish PTI Video', '', 'Wed Apr 10   Serum
> uric acid test', \
> '', 'Sat Apr 13   1:00pm  Get flag from dhariwal', '', 'Sun Apr 14
> Louis CK Oh My God', '', '']

Don't forget to handle entries with times such as "Sat Apr 13   1:00pm".

I think it would be simpler in the long run to use a module that
parses iCalendar files. Your calendar application should support
exporting to iCalendar (.ics, .ical).

http://en.wikipedia.org/wiki/ICalendar

Here's an example sorting the events in the Python event calendar:

import urllib2
import datetime

# https://pypi.python.org/pypi/icalendar
import icalendar

pyevent_url = (
  'http://www.google.com/calendar/ical/'
  'j7gov1cmnqr9tvg14k621j7t5c%40'
  'group.calendar.google.com/public/basic.ics')

pyevent_ics = urllib2.urlopen(pyevent_url).read()
pyevent_cal = icalendar.Calendar.from_ical(pyevent_ics)

You need a key function to sort the VEVENT entries by DTSTART:

def dtstart_key(vevent):
try:
dt = vevent['dtstart'].dt
except KeyError:
dt = datetime.datetime.min
if isinstance(dt, datetime.date):
dt = datetime.datetime.combine(dt, datetime.time.min)
return dt

If dt is a datetime.date, this key function converts it to a
datetime.datetime set to midnight (datetime.time.min). If the DTSTART
field is missing it uses datetime.datetime.min (0001-01-01 00:00).

Use walk('vevent') to show only the VEVENT entries in the calendar
(i.e. filter out VTODO, VJOURNAL, etc):

events = sorted(pyevent_cal.walk('vevent'), key=dtstart_key)

The last event (index -1) is PyCon DE 2013 on 14 Oct:

>>> events[-1]['description']
vText(u'https://2013.de.pycon.org/";>PyCon DE 2013')

>>> events[-1]['dtstart'].dt
datetime.date(2013, 10, 14)
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] python lists/nested lists

2013-04-13 Thread Mark Lawrence

On 13/04/2013 21:53, Soliman, Yasmin wrote:

How can I calculate the average of a list of numbers (eg [2,5,8,7,3] ) and then 
subtract the avg from the original numbers in the list and print?



lst = [2,5,8,7,3]
avg = sum(lst) / len(lst)
print(avg)
for n in lst:
print(n - avg)


Also, if I have a nested list:
sick_patients=[['Sam', 'M', 65, 'chest pain', 101.6], [['Sarah', 'F', 73, 
'dizziness', 98.6], [['Susie', 'F', 34, 'headache', 99.7], [['Scott', 'M', 12, 
'stom ache', 102.3]

and I would like to print out all the patients with a temp > 100 how would I do 
so?


for patient in sick_patients:
if patient[-1] > 100:
print(patient)

The above works if you fix the syntax errors in sick_patients, you do't 
need all the double brackets.


--
If you're using GoogleCrap™ please read this 
http://wiki.python.org/moin/GoogleGroupsPython.


Mark Lawrence

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


[Tutor] python lists/nested lists

2013-04-13 Thread Soliman, Yasmin
How can I calculate the average of a list of numbers (eg [2,5,8,7,3] ) and then 
subtract the avg from the original numbers in the list and print? 

Also, if I have a nested list: 
sick_patients=[['Sam', 'M', 65, 'chest pain', 101.6], [['Sarah', 'F', 73, 
'dizziness', 98.6], [['Susie', 'F', 34, 'headache', 99.7], [['Scott', 'M', 12, 
'stom ache', 102.3]

and I would like to print out all the patients with a temp > 100 how would I do 
so?
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] creating dictionary from a list

2013-04-13 Thread Mark Lawrence

On 13/04/2013 21:06, Saad Javed wrote:

I don't know what I'm doing wrong here. Ive tried copy-pasting the line.
I've tried entering underscores manually. doesn't work.


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



The underscores are the syntax error.  If you'd bothered to read my 
previous two replies and actually compared your original line of code to 
the line with the underscores you'd have seen this for yourself.


--
If you're using GoogleCrap™ please read this 
http://wiki.python.org/moin/GoogleGroupsPython.


Mark Lawrence

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


Re: [Tutor] creating dictionary from a list

2013-04-13 Thread Saad Javed
I don't know what I'm doing wrong here. Ive tried copy-pasting the line.
I've tried entering underscores manually. doesn't work.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] creating dictionary from a list

2013-04-13 Thread Mark Lawrence

On 13/04/2013 20:30, Saad Bin Javed wrote:

On 04/14/2013 12:08 AM, Mark Lawrence wrote:

On 13/04/2013 19:45, Saad Javed wrote:


 for item in lst:
  if


item.startswith(('Mon','Tue','Wed','Thu','Fri','Sat','Sun'__))__:
  myDict[item] = []
  saveItem = item
  else:
  myDict[saveItem].append(item.strip())

Returns:
  File "gcalcli_agenda_test.py", line 38
 if
item.startswith(('Mon','Tue','__Wed','Thu','Fri','Sat','Sun'))__:
   ^
SyntaxError: invalid syntax



Please compare your original line with the line above and note the
differences.  That'll account for the syntax error, which appears to
have been introduced by your email client.


This is what I'm using:

for item in lst:
 if
item.startswith(('Mon','Tue','Wed','Thu','Fri','Sat','Sun'__))__:
 dict[item] = []
 saveItem = item
 else:
 dict[saveItem].append(item.strip())

gives:
  File "gcalcli_agenda_test.py", line 39
 if
item.startswith(('Mon','Tue','Wed','Thu','Fri','Sat','Sun'__))__:
   ^
SyntaxError: invalid syntax



Please compare your original line with the line above and note the
differences.  That'll account for the syntax error, which appears to
have been introduced by your email client.

--
If you're using GoogleCrap™ please read this 
http://wiki.python.org/moin/GoogleGroupsPython.


Mark Lawrence

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


Re: [Tutor] creating dictionary from a list

2013-04-13 Thread Saad Bin Javed

On 04/14/2013 12:08 AM, Mark Lawrence wrote:

On 13/04/2013 19:45, Saad Javed wrote:


 for item in lst:
  if


item.startswith(('Mon','Tue','Wed','Thu','Fri','Sat','Sun'__))__:
  myDict[item] = []
  saveItem = item
  else:
  myDict[saveItem].append(item.strip())

Returns:
  File "gcalcli_agenda_test.py", line 38
 if item.startswith(('Mon','Tue','__Wed','Thu','Fri','Sat','Sun'))__:
   ^
SyntaxError: invalid syntax



Please compare your original line with the line above and note the
differences.  That'll account for the syntax error, which appears to
have been introduced by your email client.


This is what I'm using:

for item in lst:
if item.startswith(('Mon','Tue','Wed','Thu','Fri','Sat','Sun'__))__:
dict[item] = []
saveItem = item
else:
dict[saveItem].append(item.strip())

gives:
 File "gcalcli_agenda_test.py", line 39
if 
item.startswith(('Mon','Tue','Wed','Thu','Fri','Sat','Sun'__))__:

  ^
SyntaxError: invalid syntax


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


Re: [Tutor] creating dictionary from a list

2013-04-13 Thread Mark Lawrence

On 13/04/2013 19:45, Saad Javed wrote:


 for item in lst:
  if

item.startswith(('Mon','Tue','Wed','Thu','Fri','Sat','Sun'__))__:
  myDict[item] = []
  saveItem = item
  else:
  myDict[saveItem].append(item.strip())

Returns:
  File "gcalcli_agenda_test.py", line 38
 if item.startswith(('Mon','Tue','__Wed','Thu','Fri','Sat','Sun'))__:
   ^
SyntaxError: invalid syntax



Please compare your original line with the line above and note the 
differences.  That'll account for the syntax error, which appears to 
have been introduced by your email client.


--
If you're using GoogleCrap™ please read this 
http://wiki.python.org/moin/GoogleGroupsPython.


Mark Lawrence

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


Re: [Tutor] creating dictionary from a list

2013-04-13 Thread Saad Javed
> for item in lst:
>>  if
>> item.startswith(('Mon','Tue','**__Wed','Thu','Fri','Sat','Sun'**))__:
>>  myDict[item] = []
>>  saveItem = item
>>  else:
>>  myDict[saveItem].append(item._**_strip())
>>
>> Returns:
 File "gcalcli_agenda_test.py", line 38
if item.startswith(('Mon','Tue','__Wed','Thu','Fri','Sat','Sun'))__:
  ^
SyntaxError: invalid syntax
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] creating dictionary from a list

2013-04-13 Thread Mark Lawrence

On 13/04/2013 19:19, Saad Javed wrote:



Don't fight Python, unlike this chap[1] :)  Basically if you're
looping around any data structure you rarely need to use indexing,
so try this approach.

for item in lst:
 if
item.startswith(('Mon','Tue','__Wed','Thu','Fri','Sat','Sun'))__:
 myDict[item] = []
 saveItem = item
 else:
 myDict[saveItem].append(item.__strip())


This creates a dictionary whose keys are out of order in terms of dates.

{'Thu Apr 04': ['Weigh In'], 'Sat Apr 06': ['Collect NIC', 'Finish PTI
Video'], 'Wed Apr 10': ['Serum uric acid test'], 'Sun Apr 14':
['Download Louis CK Oh My God', '4:00pm', 'UPS Guy'], 'Sat Apr 13':
['1:00pm', 'Get flag from dhariwal']}

Sat Apr 13 is appearing after Sun Apr 14. How do you sort this?



http://docs.python.org/3/library/collections.html#collections.OrderedDict

--
If you're using GoogleCrap™ please read this 
http://wiki.python.org/moin/GoogleGroupsPython.


Mark Lawrence

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


Re: [Tutor] creating dictionary from a list

2013-04-13 Thread Saad Javed
>
> Don't fight Python, unlike this chap[1] :)  Basically if you're looping
> around any data structure you rarely need to use indexing, so try this
> approach.
>
> for item in lst:
> if item.startswith(('Mon','Tue','**Wed','Thu','Fri','Sat','Sun'))**:
> myDict[item] = []
> saveItem = item
> else:
> myDict[saveItem].append(item.**strip())
>

This creates a dictionary whose keys are out of order in terms of dates.

{'Thu Apr 04': ['Weigh In'], 'Sat Apr 06': ['Collect NIC', 'Finish PTI
Video'], 'Wed Apr 10': ['Serum uric acid test'], 'Sun Apr 14': ['Download
Louis CK Oh My God', '4:00pm', 'UPS Guy'], 'Sat Apr 13': ['1:00pm', 'Get
flag from dhariwal']}

Sat Apr 13 is appearing after Sun Apr 14. How do you sort this?
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] creating dictionary from a list

2013-04-13 Thread Saad Javed
What just happened here? :)

I am trying to learn python so i'm sorry if my mistakes seem trivial.

On Saturday, April 13, 2013, Mark Lawrence wrote:

> On 13/04/2013 15:34, Saad Bin Javed wrote:
>
>> I ran into a bit of problem with my revised code based on Steven's
>> suggestions.
>>
>> lst = ['', 'Thu Apr 04   Weigh In', '', 'Sat Apr 06 Collect
>> NIC', ' Finish PTI Video', '', 'Wed Apr 10  Serum
>> uric acid test', '', 'Sat Apr 13   1:00pm  Get flag from dhariwal', '',
>> 'Sun Apr 14  Louis CK Oh My God', '', '']
>>
>> lst = filter(None, lst)
>> lst = [item.split('  ') for item in lst]
>> lst = [item for sublist in lst for item in sublist]
>> lst = filter(None, lst)
>>
>> This code would produce:
>>
>> ['Thu Apr 04', ' Weigh In', 'Sat Apr 06', ' Collect NIC', ' Finish PTI
>> Video', 'Wed Apr 10', ' Serum uric acid test', 'Sat Apr 13', ' 1:00pm',
>> 'Get flag from dhariwal', 'Sun Apr 14', ' Download Louis CK Oh My God']
>>
>> dict = {}
>> for item in lst:
>>  if item.startswith(('Mon','Tue','**Wed','Thu','Fri','Sat','Sun'))**:
>>
>>  dict.update({lst[lst.index(**item)].lstrip():
>> lst[lst.index(item)+1].lstrip(**)})
>> print dict
>>
>> Such a dictionary would only add the item next to the date as the value.
>> But from the list you can see 'Sat Apr 06' has two items on the agenda
>> while 'Sat Apr 13' show item and a time. So you can understand why such
>> a dict would be useless.
>>
>> I want all agenda items joined as a comma delimited string and added to
>> the date key as a value. I've been mulling over how to go about it. One
>> idea was to get indices of dates in the list and add all items in
>> between them as values.
>>
>> index_keys = [] #0, 2, 5, 7, 9
>> index_values = [] #1, 3, 4, 6, 8, 10
>> for item in lst:
>>  if
>> item.lstrip().startswith(('**Mon','Tue','Wed','Thu','Fri','**
>> Sat','Sun')):
>>  index_keys.append(lst.index(**item))
>>  else:
>>  index_values.append(lst.index(**item))
>>
>> But I can't quite get it to understand that i want all items between
>> position 0 and 2 in the list to be assigned to item at 0 in the
>> dictionary and so forth.
>>
>> Ideas?
>>
>>
> Don't fight Python, unlike this chap[1] :)  Basically if you're looping
> around any data structure you rarely need to use indexing, so try this
> approach.
>
> for item in lst:
> if item.startswith(('Mon','Tue','**Wed','Thu','Fri','Sat','Sun'))**:
> myDict[item] = []
> saveItem = item
> else:
> myDict[saveItem].append(item.**strip())
>
>
> [1]http://www.bbc.co.uk/news/**world-us-canada-22118773
>
> --
> If you're using GoogleCrap™ please read this http://wiki.python.org/moin/*
> *GoogleGroupsPython .
>
> Mark Lawrence
>
> __**_
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/**mailman/listinfo/tutor
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] creating dictionary from a list

2013-04-13 Thread Mark Lawrence

On 13/04/2013 15:34, Saad Bin Javed wrote:

I ran into a bit of problem with my revised code based on Steven's
suggestions.

lst = ['', 'Thu Apr 04   Weigh In', '', 'Sat Apr 06 Collect
NIC', ' Finish PTI Video', '', 'Wed Apr 10  Serum
uric acid test', '', 'Sat Apr 13   1:00pm  Get flag from dhariwal', '',
'Sun Apr 14  Louis CK Oh My God', '', '']

lst = filter(None, lst)
lst = [item.split('  ') for item in lst]
lst = [item for sublist in lst for item in sublist]
lst = filter(None, lst)

This code would produce:

['Thu Apr 04', ' Weigh In', 'Sat Apr 06', ' Collect NIC', ' Finish PTI
Video', 'Wed Apr 10', ' Serum uric acid test', 'Sat Apr 13', ' 1:00pm',
'Get flag from dhariwal', 'Sun Apr 14', ' Download Louis CK Oh My God']

dict = {}
for item in lst:
 if item.startswith(('Mon','Tue','Wed','Thu','Fri','Sat','Sun')):

 dict.update({lst[lst.index(item)].lstrip():
lst[lst.index(item)+1].lstrip()})
print dict

Such a dictionary would only add the item next to the date as the value.
But from the list you can see 'Sat Apr 06' has two items on the agenda
while 'Sat Apr 13' show item and a time. So you can understand why such
a dict would be useless.

I want all agenda items joined as a comma delimited string and added to
the date key as a value. I've been mulling over how to go about it. One
idea was to get indices of dates in the list and add all items in
between them as values.

index_keys = [] #0, 2, 5, 7, 9
index_values = [] #1, 3, 4, 6, 8, 10
for item in lst:
 if
item.lstrip().startswith(('Mon','Tue','Wed','Thu','Fri','Sat','Sun')):
 index_keys.append(lst.index(item))
 else:
 index_values.append(lst.index(item))

But I can't quite get it to understand that i want all items between
position 0 and 2 in the list to be assigned to item at 0 in the
dictionary and so forth.

Ideas?



Don't fight Python, unlike this chap[1] :)  Basically if you're looping 
around any data structure you rarely need to use indexing, so try this 
approach.


for item in lst:
if item.startswith(('Mon','Tue','Wed','Thu','Fri','Sat','Sun')):
myDict[item] = []
saveItem = item
else:
myDict[saveItem].append(item.strip())


[1]http://www.bbc.co.uk/news/world-us-canada-22118773

--
If you're using GoogleCrap™ please read this 
http://wiki.python.org/moin/GoogleGroupsPython.


Mark Lawrence

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


Re: [Tutor] creating dictionary from a list

2013-04-13 Thread Saad Bin Javed
I ran into a bit of problem with my revised code based on Steven's 
suggestions.


lst = ['', 'Thu Apr 04   Weigh In', '', 'Sat Apr 06 Collect 
NIC', ' Finish PTI Video', '', 'Wed Apr 10 
 Serum uric acid test', '', 'Sat Apr 13   1:00pm  Get flag from 
dhariwal', '', 'Sun Apr 14  Louis CK Oh My God', '', '']


lst = filter(None, lst)
lst = [item.split('  ') for item in lst]
lst = [item for sublist in lst for item in sublist]
lst = filter(None, lst)

This code would produce:

['Thu Apr 04', ' Weigh In', 'Sat Apr 06', ' Collect NIC', ' Finish PTI 
Video', 'Wed Apr 10', ' Serum uric acid test', 'Sat Apr 13', ' 1:00pm', 
'Get flag from dhariwal', 'Sun Apr 14', ' Download Louis CK Oh My God']


dict = {}
for item in lst:
if item.startswith(('Mon','Tue','Wed','Thu','Fri','Sat','Sun')):

dict.update({lst[lst.index(item)].lstrip(): 
lst[lst.index(item)+1].lstrip()})

print dict

Such a dictionary would only add the item next to the date as the value. 
But from the list you can see 'Sat Apr 06' has two items on the agenda 
while 'Sat Apr 13' show item and a time. So you can understand why such 
a dict would be useless.


I want all agenda items joined as a comma delimited string and added to 
the date key as a value. I've been mulling over how to go about it. One 
idea was to get indices of dates in the list and add all items in 
between them as values.


index_keys = [] #0, 2, 5, 7, 9
index_values = [] #1, 3, 4, 6, 8, 10
for item in lst:
if 
item.lstrip().startswith(('Mon','Tue','Wed','Thu','Fri','Sat','Sun')):
index_keys.append(lst.index(item))
else:
index_values.append(lst.index(item))

But I can't quite get it to understand that i want all items between 
position 0 and 2 in the list to be assigned to item at 0 in the 
dictionary and so forth.


Ideas?

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


Re: [Tutor] design question (Django?)

2013-04-13 Thread Alan Gauld

On 13/04/13 09:48, Albert-Jan Roskam wrote:


I think I have to make a diagram of this. This stuff is quite hard


You could use a simple UML class diagram (class -> table). See the OOP 
topic in my V3 tutorial for simple examples.


Or you could use a proper entity relationship diagram(ERD) - see 
wikipedia for details and examples (there are various notational variations)


They all show the same concepts. UML will be best if you plan
on using OOP in the python code. ERD is better for vanilla database design.

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

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


Re: [Tutor] creating dictionary from a list

2013-04-13 Thread Brian van den Broek
On 12 Apr 2013 21:25, "Steven D'Aprano"  wrote:

> Also, you might find it easier to process the list if you strip out empty
items. There are two simple ways to do it:
>
>
> lst = [x for x in list if x != '']
> # or
> lst = filter(None, lst)

Hi all,

For the first, I would use

lst = [x for x in list if x]

instead.

Best,

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


Re: [Tutor] design question (Django?)

2013-04-13 Thread Albert-Jan Roskam
Hi Alan,

Thanks for your reply!


> Subject: Re: [Tutor] design question (Django?)

> 
> Some clarification please.
> 
>>  (1) Database design. Here are the database tables I think are necessary:
>>  tblPostalcode: pc6, streetname, nHouseholds, isVisitable, remarks
>>  tblCollectorSelection: collectorname, streetname, selectiondate
> 
> streetname is in both so presumably is the link between collector and the 
> postcodes? Can a steetname be in multiple postcodes? So if a collector 
> selects a 
> street does he implicitly select multiple post codes?

Yes, a street name can be in multiple postcodes (typically odd and even street 
numbers of long streets have different postcodes). For example, postcodes (pc4) 
of the longest street of the country (in The Hague) are 2517, 2555:
http://www.postcode.nl/index.php?goto=postcoderesult&action=page&pagenum=0&address=den+haag%2C+Laan+van+Meerdervoort&TreeID=1
 So, yes, the collector may select multiple postcodes when selecting just one 
street. Historically, pc6 is a concept from the mail service. One pc6 is 
(literally) a handful of mail for a mailman. One record in 
tblCollectorSelection = one pc6 selected by that collector. But since most 
people think in terms of street names rather than in pc6, the selection is made 
by ticking boxes with street names.

Come to think of it, I may also need a tblCollectors, with name, adress, postal 
code, phone number of the collector, preferredPostalCode (some collectors want 
to collect in another pc6 than where they live).
 
> Does a postcode only have a single street? (Ours can have several)

It's the same as with you in the UK/Scotland. Often one postcode has just one 
street, but there are exceptions.

> I assume isVisitable is a derived field that you are going to calculate each 
> time based on the number of collectors who have selected the postcode? 

isVisitable would be PO boxes, apartment buildings that do not admit any 
collectors at their main entrance,
industrial zones, dangerous neighbourhoods, and maybe a few more categories.

>If so it 
> may be easier and more efficient to have a mapping table to manage the 
> relationship of collectors to postcodes and another table for the collector 
> data 
> (although you don't appear to be holding much collector data, which 
> surprises me... I assume the users will be collectors with login credentials 
> etc?)

yes, collectors are assigned to groups (of about 8 persons) and they should get 
login credentials (which are stored in tblCollectors (?)).

> As always when modelling data the important information is the relationships 
> between the entities and I'm not sure I understand
> the relationships between street, postcode and collector.

I think I have to make a diagram of this. This stuff is quite hard for me, but 
it's important to get the basis right.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] design question (Django?)

2013-04-13 Thread Alan Gauld

Some clarification please.


(1) Database design. Here are the database tables I think are necessary:
tblPostalcode: pc6, streetname, nHouseholds, isVisitable, remarks
tblCollectorSelection: collectorname, streetname, selectiondate


streetname is in both so presumably is the link between collector and 
the postcodes? Can a steetname be in multiple postcodes? So if a 
collector selects a street does he implicitly select multiple post codes?


And

Does a postcode only have a single street? (Ours can have several)

I assume isVisitable is a derived field that you are going to calculate 
each time based on the number of collectors who have selected the 
postcode? If so it may be easier and more efficient to have a mapping 
table to manage the relationship of collectors to postcodes and another 
table for the collector data (although you don't appear to be holding 
much collector data, which surprises me... I assume the users will be 
collectors with login credentials etc?)


As always when modelling data the important information is the 
relationships between the entities and I'm not sure I understand

the relationships between street, postcode and collector.

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

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


[Tutor] design question (Django?)

2013-04-13 Thread Albert-Jan Roskam
Hi,

I am doing volunteer work for a charity. The job is to coordinate money 
collecting activities of people who
raise money with collecting-boxes. I am involved with one postal code  4 (pc4) 
area (our postal codes have the format 1234 AB (postal code 6). So 'one postal 
code 4 area'  means [0-9]{4}[A-Z]{2} (1234AA, 1234AB, etc.). One pc4 area is 
typically divided over a group of 8 people who actually go out there to collect 
the money.

I would like to make a webtool that makes it possible for collectors to select 
what streets they want to visit.
Other collectors of their pc4 area should also be able to see their selection, 
once it's final (it's a BIG no-no that the same street is visited by multiple 
collectors in the same week). Selection would be done by selecting street names 
or pc6 (tick boxes). A selection would be visualized on a map (a different 
color for each collector). The number of households associated with the 
selection is shown to see if the selection is a realistic amount.

Now, this is where Python comes in. Or wait, maybe not quite yet. The problem 
should (I think) be divided into two major steps: (1) database design (2) UI 
design (Python, I hope!)

(1) Database design. Here are the database tables I think are necessary:
tblPostalcode: pc6, streetname, nHouseholds, isVisitable, remarks
tblCollectorSelection: collectorname, streetname, selectiondate

(2) UI design. Ah, finally, Python. ;-) I had Django in mind to create the web 
interface and GeoDjango to display the selection on a map. I am open for other 
suggestions though (D3?). I am not even sure how realistic this is, given that 
I have zilch experience with web programming (and Java script). The whole thing 
should be non-geeky, non-techy for users.

I would love to hear your thoughts about this. Does this make sense? Is Django 
a good choice?

Regards,
Albert-Jan

ps: sorry about the large amount of text. ;-)


~~
All right, but apart from the sanitation, the medicine, education, wine, public 
order, irrigation, roads, a 
fresh water system, and public health, what have the Romans ever done for us?

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