[Tutor] Occurrence of number 2 in a range from 1 to 100

2013-12-01 Thread Reuben
Hi,

How can we write a logic for detecting the number 2 in  range from 1 to 100

Regards,
Reuben
___
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-01 Thread Amit Saha
On Sun, Dec 1, 2013 at 5:04 PM, Steven D'Aprano st...@pearwood.info wrote:
 On Sun, Dec 01, 2013 at 02:32:38PM +1000, Amit Saha wrote:
 Hello,

 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:

 There is absolutely nothing wrong with append. Either you have
 misunderstood, or the person who told you this was smoking crack.

heh, no I literally quote the person above, so I think I understood
him alright.


  mylist = []
  mylist.append(1)
 # a number of times over

 However, growing a list one item at a time using append like this is too
 much hard work. Some better solutions:

 # You have an existing list, and want to append a bunch of things to it
 mylist.extend([x, y+1, z*2])

 # You want a list consisting of the same objects repeated many times
 mylist = [0, 1, 2]*100  # like [0, 1, 2, 0, 1, 2, 0, 1, 2, ...]

 # You want to create a list containing known objects
 mylist = [1, 2, 4, 8, 16, 32, 64]

 # Like above, but using a list comprehension
 mylist = [2**n for n in range(7)]

 # You don't know how many things you want to add.
 mylist = []
 x = 1
 while x  100:
 mylist.append(x)
 x = 3*x-1

 and so on. As you can see, append has its job to do.



The last case is the closest to the context in which I used the above
code construct.



 I have some ideas that on an append() the list's internal size
 increases (doubled?) since CPython over-allocates memory, and such.

 Not just on append. Any operation that adds or deletes items from a list
 might trigger a re-size. If the list needs to increase, it will double
 in size up to some maximum, then it will grow by a smaller amount. The
 purpose of this is that *on average* appending to the list will take a
 fixed amount of time.


 So, the question is: what is the alternative to growing a list when I
 have no idea what items or how many may be there?

 Don't worry about growing the list. That's all handled for you as part
 of the list interface. The whole point of using Python is to not have to
 worry about internal details like that.


Right, that's what I thought. Good that I checked here, now I can
write a nice reply to the comment :-)

Thanks Steven and Dave.

Best,
Amit.


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


Re: [Tutor] Occurrence of number 2 in a range from 1 to 100

2013-12-01 Thread Amit Saha
Hello,

On Sun, Dec 1, 2013 at 3:50 PM, Reuben reuben.dl...@gmail.com wrote:
 Hi,

 How can we write a logic for detecting the number 2 in  range from 1 to 100

You question is unclear. Could you please give more details ?

Best,
Amit.


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


[Tutor] Loop over floating point values

2013-12-01 Thread Amit Saha
Hello,

Much to my disbelief, I realized I hadn't written a program in Python
as far as I can recall which required me to do something like this, in
psuedocode:

x = 0.1

for i = 0 to x step 0.01
# do something with i
end i

Simply stated, I want to start from say a value, 0 and go upto 0.1 in
increments of 0.01.  I don't want to create a list with the values
hard-coded and then iterate over it, and hence I would use a while
loop instead:

x = 0.1
while i  x:
   # do something with i
   i += 0.01

I think this is one case, where you definitely cannot do this with a
for loop assuming the following restrictions:

- Do not create a list of the floating point values as i=[0.01, 0.02,
0.03..] - either like that or by using a suitable mathematical formula
combined with a list comprehension
- Use numpy's linspace() to create the list for you


Thoughts?

Thanks,
Amit.

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


Re: [Tutor] Occurrence of number 2 in a range from 1 to 100

2013-12-01 Thread Steven D'Aprano
On Sun, Dec 01, 2013 at 11:20:02AM +0530, Reuben wrote:
 Hi,
 
 How can we write a logic for detecting the number 2 in  range from 1 to 100

2 in range(1, 101)


-- 
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-01 Thread Dominik George
Hi,

 - Do not create a list of the floating point values as i=[0.01, 0.02,
 0.03..] - either like that or by using a suitable mathematical formula
 combined with a list comprehension

You could simply write your own version of xrange that does it, as a
generator:

  def xrange_f(start, stop, step):
  x = start
  while x  stop:
  yield x
  x += step

Then, in your code, you can do:

  for f in xrange_f(0, 10, 0.01):
  pass

-nik

-- 
* concerning Mozilla code leaking assertion failures to tty without D-BUS *
mirabilos That means, D-BUS is a tool that makes software look better
than it actually is.

PGP-Fingerprint: 3C9D 54A4 7575 C026 FB17  FD26 B79A 3C16 A0C4 F296


signature.asc
Description: Digital signature
___
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-01 Thread Steven D'Aprano
On Sun, Dec 01, 2013 at 07:03:15PM +1000, Amit Saha wrote:
 Hello,
 
 Much to my disbelief, I realized I hadn't written a program in Python
 as far as I can recall which required me to do something like this, in
 psuedocode:
 
 x = 0.1
 
 for i = 0 to x step 0.01
 # do something with i
 end i


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.

One way to fix this is to iterate over integers, and then divide just 
before doing the work:

for x in range(0, 10):
print x/10.0


Another way is to use the recipes I have here:

http://code.activestate.com/recipes/577878-generate-equally-spaced-floats/

http://code.activestate.com/recipes/577881-equally-spaced-floats-part-2/

http://code.activestate.com/recipes/577068-floating-point-range/

I encourage you to read all three. If you have any 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] Occurrence of number 2 in a range from 1 to 100

2013-12-01 Thread Steven D'Aprano
On Sun, Dec 01, 2013 at 02:57:33PM +0530, Reuben wrote:
 I mean occurrence of 2 from numbers 1 to 100.  The number could be the
 first digit or second digit in a two digit number..for e.g. In number 21 it
 appears as first digit. For number 92 it appears as second digit

The most efficient way is to use a bit of reasoning:

2, 12, 20 through 29, then 32, 42, 52 etc.

But if you have to do it computationally:

for i in range(1, 101):
print 2 in str(i)



-- 
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-01 Thread Mark Lawrence

On 01/12/2013 09:14, Dominik George wrote:

Hi,


- Do not create a list of the floating point values as i=[0.01, 0.02,
0.03..] - either like that or by using a suitable mathematical formula
combined with a list comprehension


You could simply write your own version of xrange that does it, as a
generator:

   def xrange_f(start, stop, step):
   x = start
   while x  stop:
   yield x
   x += step

Then, in your code, you can do:

   for f in xrange_f(0, 10, 0.01):
   pass

-nik



To encourage Python 3 take up this should be range rather than xrange :)

--
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] Occurrence of number 2 in a range from 1 to 100

2013-12-01 Thread Mark Lawrence

On 01/12/2013 05:50, Reuben wrote:

Hi,

How can we write a logic for detecting the number 2 in  range from 1 to 100

Regards,
Reuben



Paper and pen or pencil should be perfectly adequate for this task. 
Alternatively, open an editor, type some code, run it, if you have 
problems ask another question here, preferably one that makes sense :)


Unless of course your question above is to be taken literally, in which 
case Mr. K'Aprano has already answered.


--
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] Occurrence of number 2 in a range from 1 to 100

2013-12-01 Thread Steven D'Aprano
On Sun, Dec 01, 2013 at 08:43:46AM -0500, bruce wrote:
 hmm...
 
 two questions. (new to cmdline py)
 
 tried typing in what was typed in above in the python shell:
 
 for i in range(1, 101):
 print 2 in str(i)
 
 this did nothing..

Curious. Which Python shell did you use?

I would expect that you get a prompt  (without the quotes). I've 
changed the prompt in my Python to py, but by default you should have 
. Then, when you hit return at the end of the first line, you 
should get the second level prompt,  You'll need to add at least 
one space, or tab, to indent the second line. Then when you hit enter 
again you'll get a ... prompt, Enter one last time and the code will 
run. Here's what I get (changing 101 to a smaller number for brevity:


py for i in range(1, 11):
... 2 in str(i)
...
False
True
False
False
False
False
False
False
False
False



However, I may have inadvertently been misleading. Outside of the 
interactive shell, even though that code will run, it won't display any 
output. Only in the interactive shell does that print True and False as 
above.

Outside of the interactive shell, you need to use the print statement or 
function to see the output, otherwise Python calculates the answer and 
then doesn't do anything with it. So it may be better to write this as:

for i in range(1, 101):
print (2 in str(i))


which will work anywhere.



 def aa():
   for i in range(1, 101):
 print 2 in str(i)
 
 aa()
 
 error::
  aa()
 Traceback (most recent call last):
   File stdin, line 1, in module
 NameError: name 'aa' is not defined

That is remarkable. I cannot explain this error. Are you using IDLE or 
some other shell?



 the other question, what does the in function within py do?? I've
 used str.find() to look if a substring is present, but didn't know a
 in even exists..!

The in operator tests whether one object includes another object. For 
example, with strings it tests substrings:


hat in what
= returns True

hat in h-a-t
= returns False

With lists and tuples, it tests to see if an item is the given value:

23 in [1, 5, 23, 99]
= returns True

dog in [cat, dog, mouse]
= returns True

dog in [cats, dogs, mice]
= return False


But it only looks one level deep!

23 in [1, 2, 3, [22, 23, 24], 5, 6]
= returns False

 
With dictionaries, it checks to see if the given object is a key:

5 in {2: two, 5: five, 7: seven}  # {key: value}
= returns True

but not a value:

five in {2: two, 5: five, 7: seven}
= returns False


-- 
Steven
___
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-01 Thread eryksun
On Sun, Dec 1, 2013 at 2:04 AM, Steven D'Aprano st...@pearwood.info wrote:
 might trigger a re-size. If the list needs to increase, it will double
 in size up to some maximum, then it will grow by a smaller amount. The
 purpose of this is that *on average* appending to the list will take a
 fixed amount of time.

Here's the over-allocation rule:

if newsize  0:
const = 3 if newsize  9 else 6
newsize += newsize // 8 + const

Starting from empty and appending:

0, 4,  8, 16, 25, 35, 46, 58, 72, 88

CPython's list uses realloc, which tries to resize without copying.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Occurrence of number 2 in a range from 1 to 100

2013-12-01 Thread eryksun
On Sun, Dec 1, 2013 at 6:14 AM, Steven D'Aprano st...@pearwood.info wrote:
 On Sun, Dec 01, 2013 at 02:57:33PM +0530, Reuben wrote:
 I mean occurrence of 2 from numbers 1 to 100.  The number could be the
 first digit or second digit in a two digit number..for e.g. In number 21 it
 appears as first digit. For number 92 it appears as second digit

 The most efficient way is to use a bit of reasoning:

 2, 12, 20 through 29, then 32, 42, 52 etc.

 [n for n in range(100) if n % 10 == 2 or n // 10 == 2]
[2, 12, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29,
 32, 42, 52, 62, 72, 82, 92]

Floor division (//) and modulo (%) are explained here:

http://docs.python.org/2/reference/expressions.html#binary-arithmetic-operations
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Occurrence of number 2 in a range from 1 to 100

2013-12-01 Thread Mark Lawrence

On 01/12/2013 17:40, eryksun wrote:

On Sun, Dec 1, 2013 at 6:14 AM, Steven D'Aprano st...@pearwood.info wrote:

On Sun, Dec 01, 2013 at 02:57:33PM +0530, Reuben wrote:

I mean occurrence of 2 from numbers 1 to 100.  The number could be the
first digit or second digit in a two digit number..for e.g. In number 21 it
appears as first digit. For number 92 it appears as second digit


The most efficient way is to use a bit of reasoning:

2, 12, 20 through 29, then 32, 42, 52 etc.


  [n for n in range(100) if n % 10 == 2 or n // 10 == 2]
 [2, 12, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29,
  32, 42, 52, 62, 72, 82, 92]

Floor division (//) and modulo (%) are explained here:

http://docs.python.org/2/reference/expressions.html#binary-arithmetic-operations



I wish people would use Python 3 references.  I believe it would lead to 
a greater take up of, IMHO, a superior product than Python 2.


--
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] Occurrence of number 2 in a range from 1 to 100

2013-12-01 Thread Joel Goldstick
On Sun, Dec 1, 2013 at 12:53 PM, Mark Lawrence breamore...@yahoo.co.ukwrote:

 On 01/12/2013 17:40, eryksun wrote:

 On Sun, Dec 1, 2013 at 6:14 AM, Steven D'Aprano st...@pearwood.info
 wrote:

 On Sun, Dec 01, 2013 at 02:57:33PM +0530, Reuben wrote:

 I mean occurrence of 2 from numbers 1 to 100.  The number could be the
 first digit or second digit in a two digit number..for e.g. In number
 21 it
 appears as first digit. For number 92 it appears as second digit



This way may not be faster, but it may be simpler to understand:

 for n in range(100):
...   if '2' in str(n):
... print n
...



 ___
 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] Occurrence of number 2 in a range from 1 to 100

2013-12-01 Thread Mark Lawrence

On 01/12/2013 17:59, Joel Goldstick wrote:

On Sun, Dec 1, 2013 at 12:53 PM, Mark Lawrence breamore...@yahoo.co.uk
mailto:breamore...@yahoo.co.uk wrote:

On 01/12/2013 17:40, eryksun wrote:

On Sun, Dec 1, 2013 at 6:14 AM, Steven D'Aprano
st...@pearwood.info mailto:st...@pearwood.info wrote:

On Sun, Dec 01, 2013 at 02:57:33PM +0530, Reuben wrote:

I mean occurrence of 2 from numbers 1 to 100.  The
number could be the
first digit or second digit in a two digit number..for
e.g. In number 21 it
appears as first digit. For number 92 it appears as
second digit
This way may not be faster, but it may be simpler to understand:

  for n in range(100):
...   if '2' in str(n):
... print n
...



Why do you appear to be replying to me but haven't quoted anything that 
I've said?  It's also difficult to see who said what above as the normal 
attribution marker levels are missing.  Time to boot google products 
into touch?


As for code speed who cares?  Good programmers jump that fence when they 
have to, not because they can.


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


[Tutor] truncated dictionary return

2013-12-01 Thread richard kappler
I have a script that reads sensor values gathered by an Arduino board from
serial as a dictionary, said values to later be used in the AI for Nav 
Control. Here's the script:

#!/usr/bin/python

def sensorRead():
import serial
from time import sleep

sensors = {}
sensors = dict.fromkeys('Sonar1 Sonar2 Sonar3 Sonar4 Dewpoint
Temperature Humidity Light'.split())

arduino = serial.Serial('/dev/ttyACM0', 9600)
sleep(1)
line = arduino.readline().strip()
line = line.lstrip('{').rstrip('}').strip()

d = {}
for item in line.split(','):
item = item.strip()
key, value = item.split(':')
key = key.strip()
value = value.strip()
d[key]=int(value)
return d

I hope that comes through okay, I copied it from the text file so
indentation and such should be fine, if not let me know.

The script works great with one exception. I understand the problem, I'm
just not sure how to address it. The problem is:

The Arduino runs on a constant loop, it reads each sensor, sends the key
and the value to the serial bus in format for python to read it as a
dictionary, lather, rinse, repeat.

Python querries the bus when told. Usually the python script gets the full
dictionary (all 8 values with keys, brackets etc) but sometimes it doesn't.
Sometimes it only gets the last few values, sometimes it gets nothing or
misses a bracket and throws an error. This makes sense. They are not in
sync.

What I need to figure out how to do is have the python script wait until
the next round of values as signified by the opening bracket { or check
that it has all 8 values and if not retry or something.

Would this be an if/else? try? exception?

I've not yet delved into any of these in my quest to learn python except
if/else and that doesn't feel right for this, so I'm at a loss as to how to
proceed.

regards, Richard

-- 

*Mater tua criceta fuit, et pater tuo redoluit bacarum sambucus*
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] truncated dictionary return

2013-12-01 Thread Wolfgang Maier
richard kappler richkappler at gmail.com writes:

 
 I have a script that reads sensor values gathered by an Arduino board from
serial as a dictionary, said values to later be used in the AI for Nav 
Control. Here's the script:
 #!/usr/bin/python
 
 
 def sensorRead():
     import serial
     from time import sleep
 
     sensors = {}
     sensors = dict.fromkeys('Sonar1 Sonar2 Sonar3 Sonar4 Dewpoint
Temperature Humidity Light'.split())
 
     arduino = serial.Serial('/dev/ttyACM0', 9600)
     sleep(1)
     line = arduino.readline().strip()
     line = line.lstrip('{').rstrip('}').strip()
 
     d = {}
     for item in line.split(','):
         item = item.strip()
         key, value = item.split(':')
         key = key.strip()
 
         value = value.strip()
         d[key]=int(value)
     return d
 
 The script works great with one exception. I understand the problem, I'm
just not sure how to address it. The problem is:
 
 The Arduino runs on a constant loop, it reads each sensor, sends the key
and the value to the serial bus in format for python to read it as a
dictionary, lather, rinse, repeat.
 
 Python querries the bus when told. Usually the python script gets the full
dictionary (all 8 values with keys, brackets etc) but sometimes it doesn't.
Sometimes it only gets the last few values, sometimes it gets nothing or
misses a bracket and throws an error. This makes sense. They are not in sync.
 
 What I need to figure out how to do is have the python script wait until
the next round of values as signified by the opening bracket { or check
that it has all 8 values and if not retry or something.
 
There should be no sync issue here. The readline method should read from the
serial port until it reaches an EOL character, then return the whole line
(i.e., your sleep(1) should be removed since readline() already waits for
input).
From what you're describing, the real issue seems to be on the side of the
sender. Are you sure, it terminates each line with \n as it should? Where is
that code coming from?
Best,
Wolfgang

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


Re: [Tutor] truncated dictionary return

2013-12-01 Thread Wolfgang Maier
Hi again,
think I spotted the problem now:
you’re setting up your connection everytime you enter the function (with the
serial.Serial call), but I guess you’re calling that function repeatedly to
retrieve lines. That’s wrong and means you could loose data that was sent
while you weren’t listening.
You’ll have to open the connection once outside the sensorRead() function,
then pass it the arduino object like this:

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

# your main program:
arduino = serial.Serial('/dev/ttyACM0', 9600)
sleep(1)
while True:
reads = sensorRead(arduino)
# do something with the data

Hope that helps,
Wolfgang


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


Re: [Tutor] truncated dictionary return

2013-12-01 Thread Paul Simon
Wolfgang Maier wolfgang.ma...@biologie.uni-freiburg.de wrote in message 
news:loom.20131201t230651-...@post.gmane.org...
 richard kappler richkappler at gmail.com writes:


 I have a script that reads sensor values gathered by an Arduino board 
 from
 serial as a dictionary, said values to later be used in the AI for Nav 
 Control. Here's the script:
 #!/usr/bin/python


 def sensorRead():
 import serial
 from time import sleep

 sensors = {}
 sensors = dict.fromkeys('Sonar1 Sonar2 Sonar3 Sonar4 Dewpoint
 Temperature Humidity Light'.split())

 arduino = serial.Serial('/dev/ttyACM0', 9600)
 sleep(1)
 line = arduino.readline().strip()
 line = line.lstrip('{').rstrip('}').strip()

 d = {}
 for item in line.split(','):
 item = item.strip()
 key, value = item.split(':')
 key = key.strip()

 value = value.strip()
 d[key]=int(value)
 return d

 The script works great with one exception. I understand the problem, I'm
 just not sure how to address it. The problem is:

 The Arduino runs on a constant loop, it reads each sensor, sends the key
 and the value to the serial bus in format for python to read it as a
 dictionary, lather, rinse, repeat.

 Python querries the bus when told. Usually the python script gets the 
 full
 dictionary (all 8 values with keys, brackets etc) but sometimes it 
 doesn't.
 Sometimes it only gets the last few values, sometimes it gets nothing or
 misses a bracket and throws an error. This makes sense. They are not in 
 sync.

 What I need to figure out how to do is have the python script wait until
 the next round of values as signified by the opening bracket { or check
 that it has all 8 values and if not retry or something.

 There should be no sync issue here. The readline method should read from 
 the
 serial port until it reaches an EOL character, then return the whole line
 (i.e., your sleep(1) should be removed since readline() already waits for
 input).
 From what you're describing, the real issue seems to be on the side of the
 sender. Are you sure, it terminates each line with \n as it should? Where 
 is
 that code coming from?
 Best,
 Wolfgang

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

I also suspect sleep doesn't work.  Two better options would be:
1. read/loop until line terminator,
2. Use serial signals, i.e., RTS/DTS if possible.

Paul  Simon 



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


Re: [Tutor] Occurrence of number 2 in a range from 1 to 100

2013-12-01 Thread spir

On 12/01/2013 06:50 AM, Reuben wrote:

Hi,

How can we write a logic for detecting the number 2 in  range from 1 to 100


Do you mean:
if 2 in numbers:
?

Also for a more general solution, think at the very nice function any(bools), in 
combination with a generator comprehension:


numbers = [2,3,4,5,6,8]
if any((n%2 == 1) for n in numbers):
print(some is odd)
___
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-01 Thread spir

On 12/01/2013 05:32 AM, Amit Saha wrote:

Hello,

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:


mylist = []
mylist.append(1)

# a number of times over

I have some ideas that on an append() the list's internal size
increases (doubled?) since CPython over-allocates memory, and such.

So, the question is: what is the alternative to growing a list when I
have no idea what items or how many may be there?


Maybe you are confusing with catenating _strings_, rather than lists. Python's 
concat is problematic because it is a binary operation. So, catenating n bits 
makes n-1 operations, each with intermediate results, of growing sizes, all 
thrown away except for the last one, the actual result. If all of the bitN are 
strings:

bit1 + bit2 + bit3 + bit4 + bit5
actually constructs:
bit1+bit2
bit1+bit2+bit3
bit1+bit2+bit3+bit4
bit1+bit2+bit3+bit4+bit5
A number of unneeded string object, and a very big useless memory weight.

Example Python code showing good/bad usage below (advanced pythonistas, please 
correct if needed, I don't know the latest nice Python idioms):




# === case of a series of explicite text sections 

# don't do this:
text = 

intro = intro...
text += intro

body = body...
text+= '\n' + body

concl = concl...
text += '\n' + concl

print(text) ; print()

# also do not do:
text = intro + '\n' + body + '\n' + concl
print(text) ; print()

# do that...:
intro = intro...
body  = body...
concl = concl...
text = '\n'.join([intro, body, concl]) # but creates a list
print(text) ; print()

# ...or that:
text = %s\n%s\n%s % (intro, body, concl) # no such list
print(text) ; print()

# === case of a list of sections of arbitrary size 

# (simulation code for demo)
def make_section (n): return %s\n % n
section_data = [13, 5, 79, 4, 268, 0, 987654321]

# don't do this:
text   = 
for dat in section_data:
section = make_section(dat)
text += section
print(text)

# do that...:
sections = []
for dat in section_data:
section = make_section(dat)
sections.append(section)
text = ''.join(sections)
print(text)

# ... or that:
sections = (make_section(dat) for dat in section_data)
text = ''.join(sections)
print(text)

# ... or even that:
text = ''.join(make_section(dat) for dat in section_data) # no need for ((...))
print(text)
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Occurrence of number 2 in a range from 1 to 100

2013-12-01 Thread Reuben
I tried it with the python interpreter as mentioned below:

test@test-Inspiron-1564:~/learn$ python
Python 2.7.4 (default, Apr 19 2013, 18:28:01)
[GCC 4.7.3] on linux2
Type help, copyright, credits or license for more information.






On Sun, Dec 1, 2013 at 7:50 PM, Steven D'Aprano st...@pearwood.info wrote:

 On Sun, Dec 01, 2013 at 08:43:46AM -0500, bruce wrote:
  hmm...
 
  two questions. (new to cmdline py)
 
  tried typing in what was typed in above in the python shell:
 
  for i in range(1, 101):
  print 2 in str(i)
 
  this did nothing..

 Curious. Which Python shell did you use?

 I would expect that you get a prompt  (without the quotes). I've
 changed the prompt in my Python to py, but by default you should have
 . Then, when you hit return at the end of the first line, you
 should get the second level prompt,  You'll need to add at least
 one space, or tab, to indent the second line. Then when you hit enter
 again you'll get a ... prompt, Enter one last time and the code will
 run. Here's what I get (changing 101 to a smaller number for brevity:


 py for i in range(1, 11):
 ... 2 in str(i)
 ...
 False
 True
 False
 False
 False
 False
 False
 False
 False
 False



 However, I may have inadvertently been misleading. Outside of the
 interactive shell, even though that code will run, it won't display any
 output. Only in the interactive shell does that print True and False as
 above.

 Outside of the interactive shell, you need to use the print statement or
 function to see the output, otherwise Python calculates the answer and
 then doesn't do anything with it. So it may be better to write this as:

 for i in range(1, 101):
 print (2 in str(i))


 which will work anywhere.



  def aa():
for i in range(1, 101):
  print 2 in str(i)
 
  aa()
 
  error::
   aa()
  Traceback (most recent call last):
File stdin, line 1, in module
  NameError: name 'aa' is not defined

 That is remarkable. I cannot explain this error. Are you using IDLE or
 some other shell?



  the other question, what does the in function within py do?? I've
  used str.find() to look if a substring is present, but didn't know a
  in even exists..!

 The in operator tests whether one object includes another object. For
 example, with strings it tests substrings:


 hat in what
 = returns True

 hat in h-a-t
 = returns False

 With lists and tuples, it tests to see if an item is the given value:

 23 in [1, 5, 23, 99]
 = returns True

 dog in [cat, dog, mouse]
 = returns True

 dog in [cats, dogs, mice]
 = return False


 But it only looks one level deep!

 23 in [1, 2, 3, [22, 23, 24], 5, 6]
 = returns False


 With dictionaries, it checks to see if the given object is a key:

 5 in {2: two, 5: five, 7: seven}  # {key: value}
 = returns True

 but not a value:

 five in {2: two, 5: five, 7: seven}
 = returns False


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

2013-12-01 Thread spir

On 12/01/2013 10:03 AM, Amit Saha wrote:

Hello,

Much to my disbelief, I realized I hadn't written a program in Python
as far as I can recall which required me to do something like this, in
psuedocode:

x = 0.1

for i = 0 to x step 0.01
# do something with i
end i

Simply stated, I want to start from say a value, 0 and go upto 0.1 in
increments of 0.01.  I don't want to create a list with the values
hard-coded and then iterate over it, and hence I would use a while
loop instead:

x = 0.1
while i  x:
# do something with i
i += 0.01

I think this is one case, where you definitely cannot do this with a
for loop assuming the following restrictions:

- Do not create a list of the floating point values as i=[0.01, 0.02,
0.03..] - either like that or by using a suitable mathematical formula
combined with a list comprehension
- Use numpy's linspace() to create the list for you


Thoughts?


There is a general solution for this (a typical school problem ;-), maybe the 
reason why we rarely meet it in practice!). However, watch the issues with 
binary floats mentionned by Steven.


# loop from x0 to x1 with step dx, total n passes
x0, x1, dx, n = -0.3, 0.8, 0.2, 6
for i in range(n):
x = x0 + dx * i
print(x)
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] Hash map and dictionaries

2013-12-01 Thread Reuben
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.


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?





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


Re: [Tutor] Occurrence of number 2 in a range from 1 to 100

2013-12-01 Thread Reuben
I mean occurrence of 2 from numbers 1 to 100.  The number could be the
first digit or second digit in a two digit number..for e.g. In number 21 it
appears as first digit. For number 92 it appears as second digit
On 01-Dec-2013 2:45 PM, Steven D'Aprano st...@pearwood.info wrote:

 On Sun, Dec 01, 2013 at 11:20:02AM +0530, Reuben wrote:
  Hi,
 
  How can we write a logic for detecting the number 2 in  range from 1 to
 100

 2 in range(1, 101)


 --
 Steven
 ___
 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] Occurrence of number 2 in a range from 1 to 100

2013-12-01 Thread Reuben
Thanks everyone for all the replies.


On Sun, Dec 1, 2013 at 11:29 PM, Joel Goldstick joel.goldst...@gmail.comwrote:




 On Sun, Dec 1, 2013 at 12:53 PM, Mark Lawrence breamore...@yahoo.co.ukwrote:

 On 01/12/2013 17:40, eryksun wrote:

 On Sun, Dec 1, 2013 at 6:14 AM, Steven D'Aprano st...@pearwood.info
 wrote:

 On Sun, Dec 01, 2013 at 02:57:33PM +0530, Reuben wrote:

 I mean occurrence of 2 from numbers 1 to 100.  The number could be the
 first digit or second digit in a two digit number..for e.g. In number
 21 it
 appears as first digit. For number 92 it appears as second digit



 This way may not be faster, but it may be simpler to understand:

  for n in range(100):
 ...   if '2' in str(n):
 ... print n
 ...



 ___
 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


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


[Tutor] Fwd: empty delimiters, and None

2013-12-01 Thread ugajin

 The answer is , yes (to both questions)
locale -a does report availability of en_US (and en_US.UTF), C is supported, 
but C.UTF-8 does not appear in the list.
I have tried inserting export LANG=en_GB.UTF.8 as a new line 127.

Thanks.


-A


-Original Message-
From: eryksun eryk...@gmail.com
To: uga...@talktalk.net
CC: Tutor@python.org
Sent: Sat, 30 Nov 2013 23:56
Subject: Re: empty delimiters, and None


On Sat, Nov 30, 2013 at 7:04 AM,  uga...@talktalk.net wrote:
 believe the system locale is set correctly:

 Apples-iMac-4:~ apple$ locale
 LANG=en_GB.UTF-8

Does `locale -a` report that en_US is available?

 127
6) Insert a new line before line 127 with this content:
 export LANG=en_US.UTF-8

Did you try en_GB.UTF-8 here?

 Lines 123 to 127 of the launcher script read:

 # NOTE: Have to add .UTF-8 to the LANG since omitting causes Inkscape
 #   to crash on startup in locale_from_utf8().
 export LANG=`grep \\`echo $LANGSTR\`_\ /usr/share/locale/locale.alias | \
 tail -n1 | sed 's/\./ /' | awk '{print $2}'`.UTF-8
 echo Setting Language: $LANG 12

The current version uses the value of AppleCollationOrder or
AppleLocale (e.g. defaults read .GlobalPreferences AppleLocale) to
find the locale in the locale.alias file, and defaults to
en_US.UTF-8. I don't know if en_US is always available in OS X,
but surely C.UTF-8 would be. I don't know why it can't modify the
existing LANG to use the UTF-8 codeset. Finally, I can't speak for OS
X, but the glibc locale.alias on Linux is obsolete and doesn't have an
alias for English.

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


Re: [Tutor] empty delimiters, and None

2013-12-01 Thread ugajin

 Well, yes.
I find can indeed use;locale.setlocale(locale.LC_ALL) thanks!
In addition to locale.setlocale(locale.LC_ALL, None)
I found I can also use; locale.setlocale(locale.LC_ALL, 'en_GB')
The question remains, why does; locale.setlocale(locale.LC_ALL, '') fail, 
especially if it is good practice?

 
-A


 

-Original Message-
From: spir denis.s...@gmail.com
To: tutor@python.org
Sent: Sun, 1 Dec 2013 0:56
Subject: Re: [Tutor] empty delimiters, and None


On 11/29/2013 02:19 PM, uga...@talktalk.net wrote: 
 I have also looked at locale.py Line 494 of which is the last line of a def 
 (def function?) I include this below, hopefully this may save you searching 
 for locale.py (Pyhon 2.6) should you need it and wish to answer the above 
 questions, it may help. 
 
 def setlocale(category, locale=None): 
 
   Set the locale for the given category.  The locale can be 
  a string, a locale tuple (language code, encoding), or None. 
 
  Locale tuples are converted to strings the locale aliasing 
  engine.  Locale strings are passed directly to the C lib. 
 
  category may be given as one of the LC_* values. 
 
   
  if locale and type(locale) is not type(): 
  # convert to string 
  locale = normalize(_build_localename(locale)) 
  return _setlocale(category, locale) 
 
As a side-note, in addition to what other have said, the headline of the 
function def 
 
def setlocale(category, locale=None) 
 
says that None is the default (standard) value for the parameter 'locale'. This 
means that, if ever you provide no value for it when calling setlocale, then 
the value None is used in standard. So, you could as well call it like: 
 
locale.setlocale(locale.LC_ALL) # no value at all for param 'locale' 
 
instead of you correction 
 
locale.setlocale(locale.LC_ALL, None) 
 
for the initial version 
 
locale.setlocale(locale.LC_ALL, '') 
 
This is actually good coding practice (in all language which have default 
values). 
 
Denis 
___ 
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] truncated dictionary return

2013-12-01 Thread spir

On 12/01/2013 08:28 PM, richard kappler wrote:

I have a script that reads sensor values gathered by an Arduino board from
serial as a dictionary, said values to later be used in the AI for Nav 
Control. Here's the script:

#!/usr/bin/python

def sensorRead():
 import serial
 from time import sleep

 sensors = {}
 sensors = dict.fromkeys('Sonar1 Sonar2 Sonar3 Sonar4 Dewpoint
Temperature Humidity Light'.split())

 arduino = serial.Serial('/dev/ttyACM0', 9600)
 sleep(1)
 line = arduino.readline().strip()
 line = line.lstrip('{').rstrip('}').strip()

 d = {}
 for item in line.split(','):
 item = item.strip()
 key, value = item.split(':')
 key = key.strip()
 value = value.strip()
 d[key]=int(value)
 return d

I hope that comes through okay, I copied it from the text file so
indentation and such should be fine, if not let me know.

The script works great with one exception. I understand the problem, I'm
just not sure how to address it. The problem is:

The Arduino runs on a constant loop, it reads each sensor, sends the key
and the value to the serial bus in format for python to read it as a
dictionary, lather, rinse, repeat.

Python querries the bus when told. Usually the python script gets the full
dictionary (all 8 values with keys, brackets etc) but sometimes it doesn't.
Sometimes it only gets the last few values, sometimes it gets nothing or
misses a bracket and throws an error. This makes sense. They are not in
sync.

What I need to figure out how to do is have the python script wait until
the next round of values as signified by the opening bracket { or check
that it has all 8 values and if not retry or something.

Would this be an if/else? try? exception?

I've not yet delved into any of these in my quest to learn python except
if/else and that doesn't feel right for this, so I'm at a loss as to how to
proceed.


* What is the point of the 'sensors' dict? (also, you don't need to initialise 
it as an enmpty dict)
* If you know about regexps or another matching utility, use that to decode the 
input line into (key,value) pairs. This is even easier if input has a strict 
format. Would tell us?
* About wrong input (incomplete data), avoid try/except, except if ever most 
cases are ok (it is very costly in case of exception). Anyway, you need to 
decode input, so use that to check for errors/missing stuff.


If you used a matching tool, its absence of result would directly tell about 
wrong input (provided your pattern is correct! ;-) As of now, just place checks 
in your decoding sequence. Possible checks places, at first sight, marked below:


line = arduino.readline().strip()
line = line.lstrip('{').rstrip('}').strip()
# check line not empty
# (actually big enough for at least {} + one key:val entry)

d = {}
# first get items in separate var and check how many:
for item in line.split(','):
item = item.strip()  # not needed, for you strip key/val again 
later

# first get tuple from split() and check its size is 2
key, value = item.split(':')
key = key.strip()
value = value.strip()# not needed, for int() itself strips
# maybe one try/except here for checking conversion to int:
# (else, you need to check yourself it is an int numeral)
d[key]=int(value)

Each check failure is a sign of wrong input. What do you need to do, then? 
Abandon the whole round?


Denis










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


Re: [Tutor] Occurrence of number 2 in a range from 1 to 100

2013-12-01 Thread Mark Lawrence

On 01/12/2013 18:02, Reuben wrote:

Thanks everyone for all the replies.


No problem but please don't top post, it makes following long threads 
particularly difficult, thanks.


--
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] truncated dictionary return

2013-12-01 Thread richard kappler
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.

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

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


On Sun, Dec 1, 2013 at 3:06 PM, spir denis.s...@gmail.com wrote:

 On 12/01/2013 08:28 PM, richard kappler wrote:

 I have a script that reads sensor values gathered by an Arduino board from
 serial as a dictionary, said values to later be used in the AI for Nav 
 Control. Here's the script:

 #!/usr/bin/python

 def sensorRead():
  import serial
  from time import sleep

  sensors = {}
  sensors = dict.fromkeys('Sonar1 Sonar2 Sonar3 Sonar4 Dewpoint
 Temperature Humidity Light'.split())

  arduino = serial.Serial('/dev/ttyACM0', 9600)
  sleep(1)
  line = arduino.readline().strip()
  line = line.lstrip('{').rstrip('}').strip()

  d = {}
  for item in line.split(','):
  item = item.strip()
  key, value = item.split(':')
  key = key.strip()
  value = value.strip()
  d[key]=int(value)
  return d

 I hope that comes through okay, I copied it from the text file so
 indentation and such should be fine, if not let me know.

 The script works great with one exception. I understand the problem, I'm
 just not sure how to address it. The problem is:

 The Arduino runs on a constant loop, it reads each sensor, sends the key
 and the value to the serial bus in format for python to read it as a
 dictionary, lather, rinse, repeat.

 Python querries the bus when told. Usually the python script gets the full
 dictionary (all 8 values with keys, brackets etc) but sometimes it
 doesn't.
 Sometimes it only gets the last few values, sometimes it gets nothing or
 misses a bracket and throws an error. This makes sense. They are not in
 sync.

 What I need to figure out how to do is have the python script wait until
 the next round of values as signified by the opening bracket { or check
 that it has all 8 values and if not retry or something.

 Would this be an if/else? try? exception?

 I've not yet delved into any of these in my quest to learn python except
 if/else and that doesn't feel right for this, so I'm at a loss as to how
 to
 proceed.


 * What is the point of the 'sensors' dict? (also, you don't need to
 initialise it as an enmpty dict)
 * If you know about regexps or another matching utility, use that to
 decode the input line into (key,value) pairs. This is even easier if input
 has a strict format. Would tell us?
 * About wrong input (incomplete data), avoid try/except, except if ever
 most cases are ok (it is very costly in case of exception). Anyway, you
 need to decode input, so use that to check for errors/missing stuff.

 If you used a matching tool, its absence of result would directly tell
 about wrong input (provided your pattern is correct! ;-) As of now, just
 place checks in your decoding sequence. Possible checks places, at first
 sight, marked below:


 line = arduino.readline().strip()
 line = line.lstrip('{').rstrip('}').strip()
 # check line not empty
 # (actually big enough for at least {} + one key:val entry)

 d = {}
 # first get items in separate var and check how many:

 for item in line.split(','):
 item = item.strip()  # not needed, for you strip key/val
 again later
 # first get tuple from split() and check its size is 2

 key, value = item.split(':')
 key = key.strip()
 value = value.strip()# not needed, for int() itself strips
 # maybe one try/except here for checking conversion to int:
 # (else, you need to check yourself it is an int numeral)
 d[key]=int(value)

 Each check failure is a sign 

Re: [Tutor] truncated dictionary return

2013-12-01 Thread richard kappler
Would something like

if len(dict) = 8
return d
else
continue

work?


On Sun, Dec 1, 2013 at 8:54 PM, richard kappler richkapp...@gmail.comwrote:

 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.

 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

 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


 On Sun, Dec 1, 2013 at 3:06 PM, spir denis.s...@gmail.com wrote:

 On 12/01/2013 08:28 PM, richard kappler wrote:

 I have a script that reads sensor values gathered by an Arduino board
 from
 serial as a dictionary, said values to later be used in the AI for Nav 
 Control. Here's the script:

 #!/usr/bin/python

 def sensorRead():
  import serial
  from time import sleep

  sensors = {}
  sensors = dict.fromkeys('Sonar1 Sonar2 Sonar3 Sonar4 Dewpoint
 Temperature Humidity Light'.split())

  arduino = serial.Serial('/dev/ttyACM0', 9600)
  sleep(1)
  line = arduino.readline().strip()
  line = line.lstrip('{').rstrip('}').strip()

  d = {}
  for item in line.split(','):
  item = item.strip()
  key, value = item.split(':')
  key = key.strip()
  value = value.strip()
  d[key]=int(value)
  return d

 I hope that comes through okay, I copied it from the text file so
 indentation and such should be fine, if not let me know.

 The script works great with one exception. I understand the problem, I'm
 just not sure how to address it. The problem is:

 The Arduino runs on a constant loop, it reads each sensor, sends the key
 and the value to the serial bus in format for python to read it as a
 dictionary, lather, rinse, repeat.

 Python querries the bus when told. Usually the python script gets the
 full
 dictionary (all 8 values with keys, brackets etc) but sometimes it
 doesn't.
 Sometimes it only gets the last few values, sometimes it gets nothing or
 misses a bracket and throws an error. This makes sense. They are not in
 sync.

 What I need to figure out how to do is have the python script wait until
 the next round of values as signified by the opening bracket { or check
 that it has all 8 values and if not retry or something.

 Would this be an if/else? try? exception?

 I've not yet delved into any of these in my quest to learn python except
 if/else and that doesn't feel right for this, so I'm at a loss as to how
 to
 proceed.


 * What is the point of the 'sensors' dict? (also, you don't need to
 initialise it as an enmpty dict)
 * If you know about regexps or another matching utility, use that to
 decode the input line into (key,value) pairs. This is even easier if input
 has a strict format. Would tell us?
 * About wrong input (incomplete data), avoid try/except, except if ever
 most cases are ok (it is very costly in case of exception). Anyway, you
 need to decode input, so use that to check for errors/missing stuff.

 If you used a matching tool, its absence of result would directly tell
 about wrong input (provided your pattern is correct! ;-) As of now, just
 place checks in your decoding sequence. Possible checks places, at first
 sight, marked below:


 line = arduino.readline().strip()
 line = line.lstrip('{').rstrip('}').strip()
 # check line not empty
 # (actually big enough for at least {} + one key:val entry)

 d = {}
 # first get items in separate var and check how many:

 for item in line.split(','):
 item = item.strip()  # not needed, for you strip key/val
 again later
 # first get tuple from split() and check its size is 2

 key, value = item.split(':')
 key = key.strip()
 value = value.strip()# not needed, for int() itself strips
 # 

Re: [Tutor] Loop over floating point values

2013-12-01 Thread Amit Saha
On Sun, Dec 1, 2013 at 7:26 PM, Steven D'Aprano st...@pearwood.info wrote:
 On Sun, Dec 01, 2013 at 07:03:15PM +1000, Amit Saha wrote:
 Hello,

 Much to my disbelief, I realized I hadn't written a program in Python
 as far as I can recall which required me to do something like this, in
 psuedocode:

 x = 0.1

 for i = 0 to x step 0.01
 # do something with i
 end i


 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:

# include stdio.h

int main(int argc, char **argv)
{
  float x = 0.0;
  while(x1)
{
  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



 One way to fix this is to iterate over integers, and then divide just
 before doing the work:

 for x in range(0, 10):
 print x/10.0

Yes, that's one approach to ensure that we do not exceed the hard limit of 1.



 Another way is to use the recipes I have here:

 http://code.activestate.com/recipes/577878-generate-equally-spaced-floats/

 http://code.activestate.com/recipes/577881-equally-spaced-floats-part-2/

 http://code.activestate.com/recipes/577068-floating-point-range/

 I encourage you to read all three. If you have any questions, please
 feel free to ask.

Thanks for sharing these, I will go through them.

Best,
Amit.


-- 
http://echorand.me
___
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-01 Thread Amit Saha
On Sun, Dec 1, 2013 at 7:14 PM, Dominik George n...@naturalnet.de wrote:
 Hi,

 - Do not create a list of the floating point values as i=[0.01, 0.02,
 0.03..] - either like that or by using a suitable mathematical formula
 combined with a list comprehension

 You could simply write your own version of xrange that does it, as a
 generator:

   def xrange_f(start, stop, step):
   x = start
   while x  stop:
   yield x
   x += step

 Then, in your code, you can do:

   for f in xrange_f(0, 10, 0.01):
   pass

Thanks Dominik. Yes, this is a good abstraction if I need this
functionality at multiple places.

Best,
Amit.


-- 
http://echorand.me
___
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-01 Thread Amit Saha
On Sun, Dec 1, 2013 at 7:47 PM, spir denis.s...@gmail.com wrote:
 On 12/01/2013 10:03 AM, Amit Saha wrote:

 Hello,

 Much to my disbelief, I realized I hadn't written a program in Python
 as far as I can recall which required me to do something like this, in
 psuedocode:

 x = 0.1

 for i = 0 to x step 0.01
 # do something with i
 end i

 Simply stated, I want to start from say a value, 0 and go upto 0.1 in
 increments of 0.01.  I don't want to create a list with the values
 hard-coded and then iterate over it, and hence I would use a while
 loop instead:

 x = 0.1
 while i  x:
 # do something with i
 i += 0.01

 I think this is one case, where you definitely cannot do this with a
 for loop assuming the following restrictions:

 - Do not create a list of the floating point values as i=[0.01, 0.02,
 0.03..] - either like that or by using a suitable mathematical formula
 combined with a list comprehension
 - Use numpy's linspace() to create the list for you


 Thoughts?


 There is a general solution for this (a typical school problem ;-), maybe
 the reason why we rarely meet it in practice!).

Depends on what your practice is. This will come up in any problem
where you need a continuous stream of numbers. Like, drawing a circle
with x=rcos(theta) and y=rsin(theta) with theta between 0 to 360.

However, watch the issues
 with binary floats mentionned by Steven.

 # loop from x0 to x1 with step dx, total n passes
 x0, x1, dx, n = -0.3, 0.8, 0.2, 6
 for i in range(n):
 x = x0 + dx * i
 print(x)

Yes, IIUC, I think this is an easier problem considering that you
care abut the number of passes here more than  you care about the
upper bound of the numbers.

Thanks for sharing.

Best,
Amit.

-- 
http://echorand.me
___
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-01 Thread Amit Saha
On Mon, Dec 2, 2013 at 4:36 PM, Asokan Pichai paso...@talentsprint.com wrote:
 On Mon, Dec 2, 2013 at 11:58 AM, Amit Saha amitsaha...@gmail.com wrote:

 On Sun, Dec 1, 2013 at 7:26 PM, Steven D'Aprano st...@pearwood.info
 wrote:
  On Sun, Dec 01, 2013 at 07:03:15PM +1000, Amit Saha wrote:
  Hello,
 
  Much to my disbelief, I realized I hadn't written a program in Python
  as far as I can recall which required me to do something like this, in
  psuedocode:
 
  x = 0.1
 
  for i = 0 to x step 0.01
  # do something with i
  end i
 
 
  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:

 I am not sure.


 # include stdio.h

 int main(int argc, char **argv)
 {
   float x = 0.0;

   while(x1)
 {
   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


 Try double here instead of float.
 0.10
 0.20
 0.30
 0.40
 0.50
 0.60
 0.70
 0.80
 0.90
 1.00
 1.10
 is what I get on a debian machine with gcc 4.8.2 , though I suspect that
 these are not relevant.

Yes, I didn't mean to imply C's result as something which is
absolutely the case always. I believe, the inherent nature of floating
point number representations will make this an issue, always.

Best,
-Amit.


-- 
http://echorand.me
___
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-01 Thread eryksun
On Mon, Dec 2, 2013 at 1:28 AM, Amit Saha amitsaha...@gmail.com wrote:
 Indeed, that's a good point. Surprisingly, C does it just fine:

 # include stdio.h

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

   return 0;
 }

Python uses double precision:

 import os, ctypes
 open('tmp.c', 'w').write(r'''
... double test_d() {
... double x = 0.0;
... while (x  1.0)
... x += 0.1;
... return x;
... }
... float test_f() {
... float x = 0.0;
... while (x  1.0)
... x += 0.1;
... return x;
... }
... ''')
 rc = os.system('gcc -shared -o tmp.so tmp.c')
 tmp = ctypes.CDLL('./tmp.so')
 tmp.test_d.restype = ctypes.c_double
 tmp.test_f.restype = ctypes.c_float
 tmp.test_d()
1.0999
 tmp.test_f()
1.001192092896
___
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-01 Thread Devin Jeanpierre
On Sun, Dec 1, 2013 at 7:40 AM, Reuben reuben.dl...@gmail.com 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.

Hash maps are a class of data structures which associate values with
keys. They exhibit constant time average case behavior if every
possible key is equally likely. They usually have O(n) worst case
behavior. Python dictionaries are an implementation of hash maps using
a particular choice of algorithms.


 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 would use sets, not dictionaries.

x = set(range(HUGE_NUM)) # 1 in x is as fast as -1 in x
x = list(range(HUGE_NUM)) # 1 in x is much faster than -1 in x

Sets use hash tables internally too, but they don't associate a value
with the keys. They just mark whether or not the key is present.

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