Re: [Tutor] truncated dictionary return

2013-12-02 Thread Wolfgang Maier
richard kappler  gmail.com> writes:

> 
> 
> Now I'm completely lost. While opening the serial port outside the
function sounds like a good idea, I'm thinking that might not work unless I
am mistaken. The sensorRead function once it's called would then basically
own the serial port barring other traffic, yes? That won't work as the same
serial port that receives sensor data from the arduino sends propulsion and
nav signals to the arduino which, along with controlling/reading the
sensors, also controls the motors used for propulsion, hence only opening
the port when the data is called for. The sensorRead function works, heck
it's not even mine, it was written by one of the gurus here in response to a
question I posed months ago (either Alan or Eryksun IIRC) and does exactly
what it's supposed to do, except for the timing bit.
>

No doubt, the parsing the line into a dictionary part of the function works
(and, yes, it's obvious that it was written by someone with more Python
experience than yours - no offense here :) ).
What I'm trying to tell you is that the overall control flow of your program
seems to be wrong.

> 
> Perhaps I'm looking for a simple solution where none exists but I rather
doubt it. I was thinking something along the lines of (psuedo code here)
> check incoming dict for length or number of elements
> if 8, keep
> else retry
>

This won't help, if you cannot implement the retry. You have lost a line of
data at this point and you won't be able to bring it back magically, so the
question is can you live with that?
 
> While I appreciate the above comments and any help that is offered, I
neither understand them as presented nor think they will fix the problem
with the limited understanding I do have. Again, it could be my lack of
knowledge is preventing me from seeing the light here, but it feels like
we're reinventing the wheel.
> 
> I hope that didn't come across as rude, it truly was not intended to be such.
> 
> regards, Richard
> 
>

I think you're simply not understanding the mechanism of readline(). That
method will gather bytes from the serial port until it sees a newline, then
(and only then!) return the complete line to the caller. That means your
program will be blocked when you call readline() until a complete line has
been transmitted, i.e., your sensorRead function will "own the serial port"
as you call it anyway. If this is not what you want, you'll have to use
read() instead of readline() and manage buffering yourself. Again, with
readline() your script will be halted until a full line of sensor reads data
has been transmitted, independent of where and when you opened the connection.
Now about keeping the connection alive: As you realized (I guess that is
your sync issue), you cannot control when data gets sent. This means that
you need to keep listening continuously or you may miss the beginning of a
transmission. Again, readline() will make sure that you get everything up to
the end of a line, but if you happen to open the arduino connection in the
middle of the transmission of a line, readline() has no means of restoring
the beginning of the line and your input will be incomplete (this is exactly
what's going wrong when your current code fails).
So, keep the connection alive during your script!
Switching between sending and receiving is the task of your main program
(that's the # do something with the data part in my previous message, see
below again):

def sensorRead (arduino):
line = arduino.readline().strip()
line = line.lstrip('{').rstrip('}').strip()
# rest of your code

# your main program:
# open the connection
arduino = serial.Serial('/dev/ttyACM0', 9600)
sleep(1)
# keep operating
while True:
# parse a single line of sensor reads data and store it as a dict
reads = sensorRead(arduino)
# do something with the data, i.e. react to it by sending commands

Best,
Wolfgang




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


Re: [Tutor] Hash map and dictionaries

2013-12-02 Thread Steven D'Aprano
On Sun, Dec 01, 2013 at 09:10:42PM +0530, Reuben wrote:
> Hi
> 
> Question 1:
> -
> I would like to know the concept of hash map. Additionally,  I got to know
> that hash maps are equivalent to dictionaries in python.
> 
> I would like to understand the relationship between dictionaries and hash
> map better.

Pythin dictionaries are hash maps. A hash map is another name for a hash 
table.

I already answered your earlier question about dictionaries with a 
description of hash tables:

https://mail.python.org/pipermail/tutor/2013-November/098436.html

If anything is unclear, please ask.



> Question 2:
> --
> It is also said that in a list of may be 10,000 elements(specifically
> integers), hash maps would be a better option to find the occurrence of
> repetitive integers
> 
> How can this be implemented using dictionaries for a list of 10,000 integer
> elements?

You don't use dicts as lists. If you want a list, use a list:

# list of five integers
[2, 7, 19, 25, 3]

Where hash tables are good is when you want to map a "key" to a "value", 
or another way to say the same thing, to *associate* a key to a value. 
Think of a paper dictionary, where every word is followed by a 
definition -- the key is the word itself, the value is the definition.

There are many names for the same thing:

dict
hash table
hash map
associative array
symbol table
mapping

For example, if you want to associate (map) a person's name to their 
birthday:

{"Susan": "1985-12-03",
 "Fred": "1960-03-15",
 "George": "1973-10-27",
 }


So if you want to map a number to some other piece of data, a dict is 
must better than a list. Searching a list normally depends on how many 
items are in the list -- if there are 10,000 items in the list, you will 
need to inspect 5000 items on average. Searching a dict normally takes 
exactly the same amount of time whether there is one item or 1 
items.

e.g.:

{2: "two",
 7: "seven",
 19: "nineteen",
 25: "twenty-five",
 3: "three",
 # and ten thousand more
 }


versus:

[(2, "two"), 
 (7, "seven"), 
 (19, "nineteen"), 
 (25: "twenty-five"),
 (3, "three"),
 # and ten thousand more
 ]

the dict will be thousands of times faster, on average.


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


Re: [Tutor] Loop over floating point values

2013-12-02 Thread Steven D'Aprano
On Mon, Dec 02, 2013 at 04:28:38PM +1000, Amit Saha wrote:
> On Sun, Dec 1, 2013 at 7:26 PM, Steven D'Aprano  wrote:

> > Such floating point loops are tricky to get right, thanks to rounding of
> > floats. Observe:
> >
> > py> x = 0.0
> > py> while x < 1.0:
> > ... x += 0.1
> > ...
> > py> x == 1.0
> > False
> > py> x
> > 1.0999
> >
> > We expect that after the loop is done, x should equal 1, but it doesn't.
> > That means that it actually loops one time too many.
> 
> Indeed, that's a good point. Surprisingly, C does it just fine:

That's because your example uses C singles, not doubles. If you do it 
again using doubles, I expect you'll see the same behaviour as Python 
(Python floats are implemented as C doubles under the hood).

With singles, you'll have the same kind of error but with different 
values. Sometimes having less precision makes the errors cancel out, 
sometimes it doesn't.


-- 
Steven

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


[Tutor] need a hint

2013-12-02 Thread Byron Ruffin
The following program works and does what I want except for one last
problem I need to handle.   The program reads a txt file of senators and
their associated states and when I input the last name it gives me their
state.  The problem is "Udall".  There are two of them.  The txt file is
read by line and put into a dictionary with the names split.  I need a
process to handle duplicate names.  Preferably one that will always work
even if the txt file was changed/updated.  I don't want the process to
handle the name "Udall" specifically.   For a duplicate name I would like
to tell the user it is not a unique last name and then tell them to enter
first name and then return the state of that senator.

Thanks

An excerpt of txt file...
ArkansasMark Pryor (D)20032015
ArkansasJohn Boozman (R)20112017
CaliforniaDianne Feinstein (D)19922019
CaliforniaBarbara Boxer (D)19932017
ColoradoMark Udall (D)20092015
ColoradoMichael F. Bennet (D)20092017



def createList(state):

senateInfo = {}

info = open( "USSenators.txt", "r" )

for line in info:

dataOnLine = line.split( "\t" )
state = dataOnLine[ 0 ]
senator = dataOnLine[ 1 ]

nameSplit = dataOnLine[ 1 ].split(" ")

if len(nameSplit) == 3:
lastName = nameSplit[1]


elif len(nameSplit) == 4:
lastName = nameSplit[2]


senateInfo[lastName] = state

info.close()

return senateInfo


def test( senator, usSenators ):
print( usSenators[senator] )


def main():
usSenators = createList( "USSenators.txt" )
senator = input("Enter last name of Senator")
test(senator, usSenators )
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] need a hint

2013-12-02 Thread Oscar Benjamin
On 2 December 2013 02:25, Byron Ruffin  wrote:
>
> The following program works and does what I want except for one last problem
> I need to handle.   The program reads a txt file of senators and their
> associated states and when I input the last name it gives me their state.
> The problem is "Udall".  There are two of them.  The txt file is read by
> line and put into a dictionary with the names split.  I need a process to
> handle duplicate names.  Preferably one that will always work even if the
> txt file was changed/updated.  I don't want the process to handle the name
> "Udall" specifically.   For a duplicate name I would like to tell the user
> it is not a unique last name and then tell them to enter first name and then
> return the state of that senator.

You're currently doing this:

> senateInfo = {}
> senateInfo[lastName] = state

Instead of storing just a state in the dict you could store a list of
states e.g.:

senateInfo[lastName] = [state]

Then when you find a lastName that is already in the dict you can do:

senateInfo[lastName].append(state)

to append the new state to the existing list of states. You'll need a
way to test if a particular lastName is already in the dict e.g.:

if lastName in senateInfo:


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


Re: [Tutor] need a hint

2013-12-02 Thread Wolfgang Maier
Oscar Benjamin  gmail.com> writes:

> 
> On 2 December 2013 02:25, Byron Ruffin  g.austincc.edu>
wrote:
> >
> > The following program works and does what I want except for one last problem
> > I need to handle.   The program reads a txt file of senators and their
> > associated states and when I input the last name it gives me their state.
> > The problem is "Udall".  There are two of them.  The txt file is read by
> > line and put into a dictionary with the names split.  I need a process to
> > handle duplicate names.  Preferably one that will always work even if the
> > txt file was changed/updated.  I don't want the process to handle the name
> > "Udall" specifically.   For a duplicate name I would like to tell the user
> > it is not a unique last name and then tell them to enter first name and then
> > return the state of that senator.
> 
> You're currently doing this:
> 
> > senateInfo = {}
> > senateInfo[lastName] = state
> 
> Instead of storing just a state in the dict you could store a list of
> states e.g.:
> 
> senateInfo[lastName] = [state]
> 
> Then when you find a lastName that is already in the dict you can do:
> 
> senateInfo[lastName].append(state)
> 
> to append the new state to the existing list of states. You'll need a
> way to test if a particular lastName is already in the dict e.g.:
> 
> if lastName in senateInfo:
> 
> Oscar
>

... and since you want to be able to resolve ambiguous last names based on
first names, you will have to store not just the states, but also the first
names.
You can do so by turning the entries in senateInfo from a list of strings
(states) into a list of tuples (first name, state) like this:

senateInfo[lastName] = [(firstName, state)]

or for pre-existing entries:

senateInfo[lastName].append((firstName, state))

Best,
Wolfgang


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


[Tutor] Expenses

2013-12-02 Thread Kelly Netterville
Expenses
Student Loans
SM 422
SM 151.78
Fedloan 401.48 (97.52)
UHEAA 508.44 (82.80)

Gas 700 to 1000 (depending on how often I need to go to WF)

Prescriptions
$26

Geico $97
Groceries $250 - 300 every 2 weeks ($600/mth)
Mortgage $1207


Recent
Auto Repair
$1474
$194
$700 (tires)
$600 upcoming (Transmission)

Child support


Utils $240
Jeep $380.95
ATT 50
Hannah co-pay $70 (2 or 3 times last month for 140 - 210)
Haley co-pay (not yet but will be an expense probably starting this month)


Income/mth (2455 * 2) = 4910
Expenses (est) = 4346
Left = 564
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Loop over floating point values

2013-12-02 Thread Dave Angel
On Mon, 2 Dec 2013 16:28:38 +1000, Amit Saha  
wrote:

Indeed, that's a good point. Surprisingly, C does it just fine:




# include 




int main(int argc, char **argv)
{
  float x = 0.0;
  while(x<1)
{
  x += 0.1;
  printf("%f\n", x);
}




  return 0;
}




gives the following output:




0.10
0.20
0.30
0.40
0.50
0.60
0.70
0.80
0.90
1.00


Fine The output is pretty,  but thoroughly wrong. There's an 
extra value at the end.


--
DaveA

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


Re: [Tutor] Loop over floating point values

2013-12-02 Thread Amit Saha
On Mon, Dec 2, 2013 at 10:27 PM, Dave Angel  wrote:
> On Mon, 2 Dec 2013 16:28:38 +1000, Amit Saha  wrote:
>>
>> Indeed, that's a good point. Surprisingly, C does it just fine:
>
>
>
>> # include 
>
>
>
>> int main(int argc, char **argv)
>> {
>>   float x = 0.0;
>>   while(x<1)
>> {
>>   x += 0.1;
>>   printf("%f\n", x);
>> }
>
>
>
>>   return 0;
>> }
>
>
>
>> gives the following output:
>
>
>
>> 0.10
>> 0.20
>> 0.30
>> 0.40
>> 0.50
>> 0.60
>> 0.70
>> 0.80
>> 0.90
>> 1.00
>
>
> Fine The output is pretty,  but thoroughly wrong. There's an extra value
> at the end.

You missed the fact that I am printing the value of x *after* incrementing it.



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


Re: [Tutor] need a hint

2013-12-02 Thread spir

On 12/02/2013 03:25 AM, Byron Ruffin wrote:

The following program works and does what I want except for one last
problem I need to handle.   The program reads a txt file of senators and
their associated states and when I input the last name it gives me their
state.  The problem is "Udall".  There are two of them.  The txt file is
read by line and put into a dictionary with the names split.  I need a
process to handle duplicate names.  Preferably one that will always work
even if the txt file was changed/updated.  I don't want the process to
handle the name "Udall" specifically.   For a duplicate name I would like
to tell the user it is not a unique last name and then tell them to enter
first name and then return the state of that senator.


What I would do, on data storing:
* use last name as key as long as it works (meaning no duplicate last name)
* else, try disambiguating with first name
* else, store multiple statess (if both first and last names are equal)
On data retrieval, follow the same logic.

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


[Tutor] ignoring diacritical signs

2013-12-02 Thread Albert-Jan Roskam
Hi,

I created the code below because I want to compare two fields while ignoring 
the diacritical signs. I thought it'd be cool to overload __eq__ for this. Is 
this a good approach, or have I been fixated too much on using the __eq__ 
special method? 


# -*- coding: utf-8 -*-

class Equalize(object):
    """Compare strings while ignoring diacritical signs and optionally casing"""

    def __init__(self, frms=u"é", tos=u"e", ignorecase=False):
        self.mapping = {ord(frm): ord(to) for frm, to in zip(frms, tos)}
        self.ignorecase = ignorecase

    def __call__(self, value):
        if self.ignorecase:
            value = value.lower()
        #if max(map(ord, list(value))) <= 128:
        #    return value
        return value.translate(self.mapping)

    def __eq__(self, other):
        if self == other:
            return True
        return False

if __name__ == "__main__":
    eq = Equalize(ignorecase=True)
    value_a, value_b = u"énorm", u"enorm"
    if value_a != value_b:
        print eq(value_a) == eq(value_b)


# alternative
frms, tos = u"é", u"e"
mapping = {ord(frm): ord(to) for frm, to in zip(frms, tos)}
value_a, value_b = u"énorm", u"enorm"
if value_a != value_b:
    value_a.translate(mapping) == value_b.translate(mapping)

Regards,

Albert-Jan



~~

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:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Loop over floating point values

2013-12-02 Thread Dave Angel
On Mon, 2 Dec 2013 22:57:30 +1000, Amit Saha  
wrote:
You missed the fact that I am printing the value of x *after* 

incrementing it.

You're quite right,  sorry.  I'm too accustomed to the usual c idiom, 
which would increment the value at the end of the loop.


--
DaveA

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


Re: [Tutor] Expenses

2013-12-02 Thread Tim Golden
On 02/12/2013 14:49, Alan Gauld wrote:
> Is there any point to this random set of data?
> Do you have a question for us?

I assumed it was a mis-posted email that should have gone to some
house-share group email but instead went to python-tutor. The OP's
probably lying low out of embarrassment :)

TJG

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


Re: [Tutor] Expenses

2013-12-02 Thread Alan Gauld

On 02/12/13 11:58, Kelly Netterville wrote:

Expenses
Student Loans
SM 422
SM 151.78
Fedloan 401.48 (97.52)
UHEAA 508.44 (82.80)

Gas 700 to 1000 (depending on how often I need to go to WF)

Prescriptions
$26

Geico $97
Groceries $250 - 300 every 2 weeks ($600/mth)
Mortgage $1207


Recent
Auto Repair
$1474
$194
$700 (tires)
$600 upcoming (Transmission)

Child support


Utils $240
Jeep $380.95
ATT 50
Hannah co-pay $70 (2 or 3 times last month for 140 - 210)
Haley co-pay (not yet but will be an expense probably starting this month)


Income/mth (2455 * 2) = 4910
Expenses (est) = 4346
Left = 564


Is there any point to this random set of data?
Do you have a question for us?

--
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] Loop over floating point values

2013-12-02 Thread Mark Lawrence

On 02/12/2013 12:27, Dave Angel wrote:

On Mon, 2 Dec 2013 16:28:38 +1000, Amit Saha  wrote:

Indeed, that's a good point. Surprisingly, C does it just fine:




# include 




int main(int argc, char **argv)
{
  float x = 0.0;
  while(x<1)
{
  x += 0.1;
  printf("%f\n", x);
}




  return 0;
}




gives the following output:




0.10
0.20
0.30
0.40
0.50
0.60
0.70
0.80
0.90
1.00


Fine The output is pretty,  but thoroughly wrong. There's an extra
value at the end.



Exactly what I thought at first glance but I double checked, please take 
another look :)


--
Python is the second best programming language in the world.
But the best has yet to be invented.  Christian Tismer

Mark Lawrence

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


Re: [Tutor] Expenses

2013-12-02 Thread Steven D'Aprano
On Mon, Dec 02, 2013 at 02:49:03PM +, Alan Gauld wrote:
> On 02/12/13 11:58, Kelly Netterville wrote:
> >Expenses
[...]
> Is there any point to this random set of data?
> Do you have a question for us?

No. It's a mistake, sent by accident here instead of to Kelly's college 
tutor.


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


Re: [Tutor] need a hint

2013-12-02 Thread Alan Gauld

On 02/12/13 11:03, Wolfgang Maier wrote:


... and since you want to be able to resolve ambiguous last names based on
first names, you will have to store not just the states, but also the first
names.
You can do so by turning the entries in senateInfo from a list of strings
(states) into a list of tuples (first name, state) like this:

 senateInfo[lastName] = [(firstName, state)]

or for pre-existing entries:

 senateInfo[lastName].append((firstName, state))


This results in a mixed set of values for your dictionary. Some will be 
simple strings (or tuples), others lists of tuples. You might want to 
consider standardising on a list for all even if some only have a single 
value.


This should simplify the code needed to extract the data later.

You can also use the dictionary get() method to return an empty
list if no entry exists yet so your entry code looks like

info[lastName] = info.get(lastName,[]).append((firstName, state))

And your retrieval code can use the same approach:

# get() returns a list of 0,1 or multiple tuples
for firstName,state in info.get(lastName, []):
# process the tuple

hth
--
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] /tutorial/controlflow.html "break statement"

2013-12-02 Thread Pierre-Michel Averseng

Hello,

what do you think about the results given by IDLE3 with a script studied 
recently in T. Digest Vol 117, issue 70 & seq. ?


I'm working with Linux (Debian family => i.e Linux Mint LMDE :
[please, could you excuse my poor English... ?  Thanks !  ;^))   ]

Linux hojulien 3.10-2-486 #1 Debian 3.10.5-1 (2013-08-07) i686 GNU/Linux
Python 3.3.2+ (default, Aug  4 2013, 17:23:22)
[GCC 4.8.1] on linux

The script studied was :

for n in range(2, 10):
for x in range(2, n):
if n % x == 0:
print(n, 'equals', x, '*', n//x)
break
else:
print(n, 'is a prime number')

Here is the result given in IDLE3 on my Presario CQ61:

>>> for n in range(2,10):
for x in range(2, n):
if n % x == 0:
print(n, '=',x,'*',n//x)
break
else:
# loop fell through without finding a factor
print(n, 'is a prime number')


3 is a prime number
4 = 2 * 2
5 is a prime number
5 is a prime number
5 is a prime number
6 = 2 * 3
7 is a prime number
7 is a prime number
7 is a prime number
7 is a prime number
7 is a prime number
8 = 2 * 4
9 is a prime number
9 = 3 * 3

I found this script at : 
http://docs.python.org/3/tutorial/controlflow.html#break-and-continue-statements-and-else-clauses-on-loops




4.4. break
 and
continue

Statements, and else

Clauses on Loops

The break  
statement, like in C, breaks out of the smallest enclosing for 
 or while 
 loop.


Loop statements may have an else clause; it is executed when the loop 
terminates through exhaustion of the list (with for 
) or when 
the condition becomes false (with while 
), but 
not when the loop is terminated by a break 
 
statement. This is exemplified by the following loop, which searches 
for prime numbers:


>>>
>>>  for  n  in  range(2,  10):
... for  x  in  range(2,  n):
... if  n  %  x  ==  0:
... print(n,  'equals',  x,  '*',  n//x)
... break
... else:
... # loop fell through without finding a factor
... print(n,  'is a prime number')
...
2 is a prime number
3 is a prime number
4 equals 2 * 2
5 is a

Surprising !  isn't it ?

Best regards

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


Re: [Tutor] need a hint

2013-12-02 Thread Wolfgang Maier
Alan Gauld  btinternet.com> writes:

> 
> On 02/12/13 11:03, Wolfgang Maier wrote:
> 
> > ... and since you want to be able to resolve ambiguous last names based on
> > first names, you will have to store not just the states, but also the first
> > names.
> > You can do so by turning the entries in senateInfo from a list of strings
> > (states) into a list of tuples (first name, state) like this:
> >
> >  senateInfo[lastName] = [(firstName, state)]
> >
> > or for pre-existing entries:
> >
> >  senateInfo[lastName].append((firstName, state))
> 
> This results in a mixed set of values for your dictionary. Some will be 
> simple strings (or tuples), others lists of tuples. You might want to 
> consider standardising on a list for all even if some only have a single 
> value.
> 

Hi Alan,
maybe you misread my code snippet?? It generates lists all the time just as
you are suggesting (same as for Oscar's).
Best,
Wolfgang




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


[Tutor] /tutorial/controlflow.html Apologies

2013-12-02 Thread Pierre-Michel Averseng

Hmmm,

I beg your pardon !

(Yes, this is the correct code. Look closely: the else clause belongs 
to the for 
 loop, 
*not* the if 
 statement.)


When used with a loop, the else clause has more in common with the 
else clause of a try 
 statement 
than it does that of if 
 
statements: a try 
 
statement’s else clause runs when no exception occurs, and a loop’s 
else clause runs when no break occurs. For more on the try 
 statement 
and exceptions, see /Handling Exceptions/ 
.



Yes the python.org/3/tutorial is good !

Python 3.3 is very different from Python 2 !!

Regards

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


Re: [Tutor] ignoring diacritical signs

2013-12-02 Thread Steven D'Aprano
On Mon, Dec 02, 2013 at 06:11:04AM -0800, Albert-Jan Roskam wrote:
> Hi,
> 
> I created the code below because I want to compare two fields while 
> ignoring the diacritical signs.

Why would you want to do that? That's like comparing two fields while 
ignoring the difference between "e" and "i", or "s" and "z", or "c" and 
"k". Or indeed between "s", "z", "c" and "k".

*only half joking*


I think the right way to ignore diacritics and other combining marks is 
with a function like this:

import unicodedata

def strip_marks(s):
decomposed = unicodedata.normalize('NFD', s)
base_chars = [c for c in decomposed if not unicodedata.combining(c)]
return ''.join(base_chars)


Example:

py> strip_marks("I will coöperate with Müller's résumé mañana.")
"I will cooperate with Muller's resume manana."


Beware: stripping accents may completely change the meaning of the word 
in many languages! Even in English, stripping the accents from "résumé" 
makes the word ambiguous (do you mean a CV, or the verb to start 
something again?). In other languages, stripping accents may completely 
change the word, or even turn it into nonsense.

For example, I understand that in Danish, å is not the letter a with a 
circle accent on it, but a distinct letter of the alphabet which should 
not be touched. And I haven't even considered non-Western European 
languages, like Greek, Polish, Russian, Arabic, Hebrew...

Another issue: depending on the language, it may be better to replace 
certain accents with letter combinations. For example, a German might 
prefer to see Müller transformed to Mueller. (Although Herr Müller 
probably won't, as people tend to be very sensitive about their names.)

Also, the above function leaves LATIN CAPITAL LETTER O WITH STROKE as Ø 
instead of stripping the stroke. I'm not sure whether that is an 
oversight or by design. Likewise for the lowercase version. You might 
want to do some post-processing:


def strip_marks2(s):
# Post-process letter O with stroke.
decomposed = unicodedata.normalize('NFD', s)
result = ''.join([c for c in decomposed if not unicodedata.combining(c)])
return result.replace('Ø', 'O').replace('ø', 'o')


If you have a lot of characters to post-process (e.g. ß to "ss" or "sz") 
I recommend you look into the str.translate method, which is more 
efficient than repeatedly calling replace.

No *simple* function can take into account the myriad of language- 
specific rules for accents. The best you can do is code up a limited set 
of rules for whichever languages you care about, and in the general case 
fall back on just stripping accents like an ignorant American.

(No offence intended to ignorant Americans *wink*)


> I thought it'd be cool to overload 
> __eq__ for this. Is this a good approach, or have I been fixated too 
> much on using the __eq__ special method?

This isn't Java, no need for a class :-)

On the other hand, if you start building up a set of language-specific 
normalization functions, a class might be what you want. For example:

class DefaultAccentStripper:
exceptions = {'Ø': 'O', 'ø': 'o'}
mode = 'NFD'  # Or possibly 'NFKD' for some uses?
def __call__(self, s):
decomposed = []
for c in s:
if c in self.exceptions:
decomposed.append(self.exceptions[c])
else:
decomposed.append(unicodedata.normalize(self.mode, c))
result = ''.join([c for c in decomposed if not 
  unicodedata.combining(c)])
return result

class GermanAccentStripper(DefaultAccentStripper):
exceptions = DefaultAccentStripper.exceptions.copy()
exceptions.update({'Ä': 'AE', 'ä': 'ae', 'Ë': 'EE', 'ë': 'ee',
   'Ï': 'IE', 'ï': 'ie', 'Ö': 'OE', 'ö': 'oe',
   # there seems to be a pattern here...
   'Ü': 'UE', 'ü': 'ue',
   'ß': 'sz',
   })

class DanishAccentStripper(DefaultAccentStripper):
exceptions = {'Å': 'Å', 'å': 'å'}


And there you go, three accent-strippers. Just instantiate the classes, 
once, and you're ready to go:

accent_stripper = GermanAccentStripper()



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


Re: [Tutor] ignoring diacritical signs

2013-12-02 Thread Steven D'Aprano
Oh, I forgot...

On Mon, Dec 02, 2013 at 06:11:04AM -0800, Albert-Jan Roskam wrote:
>         if self.ignorecase:
>             value = value.lower()

The right way to do case-insensitive comparisons is to use casefold, not 
lower. Unfortunately, casefold is only available in Python 3.3 and on, 
so for older versions you're stuck with lower (or maybe upper, if you 
prefer). I usually put this at the top of my module:


try:
''.casefold
except AttributeError:
def casefold(s):
return s.lower()
else:
def casefold(s):
return s.casefold()


then just use the custom casefold function.

Case-folding isn't entirely right either, it will give the wrong results 
in Turkish and Azerbaijani and one or two other languages, due to the 
presence of both dotted and dotless I, but it's as close as you're going 
to get without full locale awareness.

http://gizmodo.com/382026/a-cellphones-missing-dot-kills-two-people-puts-three-more-in-jail

By the way, that dot on the lowercase I and J, and the uppercase dotted 
I in Turkish, is called a tittle, and is technically a diacritic too. 
Next time you come across somebody bitching about how all those weird 
Unicode accents are a waste of time, you can reply "Is that rıght?"


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


Re: [Tutor] /tutorial/controlflow.html "break statement"

2013-12-02 Thread Flynn, Stephen (L & P - IT)
> The script studied was :
> 
> for n in range(2, 10):
>  for x in range(2, n):
>  if n % x == 0:
>  print(n, 'equals', x, '*', n//x)
>  break
>  else:
>  print(n, 'is a prime number')

The code above is not what you ran below, in idle. Look at the
indentation of the else: line, which completely alters the execution
flow of the code. It should be aligned with a the inner "for" and you
have it aligned with the inner "if".

> Here is the result given in IDLE3 on my Presario CQ61:
> 
>  >>> for n in range(2,10):
>  for x in range(2, n):
>  if n % x == 0:
>  print(n, '=',x,'*',n//x)
>  break
>  else:
>  # loop fell through without finding a factor
>  print(n, 'is a prime number')


Make the change and you'll get the output you were expecting.




This email and any attachment to it are confidential.  Unless you are the 
intended recipient, you may not use, copy or disclose either the message or any 
information contained in the message. If you are not the intended recipient, 
you should delete this email and notify the sender immediately.

Any views or opinions expressed in this email are those of the sender only, 
unless otherwise stated.  All copyright in any Capita material in this email is 
reserved.

All emails, incoming and outgoing, may be recorded by Capita and monitored for 
legitimate business purposes. 

Capita exclude all liability for any loss or damage arising or resulting from 
the receipt, use or transmission of this email to the fullest extent permitted 
by law.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] ignoring diacritical signs

2013-12-02 Thread Mark Lawrence

On 02/12/2013 15:53, Steven D'Aprano wrote:

On Mon, Dec 02, 2013 at 06:11:04AM -0800, Albert-Jan Roskam wrote:

Hi,

I created the code below because I want to compare two fields while
ignoring the diacritical signs.


Why would you want to do that? That's like comparing two fields while
ignoring the difference between "e" and "i", or "s" and "z", or "c" and
"k". Or indeed between "s", "z", "c" and "k".

*only half joking*


I think the right way to ignore diacritics and other combining marks is
with a function like this:

import unicodedata

def strip_marks(s):
 decomposed = unicodedata.normalize('NFD', s)
 base_chars = [c for c in decomposed if not unicodedata.combining(c)]
 return ''.join(base_chars)


Example:

py> strip_marks("I will coöperate with Müller's résumé mañana.")
"I will cooperate with Muller's resume manana."


Beware: stripping accents may completely change the meaning of the word
in many languages! Even in English, stripping the accents from "résumé"
makes the word ambiguous (do you mean a CV, or the verb to start
something again?). In other languages, stripping accents may completely
change the word, or even turn it into nonsense.

For example, I understand that in Danish, å is not the letter a with a
circle accent on it, but a distinct letter of the alphabet which should
not be touched. And I haven't even considered non-Western European
languages, like Greek, Polish, Russian, Arabic, Hebrew...


You've actually shown a perfect example above.  The Spanish letter ñ has 
become the quite distinct Spanish letter n.  And let's not go here 
http://spanish.about.com/b/2010/11/29/two-letters-dropped-from-spanish-alphabet.htm. 
 We should just stick with English as we all know that's easy, don't 
we? http://www.i18nguy.com/chaos.html :)


--
Python is the second best programming language in the world.
But the best has yet to be invented.  Christian Tismer

Mark Lawrence

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


Re: [Tutor] need a hint

2013-12-02 Thread Alan Gauld

On 02/12/13 15:18, Wolfgang Maier wrote:


You can do so by turning the entries in senateInfo from a list of strings
(states) into a list of tuples (first name, state) like this:

  senateInfo[lastName] = [(firstName, state)]

or for pre-existing entries:

  senateInfo[lastName].append((firstName, state))


This results in a mixed set of values for your dictionary. Some will be
simple strings (or tuples), others lists of tuples. You might want to



maybe you misread my code snippet?? It generates lists all the time just as
you are suggesting (same as for Oscar's).


Oops, yes, I misread, sorry.

But using get() still helps in that it removes the need to check whether 
the entry already exists. So you only need one method of

entry.

But my initial point was wrong so apologies about that.


--
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] ignoring diacritical signs

2013-12-02 Thread Albert-Jan Roskam
On Mon, 12/2/13, Steven D'Aprano  wrote:

 Subject: Re: [Tutor] ignoring diacritical signs
 To: tutor@python.org
 Date: Monday, December 2, 2013, 4:53 PM
 
 On Mon, Dec 02, 2013 at 06:11:04AM
 -0800, Albert-Jan Roskam wrote:
 > Hi,
 > 
 > I created the code below because I want to compare two
 fields while 
 > ignoring the diacritical signs.
 
 Why would you want to do that? That's like comparing two
 fields while 
 ignoring the difference between "e" and "i", or "s" and "z",
 or "c" and 
 "k". Or indeed between "s", "z", "c" and "k".
 
 *only half joking*
 
 
> ;-) Unaccented characters that really should be accented are a fact of 
life. We often need to merge datasets and if one of them comes from a system 
that dates back to the Pleistocene... well...


 I think the right way to ignore diacritics and other
 combining marks is 
 with a function like this:
 
 import unicodedata
 
 def strip_marks(s):
     decomposed = unicodedata.normalize('NFD', s)
     base_chars = [c for c in decomposed if not
 unicodedata.combining(c)]
     return ''.join(base_chars)
 
 
 Example:
 
 py> strip_marks("I will coöperate with Müller's
 résumé mañana.")
 "I will cooperate with Muller's resume manana."
 
 
> woaaah, very different approach compared to mine. Nice! I have to read up 
on unicodedata. I have used it a few times (e.g. where the re module is not 
enough), but many of the abbreviations are still a mystery to me. This seems a 
good start: http://www.unicode.org/reports/tr44/tr44-6.html


 Beware: stripping accents may completely change the meaning
 of the word 
 in many languages! Even in English, stripping the accents
 from "résumé" 
 makes the word ambiguous (do you mean a CV, or the verb to
 start 
 something again?). In other languages, stripping accents may
 completely 
 change the word, or even turn it into nonsense.
 
 For example, I understand that in Danish, å is not the
 letter a with a 
 circle accent on it, but a distinct letter of the alphabet
 which should 
 not be touched. And I haven't even considered non-Western
 European 
 languages, like Greek, Polish, Russian, Arabic, Hebrew...
 

=> Similarly, ñ is a letter in Spanish and Tagalog. So they have (at 
least?) 27 letters in their alphabet.

 Another issue: depending on the language, it may be better
 to replace 
 certain accents with letter combinations. For example, a
 German might 
 prefer to see Müller transformed to Mueller. (Although Herr
 Müller 
 probably won't, as people tend to be very sensitive about
 their names.)

=> Strangely, the nazi Goebbels is never referred to as "Göbbels".
 
 Also, the above function leaves LATIN CAPITAL LETTER O WITH
 STROKE as Ø 
 instead of stripping the stroke. I'm not sure whether that
 is an 
 oversight or by design. Likewise for the lowercase version.
 You might 
 want to do some post-processing:
 
 
 def strip_marks2(s):
     # Post-process letter O with stroke.
     decomposed = unicodedata.normalize('NFD', s)
     result = ''.join([c for c in decomposed if not
 unicodedata.combining(c)])
     return result.replace('Ø', 'O').replace('ø',
 'o')
 
 
 If you have a lot of characters to post-process (e.g. ß to
 "ss" or "sz") 
 I recommend you look into the str.translate method, which is
 more 
 efficient than repeatedly calling replace.


> Efficiency certainly counts here, with millions of records to check. It 
may even be more important than readability. Then again, accented letters are 
fairly rare in my language.

 
 No *simple* function can take into account the myriad of
 language- 
 specific rules for accents. The best you can do is code up a
 limited set 
 of rules for whichever languages you care about, and in the
 general case 
 fall back on just stripping accents like an ignorant
 American.
 
 (No offence intended to ignorant Americans *wink*)
 
 
> You are referring to this recipe, right? 
http://code.activestate.com/recipes/251871-latin1-to-ascii-the-unicode-hammer/
;-)


 > I thought it'd be cool to overload 
 > __eq__ for this. Is this a good approach, or have I
 been fixated too 
 > much on using the __eq__ special method?
 
 This isn't Java, no need for a class :-)
 
 On the other hand, if you start building up a set of
 language-specific 
 normalization functions, a class might be what you want. For
 example:
 
 class DefaultAccentStripper:
     exceptions = {'Ø': 'O', 'ø': 'o'}
     mode = 'NFD'  # Or possibly 'NFKD' for
 some uses?
     def __call__(self, s):
         decomposed = []
         for c in s:
             if c in
 self.exceptions:
                
 decomposed.append(self.exceptions[c])
             else:
                
 decomposed.append(unicodedata.normalize(self.mode, c))
         result = ''.join([c for c in
 decomposed if not 
                
          
 unicodedata.combining(c)])
         return result
 
 class GermanAccentStripper(DefaultAccentStripper):
     exceptions =
 DefaultAccentStripper.exceptions.copy()
     exceptions.update({'Ä': 'AE

Re: [Tutor] Hash map and dictionaries

2013-12-02 Thread Danny Yoo
>
> It is also said that in a list of may be 10,000 elements(specifically
> integers), hash maps would be a better option to find the occurrence of
> repetitive integers
>


There's a lot of passive voice here, so I have no idea who you mean by
this.  Attribution would be nice; otherwise, it almost sounds like you're
quoting from scripture.  :P

I'd even argue that, depending on the problem domain, it may not be the
best option.  See Jon Bentley's "Programming Pearls", chapter 1, for
example:

http://netlib.bell-labs.com/cm/cs/pearls/cto.html

where the basic lesson is that context matters.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Alternatives to append() for "growing" a list

2013-12-02 Thread Danny Yoo
>
>
> I was told by someone (as a comment) that a code snippet such as this
> "would make Pythonistas talk my ear off about how evil the append()"
> function is:
>
>

I think this thread demonstrates: we don't need an excuse to talk your ears
off.  :P

Using append() is fine.

If anything, the comment might be referring to an issue with appending
strings in a naive way.  But without further information, can't say for
sure.  If you can get more information about what your friend was talking
about, that would be helpful.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] ignoring diacritical signs

2013-12-02 Thread spir

On 12/02/2013 04:53 PM, Steven D'Aprano wrote:

Also, the above function leaves LATIN CAPITAL LETTER O WITH STROKE as Ø
instead of stripping the stroke. I'm not sure whether that is an
oversight or by design. Likewise for the lowercase version. You might
want to do some post-processing:


There's also the case that it won't turn "initial" to "ınıtıal", for some weird 
occidentalo-centric reason ;-)


(also probably won't turn ";" to "," or ":" to "." despite a middle dot above a 
base sign...)


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


[Tutor] Help with python

2013-12-02 Thread Blake
I'm writing a program to calculate totals and change for a menu, and I'm having 
a few issues.  If you could help me, it would be greatly appreciated.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Help with python

2013-12-02 Thread Mark Lawrence

On 02/12/2013 22:33, Blake wrote:

I'm writing a program to calculate totals and change for a menu, and I'm having 
a few issues.  If you could help me, it would be greatly appreciated.



A little more data would help :)  Some code, the OS and Python versions 
and the precise nature of the issues would be a good starting point.  If 
you've not already read it here's a good starting point for how to put 
your question(s) together http://sscce.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] Help with python

2013-12-02 Thread Steven D'Aprano
On Mon, Dec 02, 2013 at 04:33:27PM -0600, Blake wrote:

> I'm writing a program to calculate totals and change for a menu, and 
> I'm having a few issues.  If you could help me, it would be greatly 
> appreciated.

Would you like us to guess what issues you are having?

Let me look into my crystal ball... I see... a cat walking on your 
keyboard... Do you have a cat? Keep it off your keyboard, and your 
programs will be much better.

No no, don't thank me, it's all part of the service!

*wink*


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


Re: [Tutor] ignoring diacritical signs

2013-12-02 Thread eryksun
On Mon, Dec 2, 2013 at 3:08 PM, Albert-Jan Roskam  wrote:
>
> What is the difference between lower and casefold?
>
> casefold(...)
> S.casefold() -> str
>
> Return a version of S suitable for caseless comparisons.
>
 "Alala alala".casefold() == "Alala alala".lower()
> True

In 3.3, Unicode case conversion is extended to handle mapping to
multiple characters and case folding:

>>> u'ß'.lower()
'ß'

>>> u'ß'.casefold()
'ss'

http://docs.python.org/3/library/stdtypes.html#str.casefold

In 3.x, bytes and bytearray case conversions use lookup tables, for
ASCII only. This also applies to the bytearray type in 2.6/2.7. On the
other hand, 2.x str case conversions are locale aware:

Default C/POSIX locale:

>>> print '\xc4'.decode('latin-1')
Ä

>>> print '\xc4'.lower().decode('latin-1')
Ä

German/Germany locale with Latin-1 codeset:

>>> locale.setlocale(locale.LC_ALL, 'de_DE.iso-8859-1')
'de_DE.iso-8859-1'

>>> print '\xc4'.lower().decode('latin-1')
ä
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor