Re: [Tutor] split a string inside a list

2015-05-09 Thread Dave Angel

On 05/09/2015 04:13 AM, Alan Gauld wrote:

On 09/05/15 04:24, Kayla Hiltermann wrote:

i want to account for variability in user input,

 > like using commas or just spaces.


the user input is initially a string, but is converted to a list once

 > run through .split() .
 > I would like to split the user input by commas or spaces,

I would first replace all non-space separators with spaces
then do the split

separators = ',.;:'   # plus any others you might get
for sep in separators:
  inString.replace(sep,' ')


inString = inString.replace(sep,' ')


sides = inString.split()



import re

def pythagorean_function():
sides = raw_input("Please enter three sides to a triangle:
\n").split(" |,")



sides_int = []
for value in sides:
try:
sides_int.append(int(value))
except ValueError:
continue


You could use a list comprehension here, although you
may not have seen them yet. It would look like:

try:
sides_int = [int(value) for value in sides]
except ValueError:
print ("Remember all sides must be integers \n")
return# no point continuing with the function using bad data


while len(sides_int) != 3:
print ("you did not enter THREE sides! remember all sides must
be integers \n")
break


This should just be an 'if' test, not a while loop.
You only want to test the length once.


sides.sort()
if sides[0]**2 + sides[1]**2 == sides[2]**2:
print "\nthis triangle IS a pythagorean triple!\n"
else:
print "\nthis triangle is NOT a pythagorean triple\n"

redo()


Rather than use recursion here it would be better to
put your function in a top level while loop.


def redo():
redo_question = raw_input("would you like to see if another
triangle is a pythagorean triple? Y/N\n")
if redo_question == "Y":
pythagorean_function()
else:
print "thanks for stopping by!"


You could write that like

redo_question = 'Y'
while redo_question.upper() == 'Y':
 pythagorean_function()
 redo_question = raw_input("would you like to see if another
triangle is a pythagorean triple? Y/N\n")

print "thanks for stopping by!"


HTH



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


Re: [Tutor] pointer puzzlement

2015-05-08 Thread Dave Angel

On 05/08/2015 06:26 PM, Alan Gauld wrote:

On 08/05/15 19:10, Jim Mooney Py3.4.3winXP wrote:

On 7 May 2015 at 18:42, Dave Angel  wrote:


Python doesn't have pointers



So what is the difference between a python name and a pointer?


OK, This could get deepo.
Lets start with the supoerficial...

A pointer (in most languiages) is a named alias for a memory address.
That is a name that is a specidic memory location. At least in C and
some other languages.

That means you can, in C , declare a variable (say p) to be a pointer
to some array of objects and it is simply the memory address of the
first object in the array. The second objects address is therefore
p+sizeof(o) where 'o' is the object type of the array.

You can in fact write code like this in C (and frequently do):

int p*;  // declare p to be a pointer to an integer
int ia[] = {1,2,3,4,5,6,7,8,9,0};  // an array of 10 integers
p = ia;   # p holds the address in ia, ie its first element


This is a shorthand for
p = & (ia[0])



printf("%d\n", p);  // print the object, ie ia[0]


  print("%d\n", *p)   // print the first object   ia[0]
  print(("%d\n", p[0]);  // print the first object, ie ia[0]


printf("%d",p+3);   // print the 4th object ie ia[3]


  printf("%d",*(p+3));   // print the 4th object ie ia[3]
  printf("%d",p[3]);   // print the 4th object ie ia[3]

and p[274] is a random pile of bits which might or might not happen to 
be readable.  Using it might read some other int, it might read a few 
bytes of code, it might cause a segmentation fault.




So p is a pointer to an integer. And an array is a sequence
of integers in memory so you can access subsequent memory
locations by adding numbers to p. (The compiler multiplies
the number by the size of the type of p to get the actual
memory address.)


And all this is part of the language specification.  C is after all, an 
overblown assembly language, and all processors are expected to emulate 
the appropriate Dec machine.





In other languages (eg Pascal) pointers are slightly more
abstract but not much. They are more like C++ references
than memory addresses, but the end result is much the same:
they are very tightly  tied to the physical concepts of
memory versus variables.

Now in contrast...
In Python a name is a much more abstract concept and is
just a label that is attached to an object. How the label
gets attached is an entirely abstract and implementation
specific concept. In practice its usually via a dictionary
so that a variable is a name which is a key of a dictionary.
The corresponding value is an object or, (crucially) maybe
a pointer to an object. But the name is not the pointer
it's the corresponding value that (may be) a pointer.

So this Python code (compare to the C above) makes no sense:

aList = [1,2,3,4,5,6,7,8,9,0]
print aList_+ 3

aList is not a pointer to the start of a sequence of
objects in memory. aList is a key to a dictionary
that holds a reference to a list of objects. And adding
3 to a key in a dictionary is not a sensible operation.


I'd maintain that this is still more than what the language guarantees. 
 The model I have of the language is that a name is a key in some 
namespace (but not necessarily a dict).  The value that's associated 
with that key is an abstraction that the interpreter knows how to decode 
to identify one particular object.  It might be a pointer, it might be 
an integer, it might be a pair of values.


The object might have a fixed location, or it might move around.  As 
long as at any moment that the code is running, the interpreter can find 
the object, it doesn't matter.


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


Re: [Tutor] formatting strings

2015-05-08 Thread Dave Angel

On 05/07/2015 02:57 PM, Tudor, Bogdan - tudby001 wrote:

Hi,

This is my first time.


First time doing what?  Presumably the first time on this forum.  But 
what is your history of using Python, or of programming in general?



I am using python 3.4.3 on windows 7 64bit.

I am trying to make a binary counter that will prompt for and read a decimal 
number (whole number). Then display all decimal numbers starting from 1 up to 
and including the decimal number entered along with the binary representation 
of the numbers to the screen.

I expected nesting a bunch of loops over and over again would work, what I've 
realized is that there must be an easier way of coding this without repeating 
loops, I just cannot for the life of me work this out. What I'm doing at the 
moment is writing way to much code over and over again.

https://github.com/rks1337/binary-counting/blob/master/binary%20counting

Sorry I'm not sure how to use inline quoting on outlook online.



I can't answer for outlook, but normally you add stuff to your message 
by using copy/paste.  On Windows, that's Ctrl-C, Ctrl-V


I can't comment on the specifics of your code, since it's online rather 
than in your message.


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


Re: [Tutor] pointer puzzlement

2015-05-08 Thread Dave Angel

On 05/08/2015 02:10 PM, Jim Mooney Py3.4.3winXP wrote:

On 7 May 2015 at 18:42, Dave Angel  wrote:


Python doesn't have pointers



So what is the difference between a python name and a pointer? I'm a bit
fuzzy on that.


What's the difference between a painting of Obama and a living state 
Senator from New York?


Pointers are not part of Python.  Python is a language specification. 
Some implementations may use pointers to implement the binding, but 
that's irrelevant unless you're doing something like linking C code to 
such an implementation.  Some implementations may run on Motorola 
processors, but that's not part of the language either.  Other 
implementation do not use pointers for the binding.


A name can be reached from a namespace, and it in turn is bound to an 
object.  That binding is a one-way connection that lets the interpreter 
find the object, given the namespace and the name.




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


Re: [Tutor] introspection

2015-05-08 Thread Dave Angel

On 05/08/2015 02:26 AM, Alex Kleider wrote:

On 2015-05-07 20:45, Dave Angel wrote:


You also only showed it working on module globals.  (For code at
top-level, locals() returns the same as globals() )

You could also try it inside functions, where locals() really makes
sense as a name.  And you could try it in a nested function where
there may very well be non-locals (eg. closure items) that aren't
local or global.


You've taken me to new territory:
http://www.shutupandship.com/2012/01/python-closures-explained.html
I wasn't familiar with 'closures' and to be truthful, still am not,
although thanks to you I am at least aware of the idea.


But more interestingly, you could try it on items of a list, or
members of a dictionary, where there's no name at all associated with
the object.


It simply returns None.  I assume that's the point you are making?
(That it has no name, or perhaps more accurately expressed: there is
no name to discover.)



That's right.  But depending on why you're looking, it might be worth 
doing some more subtle searching.  For example, you're currently looking 
at all the members of a dict.  But if one of those members is of type 
dict, list, or tuple, you could look at its members. If you do that 
recursively, you could identify a lot more objects.


Also, since you have to pass the object into the search function, you 
already have one known reference.  That one might not be the interesting 
one, as it might have been made just for this testing.  So it would be 
useful if this function produced a list of *all* the references it can find.


And you could have your function work from an id() value.  Given an 
integer, try to find names or expressions that yield this id value.



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


Re: [Tutor] introspection

2015-05-07 Thread Dave Angel

On 05/07/2015 11:23 PM, Alex Kleider wrote:

On 2015-05-07 19:10, Dave Angel wrote:


def get_name(localmap, item):
 """As suggested.
 Returns 'a' name, not necessarily 'the' name."""
 for name in localmap:
 if localmap[name] == item:


This is not likely to be what was intended.  You want
   if localmap[name] is item:
That can identify if one of the names happens to be bound to the SAME
object being examined.  Rather than one that happens to have the same
value.


Correction noted.  Thank you for that.  The distinction is important.
('==' vs 'is')



You also only showed it working on module globals.  (For code at 
top-level, locals() returns the same as globals() )


You could also try it inside functions, where locals() really makes 
sense as a name.  And you could try it in a nested function where there 
may very well be non-locals (eg. closure items) that aren't local or global.


But more interestingly, you could try it on items of a list, or members 
of a dictionary, where there's no name at all associated with the object.



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


Re: [Tutor] introspection

2015-05-07 Thread Dave Angel

On 05/07/2015 09:50 PM, Alex Kleider wrote:

On 2015-04-21 16:48, Cameron Simpson wrote:


But it would not be schizophrenic to write a function that returned a
name arbitrarily, by inspecting locals(). It depends whether you only
need a name, or if you need "the" name.

Write yourself a "find_name_from_locals(local_map, value)" function
that reports. That will (a) get you a partial answer and (b) cement in
your mind what is possible and why. Easy and useful!

Cheers,
Cameron Simpson 


Well I finally got around to tackling this little challenge and you are
right:
It was illuminating.

For what it's worth, here's the code that made the light go on:
#!../venv/bin/python3
# -*- coding: utf-8 -*-
# vim: set file encoding=utf-8 :
#
# file: 'getname.py'
"""

def get_name(localmap, item):
 """As suggested.
 Returns 'a' name, not necessarily 'the' name."""
 for name in localmap:
 if localmap[name] == item:


This is not likely to be what was intended.  You want
   if localmap[name] is item:
That can identify if one of the names happens to be bound to the SAME 
object being examined.  Rather than one that happens to have the same value.



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


Re: [Tutor] pointer puzzlement

2015-05-07 Thread Dave Angel

On 05/07/2015 07:51 PM, Dave Angel wrote:

On 05/07/2015 04:54 PM, Jim Mooney Py3.4.3winXP wrote:

On 7 May 2015 at 13:03, Emile van Sebille  wrote:


Compare to:

def testid(K=100):
  K += 10
  return 'the ID is', id(K), K



Ah, thanks. I forgot small integers are saved in a table. I was
looking at
a demo that pointers to defaults in function parameters are persistent.


Python doesn't have pointers, and nothing here is persistent.
Persistence refers to a value surviving multiple invocations of a program.



I think the term you're looking for is "static lifetime".  That object 
will exist for the life of the program.  The local variable name K is 
bound to that object each time the function is called without an argument.





It
used lists so I tried ints. Although I realized persistence also works
for
dicts ;')

def testid(newitem, K={}):
  K[newitem] = newitem + 'item'
  return 'the ID is', id(K), K


testid('bonk')

('the ID is', 18263656, {'bonk': 'bonkitem'})

testid('clonk')

('the ID is', 18263656, {'bonk': 'bonkitem', 'clonk': 'clonkitem'})

testid('spam')

('the ID is', 18263656, {'bonk': 'bonkitem', 'clonk': 'clonkitem',
'spam':
'spamitem'})


The object is not immutable, so it can change.  Therefore the += does an
in-place change, and you keep the same id.





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


Re: [Tutor] pointer puzzlement

2015-05-07 Thread Dave Angel

On 05/07/2015 05:25 PM, Alan Gauld wrote:

On 07/05/15 21:54, Jim Mooney Py3.4.3winXP wrote:


Ah, thanks. I forgot small integers are saved in a table. I was
looking at
a demo that pointers to defaults in function parameters are persistent.


But remember they variables are NOT pointers.
They are keys in a dictionary. Very different.

Also the id() function is implementation dependant so
although it may seem to be a memory address in CPython
it is something else in IronPython and something else
again in Jython. The only thing guaranteed is that
it is a unique id for that object.


Unique as long as the two objects you're examining exist at the same 
time.  An id() may be reused once the first object is destroyed.  And in 
general for CPython that happens a lot for small objects.




As to default parameter values, the default object is
persistent but if you reassign the parameter inside
the function it will obviously lose its binding to
the default object. It will only be reassigned to
it on the next function call (unless it's a generator
function).




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


Re: [Tutor] pointer puzzlement

2015-05-07 Thread Dave Angel

On 05/07/2015 04:54 PM, Jim Mooney Py3.4.3winXP wrote:

On 7 May 2015 at 13:03, Emile van Sebille  wrote:


Compare to:

def testid(K=100):
  K += 10
  return 'the ID is', id(K), K



Ah, thanks. I forgot small integers are saved in a table. I was looking at
a demo that pointers to defaults in function parameters are persistent.


Python doesn't have pointers, and nothing here is persistent. 
Persistence refers to a value surviving multiple invocations of a program.




It
used lists so I tried ints. Although I realized persistence also works for
dicts ;')

def testid(newitem, K={}):
  K[newitem] = newitem + 'item'
  return 'the ID is', id(K), K


testid('bonk')

('the ID is', 18263656, {'bonk': 'bonkitem'})

testid('clonk')

('the ID is', 18263656, {'bonk': 'bonkitem', 'clonk': 'clonkitem'})

testid('spam')

('the ID is', 18263656, {'bonk': 'bonkitem', 'clonk': 'clonkitem', 'spam':
'spamitem'})


The object is not immutable, so it can change.  Therefore the += does an 
in-place change, and you keep the same id.



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


Re: [Tutor] pointer puzzlement

2015-05-07 Thread Dave Angel

On 05/07/2015 03:15 PM, Jim Mooney Py3.4.3winXP wrote:

I find this a bit confusing. Since the ID of K remains the same, so it's
the same object, why isn't it increasing each time. i.e, 20, 30, 40,. I
understand that it's immutable but doesn't that mean K is created each time
in local scope so it should have a different ID each time?

def testid(K=10):
 K += 10
 return 'the ID is', id(K), K

*** Python 3.4.3 (v3.4.3:9b73f1c3e601, Feb 24 2015, 22:43:06) [MSC v.1600
32 bit (Intel)] on win32. ***

testid()

('the ID is', 505991936, 20)

testid()

('the ID is', 505991936, 20)

testid()

('the ID is', 505991936, 20)






K is certainly created new each time, but it is bound to the same 
object, the one created when the function is defined.


K does not have an id(), that object does.

Since the object in this case is immutable, the += creates a new object 
and binds that to K.  In your particular code, you never call the id() 
for the initialization object.  I'd add another print, that shows the 
id(K) before the +=


All of this is confused by the fact that small ints happen to be 
interned by your paricular implementation.  So you're getting the same 
 object each time.




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


Re: [Tutor] pointer puzzlement

2015-05-07 Thread Dave Angel

On 05/07/2015 04:03 PM, Emile van Sebille wrote:

On 5/7/2015 12:15 PM, Jim Mooney Py3.4.3winXP wrote:

I find this a bit confusing. Since the ID of K remains the same, so it's
the same object, why isn't it increasing each time. i.e, 20, 30, 40,. I
understand that it's immutable but doesn't that mean K is created each
time
in local scope so it should have a different ID each time?


You're looking at the ID of an interned string:


Interned int



 >>> testid()
('the ID is', 7515584L, 20)
 >>> testid()
('the ID is', 7515584L, 20)
 >>> testid()
('the ID is', 7515584L, 20)
 >>> id(20)
7515584L
 >>> id(10+10)
7515584L
 >>> id(19+1)
7515584L


Compare to:

def testid(K=100):
  K += 10
  return 'the ID is', id(K), K





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


Re: [Tutor] key detection

2015-05-06 Thread Dave Angel

On 05/06/2015 01:41 PM, Jim Mooney Py3.4.3winXP wrote:


from msvcrt import *

while True:
 if kbhit():
 key = getch()
 if key == b'\xe0' or key == b'\000':
 print('special key follows')
 key = getch()
 print(str(key, encoding='utf-8')) #got rid of this decode after
a function key error
 else:
 print('The key is: ', str(key, encoding='utf-8'))

Traceback (most recent call last):
   File "keyget.py", line 9, in 
 print(str(key, encoding='utf-8'))
UnicodeDecodeError: 'utf-8' codec can't decode byte 0x85 in position 0:
invalid start byte





I don't know why you would be expecting to get a utf-8 character for the 
second byte of a function key code.  It's an entirely arbitrary byte 
sequence, and not equivalent to anything in Unicode, encoded or not.



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


Re: [Tutor] Fwd: Re: Adding consecutive numbers

2015-05-06 Thread Dave Angel

On 05/06/2015 07:51 AM, Alan Gauld wrote:

Please use ReplyAll to include the list members.


 Forwarded Message 
Subject: Re: [Tutor] Adding consecutive numbers
Date: Wed, 6 May 2015 21:13:15 +1000
From: Whom Isac 
To: Alan Gauld 



Thanks for the reply. I am sorry that I did not notice the mail. I am
actually using the latest version of python (3.5) in windows 7 operating
system. I have already made certain changes in the code. I understood my
mistake. The correction's are not finished yet,though. You can have a
look at it, because, I donot know what I have written is already in
right syntax or not.

Here are my code:
##Goal: Building a math program.
## two nums will be asked by the user
## they will be added
## condition: num >=o:
## num will continue to be added into a list untill the second number
## For your information, a consequitive sequence of num : num-->1
num1--> num+1...+n

if __name__=='__main__':
 interact()


You get an error right there, since interact() isn't defined yet.  Move 
the above two lines to the end of the file.




def interact():
 print('''Welcome to My new Math program!!
 With this program, you can find the sum of any consequitive
numbers.''')
 print('So Just add your numbers in following spaces')
 ## If anybody complaining about this function. I will have to say,
that the coding is incomplete so
 ## I will first define all my function then def interact() when I
am finishing.


def getting_numbers(first_num, second_num):
 x = [] #This is a empty list to store data
 y = [] #This is a empty list to store data
 """Getting the user values:"""
 first_num =int(input('Please enter your first number: '))
 x.append(first_num) # adding the input in x#
 second_num =int(input('Please enter your second number: '))
 y.append(second_num) # adding the input in x#
 z =(x,y) # This is a touple containing both x and y value.
 return z


Why are you so enamored with lists?  You're returning a tuple containing 
two lists each of which has exactly one value?  Why not just return a 
tuple of first_num and second_num ?





def adding_all(x):
 total = 0
 for num in x:
 total +=num
 return total


Good function.


def remove_letter(x):
 if x != len(x):


What do you think that statement does?  It can't possibly do anything 
useful since the right side assumes that x is a collection or 
equivalent, and the left side assumes that x is a number.



 print('You did not enter a number')
 elif x != adding_all(x):
 print("Please, donot include letters")
 else:
 return x
 ## I think using a while True function to iterate all item in x
would be better.



Considering that after you call each input() function, you immediately 
call int(), I'd figure that checking for "you did not enter a number" is 
superfluous.






def adding_number(x,y):
 start = x[0]
 end = y[0]
 new_x = 0
 new_x_1 = 0
 while x[0]<=y[0] or x[0]<= 0:
 if x[0]==0:
 new_x+=1
 return new_x
 elif x[0]>0 or x[0]

I can't make any sense out of anything in this function.

I think you need to write one function and include descriptive comments 
in it, and write code that tests it against those comments.  Then when 
you have one function that successfully runs, write a second one.





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


Re: [Tutor] key detection

2015-05-06 Thread Dave Angel

On 05/06/2015 12:02 AM, Jim Mooney Py3.4.3winXP wrote:


actually worked in windows instead of using their awful screen
copy. What a surprise:


Many people don't realize that you can turn on a better screen copy 
feature for the CMD window (DOS box) in Windows.


I've given up Windows, and no longer remember how, but the feature is 
called something like auto-copy and can be turned on for all DOS box 
windows.


Once on, you select by dragging with the mouse, and insert by 
right-click.  Still has to be a rectangle, but better than nothing when 
redirection lets you down.



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


Re: [Tutor] Object references and garbage collection confusion

2015-05-05 Thread Dave Angel

On 05/05/2015 12:29 AM, Brandon D wrote:

Hello tutors,

I'm having trouble understanding, as well as visualizing, how object
references work in the following situation.  For demonstration purposes I
will keep it at the most rudimentary level:

x = 10

x = x ** x

If my knowledge serves me correctly, Python destroys the value once
reassigned.  So, how does x = x +  1 work if it's destroyed before it can
be referenced?  The only solution I came up with is that the two operands
are evaluated before storing it in the variable, consequently replacing the
original value of 0.


It's not destroyed before it's referenced.  The ten-object is destroyed 
(or may be, depending on optimizations and such) when nothing is bound 
to it.  That happens just after the new object is bound to x.


it may be interesting to put some simple statements into a function, and 
use dis.dis on that function.


import dis
def myfunc():
x = 10
x = x ** x

dis.dis(myfunc)



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


Re: [Tutor] Sieve of Erastthotenes without sofisticated tools

2015-05-04 Thread Dave Angel
You accidentally sent your response to me instead of the list.  The 
proper thing to do for nearly all messages is to respond to the list. 
The main exception for that is if you just want to leave a simple 
thank-you for a person, and nothing of interest to anyone else.


From your email program, use Reply-List.  If it doesn't support that, 
use Reply-All, and then delete me, so it goes just to the list.


Another problem with your message is messed-up formatting, apparently 
caused by the fact that you're sending html-encoded email to a text-only 
mailing list.  Please tell your mailer to use text.


On 05/04/2015 10:07 PM, yvan moses levy wrote:> Le 04/05/15 13:00, Dave 
Angel a écrit :

>> On 05/04/2015 03:19 AM, yvan moses Levy wrote:
>>> My code is wrong!
>>
>> You'd find it a lot easier to get responses if you'd say in what way 
the code

>> is wrong.  If you get an exception, show the full traceback.  If you get
>> printed results, show what you expected, and what you got instead. 
If it

>> hung, or crashed the OS, or ran out of memory, say so.
>>
>>> I tried and tried
>>> But I'm very isolated and It's hard without consultation with a tutor
>>> from math import sqrt
>>> def holeofStrainer():
>>>bigList = [False, False] + [True]*100
>>>print("line 4 - bigList : ", bigList)
>>>for num in range(2, 101):
>>>  print("line 6 - num : ", num)
>>>  for x in range(bigList[2], bigList[int(sqrt(num)) + 1]):
>>
>> What did you expect this to do?  What is bigList[2] ?  What is
>> bigList[int(sqrt(num)) + 1] ?  Are these reasonable values to put into a
>> range() function?
>>

You didn't answer any of these questions.  Why not?

>>
>>
>>>print("line 8 x : %d"%x)
>>>if num % x == 0:
>>>  print("line 10 {0} divise par {1} = {2} ".format(num, x, 
num/x))

>>>  bigList[num] == False
>>>  print "bigList[{0} == {1}]".format(num, bigList[num])
>>>bigList[num] == True
>>>
>>>  for multiple in range (2, int(101/num) + 1):
>>>bigList[multiple] = False
>>>return(bigList)
>>> print("the last result of bigList {} ".format(holeofStrainer()))
>>> I WANT TO KNOW WHILE THE EXECUTION DO NOT GOING DOWNWARD
>>>
>>>
>> OK I'll trying
> code:
> from math import sqrt
> def holeofStrainer():
> """The purpose is to build a sieve of Erasthotenes.
> We beginn with a sieve without holes, called biglist.
> The indexes of the list have a double function:
> First, The natural list indexation. II-st, there are
> as keys of the corresponding list items(the boolean
>   values of the prime being question about each number).
> We have for each index a"""
> bigList = [False, False] + [True]*100
> print("line 11 - bigList : ", bigList)
> for num in range(3, 101):
>   print("line 13 - num : ", num)
>   # I f we don't find divisors of nume littler that sqrt(num)
>   # it is guaranted that num is prime.
>   # 'int(sqrt(num)) + 1' is the first integer greater than sqrt(num)
>   for x in range(bigList[2], bigList[int(sqrt(num)) + 1]):

I repeat, what did you expect this line to do? Examine this line 
carefully.  Print out the two expressions you're passing to range().


This currently loops from True to True, or from False to False, so it 
skips the whole predicate. Think about what you really want the loop to do.



> print("line 18 x  is equal to %d"%x)
> if num % x == 0:
>   print("line 20 {0} divided by {1} = {2} ".format(num, x, 
num/x))

>   bigList[num] == False
>   print ("bigList index {0} == {1}".format(num, bigList[num]))
> bigList[num] == True
>
>   for multiple in range (2, int(101/num) + 1):
> bigList[multiple] = False
> return(bigList) #We expect a 'sieve with many holes'
> print("the last result of bigList {} ".format(holeofStrainer()))*
>
> *
>
> ***Hi Dave.*

What's the reason you're quad-spacing the expected output?  I'm fixing 
it, but it's a pain to do.


>
> **
> > *I expected to obtain an output as:*
>
> *line 13 num 3*
> *line 18 x :2*
> *line 20: 3 divided by 2 is equal to 1.5*
> *biglist index 3 == True*
> *line 13 num 4*
> *line 18 x:2*
> *line 20 4 divided by 2 is equal to 2*
> *biglist index 4 == False*

So that's what you expected.  What did you get instead?  If you notice 
that line 18 never printed, shouldn't you guess that something's wrong 
with the loop in line 17?




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


Re: [Tutor] Python program malfunction

2015-05-04 Thread Dave Angel

On 05/04/2015 07:08 PM, Jag Sherrington wrote:

Hi, Alan>




Please don't top-post.  Enter your new message *after* whatever portion 
of the previous message you're quoting.  I'm rearranging the portion of 
your message to conform to that standard.





  On Monday, 4 May 2015, 17:35, Alan Gauld  
wrote:



# Process one or more items.
while another == 'y' or another == 'y':


That's the same test twice. Is that what you meant?


   #Get the item 's wholesale cost'
   wholesale = float(input("Enter the item's wholesale cost: "))

   # Validate the wholesale cost.
   while wholesale < 0:
   print('ERROR: the cost cannot be negative.')
   wholesale = float(input('Enter the correct wholesale cost: '))


BUG on following line:

   #Calculate the retail price.
   retail = wholesale * mark_up

   #Display the retail price.
   print('Retail price: $', format(retail, ',.2f'), sep='')

   #Do this again.
   another = input('Do you have another item? ' + \
   '(Enter y for yes): ')

HERE ARE THE RESULTS:

Enter the item's wholesale cost: 0.50
Enter the item's wholesale cost:(THIS SEEMS TO BE A PROBLEM)


No problem, its exactly what your program tells it to do.
If the cost is >0 there is nothing else to do so it goes
round the loop a second time.

What did you expect it to do?


> Enter the item's wholesale cost: 0.50 (AFTER THIS LINE PRINTS I HIT
> ENTER AND WOULD EXPECT THE NEXT LINE TO GIVE ME THE RESULT>
> Enter the item's wholesale cost:"Retail price: $1.25"
> INSTEAD WHEN I HIT ENTER I GET "Enter the item's
>  wholesale cost: " AGAIN AND AGAIN

(See Peter's comment as well as Alan's second one.)

All the rest of your logic is inside the while loop that's only run when 
the wholesale < 0 branch is taken.  So you don't see any output from it, 
as it never runs unless you enter a negative value followed by a 
positive one.


You have to fix the indentation of the lines starting "#Calculate the 
retail price"




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


Re: [Tutor] Sieve of Erastthotenes without sofisticated tools

2015-05-04 Thread Dave Angel

On 05/04/2015 03:19 AM, yvan moses Levy wrote:

My code is wrong!


You'd find it a lot easier to get responses if you'd say in what way the 
code is wrong.  If you get an exception, show the full traceback.  If 
you get printed results, show what you expected, and what you got 
instead.  If it hung, or crashed the OS, or ran out of memory, say so.



I tried and tried
But I'm very isolated and It's hard without consultation with a tutor
from math import sqrt
def holeofStrainer():
   bigList = [False, False] + [True]*100
   print("line 4 - bigList : ", bigList)
   for num in range(2, 101):
 print("line 6 - num : ", num)
 for x in range(bigList[2], bigList[int(sqrt(num)) + 1]):


What did you expect this to do?  What is bigList[2] ?  What is 
bigList[int(sqrt(num)) + 1] ?  Are these reasonable values to put into a 
range() function?





   print("line 8 x : %d"%x)
   if num % x == 0:
 print("line 10 {0} divise par {1} = {2} ".format(num, x, num/x))
 bigList[num] == False
 print "bigList[{0} == {1}]".format(num, bigList[num])
   bigList[num] == True

 for multiple in range (2, int(101/num) + 1):
   bigList[multiple] = False
   return(bigList)
print("the last result of bigList {} ".format(holeofStrainer()))
I WANT TO KNOW WHILE THE EXECUTION DO NOT GOING DOWNWARD

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





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


Re: [Tutor] Having Unusual results

2015-05-02 Thread Dave Angel

On 05/02/2015 04:36 AM, Peter Otten wrote:

Jag Sherrington wrote:
With that the calculation becomes


buns = 20
package_size = 8
whole_packages, missing_buns = divmod(buns, package_size)
total_packages = whole_packages
if missing_buns: total_packages += 1

...

total_packages

3



And that can be simplified:

buns = 20
package_size = 8
total_packages = (buns + package_size - 1) // package_size

#desired answer 3


Or, to take better advantage of the Python library:

import math
total_packages = math.ceil(buns/package_size)

This is exactly what the ceiling and floor mathematical concepts are 
needed for.


Note, I'm using the fact that the OP is writing in Python 3.  If not, 
one should probably add

   from __future__ import division
.

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


Re: [Tutor] Newbie problems

2015-05-02 Thread Dave Angel
1) Please reply-list, or if your email program doesn't support that, do 
a reply-all.  The idea is to make sure tutor@python.org is in your To: 
field.  Otherwise you're just leaving private messages, and that's not 
what a public forum like this is about.


2) Please use text email, not html.  As you can see below, your 
formatting was thoroughly trashed by your email program.  I took a 
message at the html in your message, and you tried to use color as well, 
which won't be visible by most people here.


On 05/01/2015 10:29 PM, Jag Sherrington wrote:

Hi DaveThanks for your help. I followed your instruction and got the following 
message:
Enter a number between 0 and 36: 9Traceback (most recent call last):  File 
"C:\Python34\Tests\Roulette_wheel_colours.py", line 8, in if number 
in green_numbers:TypeError: argument of type 'int' is not iterable
This is what I programmed:
number = int(input('Enter a number between 0 and 36: '))green_numbers = (0) 
red_numbers = (1, 3, 5, 7, 9, 12, 14, 16, 18, 19,\  21, 23, 25, 27, 
30, 32, 34, 36) black_numbers = (2, 4, 6, 8, 10, 11, 13, 15, 17, 20,\   
 22, 24, 26, 28, 34, 29, 31, 33, 35)
if number in green_numbers:print('Number is Green')
elif number in red_numbers:print('Number is Red')
elif number in black_numbers:print('Number is Black')
Kind regards, Jag BraveArt Multimedia
0421176576



Your remaining problem is that green_numbers isn't a list or tuple, it's 
just a single number.  You can change either of the following ways:


green_numbers = (0,)  #The comma forces it to be a tuple
or
green_numbers = [0]   #it's a list

Alternatively, you could use == for green, and in for the other two. 
But as good programming practice, it's good to keep symmetry for the 3 
cases.


--
DaveA

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


Re: [Tutor] Good Taste Question: Using SQLite3 in Python

2015-04-30 Thread Dave Angel

On 04/30/2015 03:22 PM, Roel Schroeven wrote:

Alan Gauld schreef op 2015-04-30 00:51:

 > ...


Trying to visually scan for _ or even __ is hard. Also different
fonts make _ and __ hard to distinguish.


 > ...


But they will be. Almost for certain. It's human nature and the nature
of code maintenance. If it's there somebody will find a use for it.
The fact that 5 or 10 years earlier the author didn't intend for it to
be used is immaterial.


Summarizing a bit, I think you make two main points (please correct me
if I'm wrong):

[1] Visually scanning for _ or __ is hard, and _ are __ hard to
distinguish from each other.

Personally, I find it easy to scan for them, but I think I can see whee
you're coming from. Python tends to prefer words and tends to dislike
symbols compared to e.g. C, C++, and certainly Perl. One could argue
that using _ or __ goes against that, though to me it's not a problem.
We're still very far from Perl's line noise.
It's true that _ and __ can be difficult to be distinguished from each
other, but that's also not a problem to me, since I don't care about
their values.


[2] Inevitably, sooner or later someone somewhere will start using _ or
__ despite the fact that by convention they should not be used.

I have to admit that I have no experience programming in larger teams,
and was blissfully unaware of the problems you describe. I think I can
see how it might be better to avoid __ rather than try to enforce good
coding discipline.


I still feel __ to be valuable, but I can see now where your dislike for
it is coming from. Thank you for your insights!



Well, are you aware that _ has a meaning in the debugger?  It holds the 
last value of an expression that wasn't assigned to a variable.  or 
something like that.


So even if you don't have any coworkers, you might trip on someone 
else's assumptions.


To see what I'm talking about:

>>> 3*4
12
>>> print(_)
12




Best regards,
Roel




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


Re: [Tutor] Newbie problems

2015-04-30 Thread Dave Angel

On 04/29/2015 11:58 PM, Jag Sherrington wrote:

Can anyone please tell me what I am doing wrong?As this code I have for the 
Roulette Wheel colours exercise, won't work. number = int(input('Enter a number 
between 0 and 36: '))green_number = (0) red_number = (1, 3, 5, 7, 9, 12, 14, 
16, 18, 19, 21, 23, 25, 27, 30, 32, 34, 36) black_number = (2, 4, 6, 8, 10, 11, 
13, 15, 17, 20, 22, 24, 26, 28, 34, 29, 31, 33, 35)
if number == green_number:print('Number is Green')elif number == 
red_number:print('Number is Red')elif number == black_number:
print('Number is Black')
Thank you for any help, Jag



Please post your code the way you're going to run it, like one statement 
per line, indented as required, etc.


Your problem is you're comparing an int (number) to a list (green_number 
or red_number or black_number).  They'll never be equal so it won't 
print anything.


presumably you don't want to know if the number is equal to the list, 
but whether it's in the list.  The "in" operator will tell you that.


Something like:
if number in green_numbers:

(I changed it to plural, so it'd be more obvious that it's not a single 
value, but a list of them.  Little things like that can make errors much 
easier to spot.)



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


Re: [Tutor] How to use Git from Windows PC for files on Solaris machine where Git cannot be installed?

2015-04-29 Thread Dave Angel

On 04/30/2015 12:28 AM, boB Stepp wrote:

The main danger as I see it is that if I am not careful, then the code
on the dev environment could diverge from the state of code on my
Windows PC, i.e., I forgot to do the scp part. But when I am actively
working on a section of code I always insert a few print statements
(Py 2.4!) to verify I am getting what I should when I test it
out--even if I don't have an actual problem yet. And so far this has
immediately revealed those few instances so far when I forgot to save
to the dev machine (Usually when someone has interrupted my workflow,
a near constant occurrence at work.).




Add an automatic file copy to the save-key definition in your editor. 
Then whenever you save the file locally, you'll also be copying it to 
the master location.


If that's too hard, or your editor can't support it, write a bash script 
that does an rsynch every 10 minutes.


rsynch does what scp does, but it works on whole directories, copying 
only those files that changed.  And you can fine tune what "changed" means.


There are other, less resource intense approaches, but if one of these 
works, it'll be pretty painless to set up.


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


Re: [Tutor] raise exception works as planned in program but not when imported into testing module

2015-04-29 Thread Dave Angel

On 04/29/2015 09:05 PM, Jim Mooney Py3.4.3winXP wrote:

I raised an exception in the parse_string function in my math parser
program, function_tosser.py, and caught it in the calling routine, and that
worked fine. But when I imported function_tosser.py into a test program,
tester.py, it threw the exception in the parse_string function instead of
handling it in the try block in the calling routine. Why did it work in one
and not the other? The testing program works fine if I return None as I did
before, instead of raising the exception.


It'd be nice if you were explicit about which code you're describing.  I 
can make guesses, but your above paragraph leaves a lot of confusion.


I'm guessing you're talking about the line in parse_string():
raise ValueError

And I assume you're talking about it being referenced in the other file 
by the line:

print(ft.parse_string(monkey_wrench), '\n')

But why are you surprised?  There's no try/except protecting the latter 
line, so the exception will be uncaught, and you'll see it reported in 
parse_string().


> in the try block in the calling routine.

What routine is that?  The line I quoted above is in top-level code, not 
in a routine. And it doesn't have a try/except there.




# function_tosser.py
"""
Takes the name of a binary math operation and two numbers from input,
repeatedly, and displays the results until done
"""


def add(a, b):
 return a + b


def subtract(a, b):
 return b - a

def minus(a, b):
 return a - b


def multiply(a, b):
 return a * b


def divide(a, b):
 return a / b


operations = {'add': add, '+': add, 'plus': add, 'subtract': subtract,
'subtracted': subtract,
   '-': minus, 'minus': minus, 'multiply': multiply, '*':
multiply, 'multiplied': multiply,
   'times': multiply, 'divide': divide, '/': divide, 'divided':
divide}

def test_number(astring):
 """
 Input: A string that should represent a valid int or float. Output:
 An int or float on success. None on failure.
 """
 for make_type in (int, float):
 try:
 return make_type(astring)
 except ValueError: # Previously returned None, which worked. This
works fine here but when imported into the test program
 pass   # it doesn't wait for the try block in the
calling routine.
 return None


def parse_string(math_string):
 """Input: A math string with a verbal or mathematical operation
 and two valid numbers to operate on. Extra numbers and operations
 are ignored. Output: A tuple containing a function corresponding
 to the operation and the two numbers. Returns None on failure.
 """
 operation = None
 tokens = math_string.split()
 numbers = []
 for token in tokens:
 if token in operations:
 operation = operations[token]
 elif test_number(token) != None:
 numbers.append(test_number(token))
 if len(numbers) > 1:
 break
 if operation is None or len(numbers) < 2:
 raise ValueError
 else:
 return operation, numbers[0], numbers[1]

if __name__ == "__main__":
 instructions = '''Enter two numbers and one of the four basid math
operations,
 either mathematical or verbal. i.e. 3 + 2, 12 divided by 14, 10 minus
4, etc.
 Enter done to quit.
 '''
 try:
 user_input = input(instructions)
 while True:
 if user_input == 'done':
 break
 try:
 result = parse_string(user_input)
 except ValueError:
 print("Not a valid math operation.")
 else:
 func, num1, num2 = result
 print(func(num1, num2))
 user_input = input()
 except KeyboardInterrupt:
 print("Program terminated by user")

# tester.py

'''Test function_tosser.py mainlogic against random operators, operands,
and bad input'''
import random
import function_tosser as ft
valid_terms = list(ft.operations.keys())
def eval_test():
 pass

trash = ['1 +', 'blah', '3-4', 'gargle', 'Newt Gingrich',
 ",", '{+=-33.44 minus12 3 times blarg 1445641654644555455']

for ctr in range(50):
 term = ' ' + random.choice(valid_terms) + ' '
 num1 = str(random.randint(1,1000))
 num2 = str(random.randint(1,1000))
 if term == ' subtract ' or term == ' subtracted ': term = ' subtracted
from '
 if ctr % 10 == 0: # stress testing for a None failure
 monkey_wrench = random.choice(trash)
 print(ft.parse_string(monkey_wrench), '\n')
 else:
 func, num1, num2 = ft.parse_string(num1 + term + num2)
 print(func, num1, term, num2)
 print('result:',func(num1, num2), '\n')





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


Re: [Tutor] Fwd: circular movement in pygame

2015-04-29 Thread Dave Angel

On 04/29/2015 02:37 PM, diliup gabadamudalige wrote:

I do not understand how Alan does not get the code that is in this thread.


There are at least 3 ways of posting to "this thread":
   A) email
   B) newsgroup
   C) googlegroups

and at least 5 ways of looking at "this thread"
   A) email
   B) email digest
   C) newsgroup
   D) googlegroups
   E) various archives

To get messages from one region to another involves going through a 
gateway, and most of them damage some of the messages going through.  To 
minimize the likelihood that what looks good on your screen will be 
missing or different on mine or on Alan's, follow a few rules:


   1) avoid html
   2) avoid attachments

There are others, but those seem to be the biggies.

Many other guidelines will help readability and consistency, like not 
top-posting, using proper quoting and attribution, giving enough 
information but not too much, specifying the whole environment in the 
FIRST message of a thread, etc.


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


Re: [Tutor] subprocess.Popen(..., cwd) and UNC paths

2015-04-29 Thread Dave Angel

On 04/29/2015 08:47 AM, Albert-Jan Roskam wrote:

Hello,

Windows has the 'feature' that the CD command does not work with UNC paths.
So in the code below, I cannot use the 'cwd' parameter of subprocess.Popen.
Therefore I use pushd/popd to accomplish the same effect. Is there a better way 
to do this?
(other than using full path names everywhere, or os.chdir). Would it be a 
useful improvement
of Python itself if cwd also works with UNC path?

import sys
import os
import getpass
import subprocess

path = r'\\server\share\possibly with\space'
executable = 'blah.exe'
username = os.getenv("USERNAME")
password = getpass.getpass("Enter password: ")
infile =  sys.argv[1]
outfile = sys.argv[2]
cmds = ['pushd "%s" &&' % path, executable, username, password, infile, outfile, "&& 
popd"]

result = subprocess.Popen(" ".join(cmds), shell=True)
error = result.stderr
if error:
 raise RuntimeError(error.read())

Regards,

Albert-Jan

PS: Python 2.7 on Windows 7 32



Just a comment about Windows.  There is a current directory for each 
lettered drive partition.  But a unc name is not necessarily on any 
known drive.


And if executable, infile and outfile might have spaces within them, you 
need to quote them as well.





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


Re: [Tutor] circular movement in pygame

2015-04-29 Thread Dave Angel

On 04/29/2015 03:15 AM, diliup gabadamudalige wrote:

Thanks all for the responses.
Charles Cossé -  yes I can write a simple pygame program that makes a
sprite move in a circle but it may not be the style and order that many may
approve or accept. I consider myself a student. :)
No one has pointed out why the object moves in a circle properly in the bit
of code where it is addressed directly and why it does not when the same
code is applied thru a class.
I know that an object can be made to move around the circumference of a
circle by constantly calculating the point and giving the x and y values

1. x = some code

That is what I used and it worked. I was trying to find how we can do the
same thing by updating the current position by doing

2. x += some code


2.  x +=  some different code


  Above 1 works. 2 does not. Why is that?


Because there is always some little error in the value you're adding to 
x, since it's a floating point value calculated using transcendentals. 
If you're going to loop thousands of times, those little errors add up.


Sometime try measuring a mile using two 12-inch rulers, placing each one 
before picking up the previous. By the time you're done, you'll probably 
be off a hundred feet.





Both the same code.


Not at all the same.


The same variable is used with different names cause
some others were confused when they were the same.

  I hope this time I have answered correctly. No more attachments. (e mail
or otherwise. :) )



I can't necessarily understand the code since you use pygame and I'm not 
familiar with pygame.  In your itertools loop, you always reset the 
angle back to 100 degrees.


In your while loop, you issue a call to draw.circle().  Perhaps that's 
the working code you're talking about.




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


Re: [Tutor] if then statements

2015-04-29 Thread Dave Angel

On 04/28/2015 09:24 PM, Jacqueline G Solis wrote:

hello,

I keep getting a syntax error. Could you please explain why that happens and 
how to correct it.


def main ():
 print( "Welcome to Gonzo Burger!")
 order= int(input("Enter 1 if you want a hamburger,\
 or 2 if you want a cheeseburger:" ))
 if order == 1 :
print("order: 1")
 else:
print("Order: 2")

 drink=int(input("Thank you! Next, enter a 1 if you want a Coke,\
 or a 2 if you want a Sprite:")
 if drink == 1 :


The line before this one has a missing right paren at the end.  you 
close the input() function, but not the int() function.  So the next 
thing would have to be a comma, not a reserved token "if"



   print("Order: 1")
 else:
   print("Order: 2")

 print("Thank you! You ordered:")
 if order == 1:
   print("- Hamburger")
 else:
   print("- Cheeseburger")
 if drink == 1 :
   print("- Coke")
 else:
   print("- Sprite")

main ()




-Jackie
p.s: the error happens in the second if statement.


That's a good hint.  Better would be to include the full traceback with 
the error message, instead of a one-word summary.  No matter in this 
caswe, but it's a good habit to get into.


Incidentally, for syntax errors, it's pretty common for the real problem 
to be in the line before, or even earlier.  I'd assume this error 
pointed at the 'if'.  So you're really only going back one token.





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


Re: [Tutor] Fwd: circular movement in pygame

2015-04-28 Thread Dave Angel

On 04/28/2015 02:37 PM, diliup gabadamudalige wrote:

I thank all those who responded to my question

Here is the code that I had written.

When updating is applied to a surface object the rotation works but when it
is applied through a class to an object it goes wrong in about 3 rotations.
As far as I can see the code is the same. What is wrong? If you can correct
some code and show me would help.



By top-posting, you're messing up the readability of your response.  And 
by trying to use an attachment, you're messing up a large portion of the 
people reading this thread.


Post a simplified example, inline in your message, and *following* any 
quote you're using.


If your symptom is that the data diverges eventually from the intended 
trajectory, the problem is that you're accumulating errors.  Each point 
you do you're rounding the calculation by storing it in finite 
precision.  After enough roundoffs, the error becomes visible.


If you need to reliably move an object in a circle, you'll want to store 
the location in angular terms, center, radius, and angle.


Then each time around the loop, increment the angle by a non-rounded 
amount, and recalculate the x/y coordinates.



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


Re: [Tutor] Adding consecutive numbers

2015-04-27 Thread Dave Angel

On 04/27/2015 06:37 AM, Whom Isac wrote:

Hi, I am trying to build a python mini program to solve a math problem . I
wanted my program to ask two number from the operator and it can add those
number as a integer but as consecutive number in range. For example, if
num1 entry =1 & num2 entry = 100 , the program should be adding number from
1 to 100 together(which should equal to 5050). I thought that I could use
range() to use it for any given input from the user. However, there are few
argumentation error and I don't know why my bool function did not work in
while loop. Is there any way to make the program more concise.
I have uploaded my code file below. Please, note that I am fairly new to
programming and donot use complex modules, therefore, suggest me where I
was wrong with the code. I have checked for indentation error, however,
there were no error. So, I don't have any idea about the error.
Thanks.



You really shouldn't use attachments on this list, since many cannot see 
them.  I happen to be able to, so I'll try to comment.


In addition, each time you start a new thread, you should specify what 
Python version you're  trying to use, and what OS.


I never heard of an "argumentation error" so you'll really have to show 
the exact error.  Just copy/paste it from your user shell.  And exact 
for syntax errors, show the complete traceback.


Your code has many errors in it, and is unnecessarily complex.  At its 
simplest, you could use some simple algebra, and write:


x =int(input('Please enter your first number: '))
y =int(input('Please enter your second number: '))
print (x+y) * (y-x + 1) / 2

But if you really have to do the sum, then you need to build a list, and 
sum it.  That's not very hard either, since range() returns a list, and 
the sum() function is built-in.


But now, let's look at your code, and identify a few of the problems 
with it.


Your second line calls function interact(), which isn't defined yet. 
And in fact, when it is defined, it is spelled differently.  Put your 
top-level code (those two lines, anyway) at the *end* of the file, after 
the function(s) it needs are defined.


In function iteract (spelled inconsistently), you have a while True 
loop, with a break in the else clause.  But if xforever, since neither one changes, and if x>=y, you'll hit the break 
without defining z, so print z will throw an exception.


Also in that function you call a function called adding_sum_in(), but 
there's no function by that name.



In function find_range(), the first thing you do is trash your 
arguments.  So whatever else is in that function probably doesn't matter 
much.


In the loop:
for num in x:
x.append(num)

you're modifying the same thing you're looping over.  Not generally a 
good idea, so I have no idea if it'll do anything useful or not. 
Probably not.


return R = range({0},{1}).format(x,y)

is a syntax error.

def adding_sum_in_range(x, y):
c= find_range(x,y)
Total_sum = 0
for i in c:
Total_sum += i
return Total_sum

You have an indentation problem there, as this will return the first 
time through the loop.


def addition(x, y):
num1=(x)
num2=(y)
return num1+num2

Another indentation problem.

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


Re: [Tutor] Please disable “digest mode” before participating

2015-04-26 Thread Dave Angel

On 04/26/2015 08:07 AM, Ben Finney wrote:

Jim Mooney  writes:


On 25 April 2015 at 18:03, Ben Finney  wrote:


Digest mode should only ever be used if you know for certain you will
never be responding to any message.


That brings up a great shortcut if you use gmail. If you select some
text before reply that's All that is sent.


That doesn't reply to the original message. So it lacks the threading
provided by the “In-Reply-To” field, since you're not replying to the
original message.

It also lacks the correct Subject field, the correct attribution line,
etc. So, no, I still recommend strongly against responding to digest
messages — the information simply isn't there to compose a correct reply
message.

Instead, disable digest mode, and only after individual messages start
arriving at your mailbox can you participate properly, by replying to
them.



When I used to subscribe here using digest, and reading with 
Thunderbird, I'd see each message as an attachment.  To reply to one, I 
first opened the appropriate attachment, and did a Reply-List to it. 
WOrked well.


I took a quick look, for another forum which I monitor using the digest, 
and it looks like the same approach would still work.  For occasional 
posting.


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


Re: [Tutor] name shortening in a csv module output

2015-04-24 Thread Dave Angel

On 04/24/2015 07:34 PM, Jim Mooney wrote:


Apparently so. It looks like utf_8-sig just ignores the sig if it is
present, and uses UTF-8 whether the signature is present or not.

That surprises me.

--
Steve




I was looking things up and although there are aliases for utf_8 (utf8 and
utf-8) I see no aliases for utf_8_sig, so I'm surprised the utf-8-sig I
tried using, worked at all. Actually, I was trying to find the file where
the aliases are so I could change it and have utf_8_sig called up when I
used utf8, but it appears to be hard-coded.



I wouldn't use utf-8-sig for output, however, as it puts the BOM in the 
file for others to trip over.


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


Re: [Tutor] name shortening in a csv module output

2015-04-23 Thread Dave Angel

On 04/23/2015 05:08 PM, Mark Lawrence wrote:


Slight aside, why a BOM, all I ever think of is Inspector Clouseau? :)



As I recall, it stands for "Byte Order Mark".  Applicable only to 
multi-byte storage formats  (eg. UTF-16), it lets the reader decide 
which of the formats were used.


For example, a file that reads

   fe ff 41 00 42 00

might be a big-endian version of UTF-16

while
   ff fe 00 41 00 42

might be the little-endian version of the same data.

I probably have it all inside out and backwards, but that's the general 
idea.  If the BOM appears backwards, you switch between BE and LE and 
the data will make sense.



The same concept was used many years ago in two places I know of. 
Binary files representing faxes had "II" or "MM" at the beginning.


But the UCSD-P system program format used a number (I think it was 0001) 
which would decode wrong if you were on the wrong processor type.  The 
idea was that instead of coding an explicit check, you just looked at 
one piece of data, and if it was wrong, you had to swap all the 
byte-pairs.  That way if you read the file on the same machine, no work 
was needed at all.


Seems to me the Java bytecode does something similar, but I don't know. 
 All of these are from memory, and subject to mis-remembering.



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


Re: [Tutor] name shortening in a csv module output

2015-04-23 Thread Dave Angel

On 04/23/2015 02:14 PM, Jim Mooney wrote:


By relying on the default when you read it, you're making an unspoken
assumption about the encoding of the file.

--
DaveA



So is there any way to sniff the encoding, including the BOM (which appears
to be used or not used randomly for utf-8), so you can then use the proper
encoding, or do you wander in the wilderness? I was going to use encoding =
utf-8 as a suggested default. I noticed it got rid of the bom symbols but
left an extra blank space at the beginning of the stream. Most books leave
unicode to the very end, if they mention the BOM at all (mine is at page
977, which is still a bit off ;')



That's not a regular blank,  See the link I mentioned before, and the 
following sentence:


""" Unfortunately the character U+FEFF had a second purpose as a ZERO 
WIDTH NO-BREAK SPACE: a character that has no width and doesn’t allow a 
word to be split. It can e.g. be used to give hints to a ligature 
algorithm. """


To automatically get rid of that BOM character when reading a file, you 
use utf-8-sig, rather than utf-8.  And on writing, since you probably 
don't want it, use utf-8.


As for guessing what encoding was used, the best approach is to ask the 
person/program that wrote the file.  Or read the specs.  And once you 
figure it out, fix the specs.


With a short sample, you're unlikely to guess right.  That's because 
ASCII looks the same in all the byte-encoded formats.  (Not in the 
various *16* and *32* formats, as they use 2 bytes or 4 bytes each)  If 
you encounter one of those, you'll probably see lots of null bytes mixed 
in a consistent pattern.



Consider the 'file' command in Linux.  I don't know of any Windows 
equivalent.


If you want to write your own utility, perhaps to scan hundreds of 
files, consider:


  http://pypi.python.org/pypi/chardet
  http://linux.die.net/man/3/libmagic
  https://github.com/ahupp/python-magic

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


Re: [Tutor] name shortening in a csv module output

2015-04-23 Thread Dave Angel

On 04/23/2015 06:37 AM, Jim Mooney wrote:

..


Ï»¿

is the UTF-8 BOM (byte order mark) interpreted as Latin 1.

If the input is UTF-8 you can get rid of the BOM with

with open("data.txt", encoding="utf-8-sig") as csvfile:



Peter Otten

I caught the bad arithmetic on name length, but where is the byte order
mark coming from? My first line is plain English so far as I can see - no
umlauts or foreign characters.
first_name|last_name|email|city|state or region|address|zip

Is this an artifact of csv module output, or is it the data from
generatedata.com, which looks global? More likely it means I have to figure
out unicode ;'(


A file is always stored as bytes, so if it's a text file, it is always 
an encoded file (although if it's ASCII, you tend not to think of that 
much).


So whatever program writes that file has picked an encoding, and when 
you read it you have to use the same encoding to safely read it into text.


By relying on the default when you read it, you're making an unspoken 
assumption about the encoding of the file.


There are dozens of common encodings out there, and anytime you get the 
wrong one, you're likely to mess up somewhere, unless it happens to be 
pure ASCII.


The BOM is not supposed to be used in a byte encoded file, but Notepad, 
among other programs does.  So it happens to be a good clue that the 
rest of the file is encoded in utf-8.  If that's the case, and if you 
want to strip the BOM, use utf-8-sig.


Note:  the BOM may be legal in utf-8 now, but it was originally intended 
to distinguish the UTF-32-BE from UTF-32-LE, as well as UTF-16-BE from 
UTF-16-LE.


https://docs.python.org/2/library/codecs.html#encodings-and-unicode

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


Re: [Tutor] enhanced subtration in an exponent

2015-04-21 Thread Dave Angel

On 04/20/2015 08:44 PM, Jim Mooney wrote:

Why does the compiler choke on this? It seems to me that the enhanced
subtraction resolves to a legitimate integer in the exponent, but I get a
syntax error:

B = '11011101'
sum = 0
start = len(B)
for char in B:
 sum += int(char) * 2**(start -= 1) ## syntax error

print(sum)



As others have said, the augmented assignment, like the regular 
assignment, is not permissible inside an expression.  It is a type of 
statement.


You could solve this easily enough by:


B = '11011101'
sum = 0
start = len(B)
for index, char in enumerate(B):
sum += int(char) * 2**(start - index)

print(sum)


But I'd think that:

B = '11011101'
sum = 0
for char in B:
sum = sum * 2 + int(char)

print(sum)

reads much better, as well as being much faster.



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


Re: [Tutor] introspection

2015-04-21 Thread Dave Angel

On 04/21/2015 01:21 AM, Danny Yoo wrote:

What's supposed to happen in this situation?


##
class Person(object):
 def __init__(self): pass

j = Person()
john = j
jack = j
##

What single name should we get back from the single Person object
here?  "j", "john", or "jack"?



And what name should you get from the second Person() object created here?

mylist = [Person(), Person(), Person()]




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


Re: [Tutor] bin to dec conversion puzzlement

2015-04-20 Thread Dave Angel

On 04/20/2015 04:15 PM, Jim Mooney wrote:

  The key is that the result gets multiplied by 2 each time


so for an N bit number the leftmost digit winds up being
effectively 2**N, which is what you want.





Alan G



Ah, the light dawns once it was restated. It would be even simpler if you
could multiply each element of the binary number by it's respective power
of two, and sum them all at once. I hear Py 3.5 will have vector abilities.
I wonder it if would do something like that.


It's important to understand these conversion methods, or I would have 
earlier mentioned that you can convert from a binary string simply by


x = int("1011", 2)

No loop needed.


But if you need a loop for an analagous algorithm, find a way to either 
minimize the number of times through the loop, or to reduce the work 
done in each loop.


Ben's algorithm is much simpler than the one in the book you're reading.

binary_text = '11011101'
result = 0

for binary_digit in binary_text:
# Accumulate powers of 2 for each digit.
result = result * 2 + int(binary_digit)

print(result)

But more importantly, it's much simpler than calculating various powers 
of two and multiplying the various coefficients by them, and somehow 
"sum them all at once".



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


Re: [Tutor] lists, name semantics

2015-04-19 Thread Dave Angel

On 04/19/2015 06:28 PM, Joel Goldstick wrote:

On Sun, Apr 19, 2015 at 6:23 PM, boB Stepp  wrote:

On Sun, Apr 19, 2015 at 4:05 PM, Dave Angel  wrote:

On 04/19/2015 03:08 PM, boB Stepp wrote:





Or is the real point that we are adding an abstraction
layer so we don't even have to think about where objects are
physically stored in RAM?



Somebody keeps track, but the address is not necessarily constant, and not
necessarily stored in any references.  The references (bindings) are
abstract, and the details are unimportant to the user.  For example, the
jython system does not use addresses at all.  And an object gets moved
around from time to time without its references knowing it.


The last sentence in this paragraph has me intrigued. Why would an
object, once it has been created, be moved? What practical benefit
does doing this give?

boB


I'm guessing memory management.  You want to have large contiguous
blocks of memory available for large objects.  If a small object is
surrounded by available memory, you might want to move it to some
smaller empty spot.


Good answer.  The java jvm garbage collector is free to move blocks 
around to defrag the free space.


FWIW, I'm told the ID value used is a simple integer, that indexes a 
list containing the actual addresses.


So in this case, the binding value is an integer, not an address.

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


Re: [Tutor] lists, name semantics

2015-04-19 Thread Dave Angel

On 04/19/2015 03:08 PM, boB Stepp wrote:

On Sun, Apr 19, 2015 at 6:47 AM, Dave Angel  wrote:

On 04/19/2015 12:07 AM, boB Stepp wrote:


[...]


I hope this is helpful, and, if there are any misstepps, that when
they are revealed both of our understandings will be enhanced!



Some of your knowledge of other languages is leaking into your explanation.
When we talk of the language Python, we need to distinguish between how
CPython happens to be implemented, how other Python implementations happen
to be created, and how C++ (for example) implements similar things.  Some of
the above use pointers, some do not.  The language Python does not.


I actually was being deliberately  *imprecise* in my use of technical
terminology.  But I see below that there are some nuances I need to
learn...


So especially when talking of inner lists, we need to clarify a few things.

An object has an identity, not a location.  That identity can be checked
with the 'is' operator, or the id() function.  But it exists all the time.


But the object, in order to exist, must be stored in RAM somewhere,
doesn't it?


Or in a swap file, a disk file, or some other media.


Or is the real point that we are adding an abstraction
layer so we don't even have to think about where objects are
physically stored in RAM?


Somebody keeps track, but the address is not necessarily constant, and 
not necessarily stored in any references.  The references (bindings) are 
abstract, and the details are unimportant to the user.  For example, the 
jython system does not use addresses at all.  And an object gets moved 
around from time to time without its references knowing it.



So I am the object referenced by "boB" and
we don't care what my precise (x, y, z) coordinates are relative to
the planet Earth. If we need to find me or modify me we use my label,
"boB", to access me?


No, we use one of your many labels to find you.  And if no labels exist, 
you quietly cease to exist (garbage collection).  But understand that a 
"label" in this sense need not be some alpha string.  It might be a slot 
in some collection, like the way I described list.



Variables, as you say, do not contain an object, they reference it.  And the
formal term for that is binding.  A name is bound to an object, to one
object, at a time.

Now some objects have attributes, which is to say names, and those
attributes are bound to other objects.  So if we define a class, and have an
instance of that class, and the instance has attributes, we can do something
like:
 obj.inst_name

and get the particular attribute.

Still other objects have unnamed bindings.  The canonical example is a list.
A list object has a bunch of bindings to other objects.  Even though each
binding doesn't have a specific name, it nevertheless exists.  And in this
case we use integers to specify which of those bindings we want to follow.
And we use a special syntax (the square bracket) to indicate which of these
we want.


Ah, "unnamed bindings" was the concept I was talking around. I
realized these were there and were referenced by the square bracket
syntax, but I did not know what to call the concept.

[...]


At this point, it should be clear what a shallow copy means.  If the
original list's oneth item was a binding to another list object, *that* list
object does NOT get copied.

I don't like the term "inner list",  but I don't know if it's incorrect.
It's just misleading, since to the slice operation, the fact that it's a
list is irrelevant.  It's just an object whose binding is to be copied.


So the real point here is that there are two distinct copying
mechanisms, deep and shallow. The "inner list" could just have been
any other type of object, though if it had been an immutable type it
would not have made Peter's original interesting point.


The distinction between deep and shallow was already made, by better 
people than I.  I was trying to explain it in terms of a working model 
that would let you predict what will happen in each circumstance.  A 
slice only copies the bindings in the list, it doesn't care what they 
are bound to.  It's shallow because it's shallow.




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


Re: [Tutor] lists, name semantics

2015-04-19 Thread Dave Angel

On 04/19/2015 12:07 AM, boB Stepp wrote:

.
Before Peter changed one of these

changeable objects, he had:

a = [1, ["x", "y"], 3]
b = a[:]

Now BOTH a[1] and b[1] now identify the location of the inner list
object, ["x", "y"] . Apparently, Python, in its ever efficient memory
management  fashion, when it creates the new object/piece of data
a[:], it sees no need to duplicate the inner list object, ["x", "y"],
but instead creates another identifier/pointer/reference to this
object's location. But since this inner list object is mutable, when
you change "y" to "hello!" in b, you also change it in a because both
a[1][1] and b[1][1] reference/point to the exact same storage location
where this element of the inner list is actually stored.

I hope this is helpful, and, if there are any misstepps, that when
they are revealed both of our understandings will be enhanced!



Some of your knowledge of other languages is leaking into your 
explanation.  When we talk of the language Python, we need to 
distinguish between how CPython happens to be implemented, how other 
Python implementations happen to be created, and how C++ (for example) 
implements similar things.  Some of the above use pointers, some do not. 
 The language Python does not.


So especially when talking of inner lists, we need to clarify a few things.

An object has an identity, not a location.  That identity can be checked 
with the 'is' operator, or the id() function.  But it exists all the time.


Variables, as you say, do not contain an object, they reference it.  And 
the formal term for that is binding.  A name is bound to an object, to 
one object, at a time.


Now some objects have attributes, which is to say names, and those 
attributes are bound to other objects.  So if we define a class, and 
have an instance of that class, and the instance has attributes, we can 
do something like:

obj.inst_name

and get the particular attribute.

Still other objects have unnamed bindings.  The canonical example is a 
list.  A list object has a bunch of bindings to other objects.  Even 
though each  binding doesn't have a specific name, it nevertheless 
exists.  And in this case we use integers to specify which of those 
bindings we want to follow.  And we use a special syntax (the square 
bracket) to indicate which of these we want.


So let's take the simplest example:

mylist = ["a", "b"]

the name mylist is bound to a list object, which has two numbered 
bindings, called 0 and 1.  That object's  [0] binding is to a separate 
object "a".  And the [1] binding is to a separate object "b"


There is another shorthand called a slice, which looks like [start, len, 
step] which lets us construct a *new* list from our list.  And using 
defaults for all three terms lets us copy the list.  But let's look at 
what the copy means:


newlist = mylist[:]
-->  mylist[0, 2, 1]

This constructs a new list from the present one, where the zeroth 
location is bound to whatever object the first list's zeroth location 
was bound to.  And so on for the oneth location, the twoth, etc.


Only one new list object is built, and no new objects are made for it. 
It just gets new bindings to the same things the first list had.


At this point, it should be clear what a shallow copy means.  If the 
original list's oneth item was a binding to another list object, *that* 
list object does NOT get copied.


I don't like the term "inner list",  but I don't know if it's incorrect. 
 It's just misleading, since to the slice operation, the fact that it's 
a list is irrelevant.  It's just an object whose binding is to be copied.


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


Re: [Tutor] How (not!) lengthy should functions be?

2015-04-18 Thread Dave Angel

On 04/18/2015 03:01 PM, boB Stepp wrote:


As I final note I want to emphasize that I am not writing a program to
*create* a treatment plan. Nor am I writing a program that can *alter*
an existing treatment plan. It is merely reading output from the
treatment plan and evaluating that output against agreed upon best
practice numbers. If this program never gets implemented it will
change nothing in how plans are created and implemented. If it does



I'd still point out that eventually people will presumably get to 
believing in your program.  They'll subconsciously assume that if they 
mess up, the program will notice, so they don't have to be as careful as 
they otherwise would.


There's nothing you can do about this; it's human nature.  So I claim 
that making sure the advice your program offers has
  1) few bugs.  And what it has should be crashes, not just getting the 
wrong result.
  2) Careful wording of the messages to indicate the confidence level 
of the conclusion it's relating.



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


Re: [Tutor] lists, name semantics

2015-04-17 Thread Dave Angel

On 04/17/2015 11:51 PM, Ben Finney wrote:

Ben Finney  writes:


Bill Allen  writes:


If I have a list defined as my_list = ['a','b','c'], what is the is
differnce between refering to it as my_list or my_list[:]?


‘my_list’ is a reference to the object you've already described (the
existing object ‘['a', 'b', 'c']’).

‘my_list[:]’ is an operation that takes the original object and
creates a new one by slicing. In this case, the new object happens to
be equal to (but probably not identical to) the original, because of
the slice you specified.


To demonstrate how identity differs from equality, use the appropriate
comparison operators::

 $ python3

 >>> foo = ['a', 'b', 'c']

 >>> bar = foo # Bind the name ‘bar’ to the same object.
 >>> bar   # Show me the object referred to by ‘bar’.
 ['a', 'b', 'c']
 >>> bar == foo# Is the object ‘bar’ equal to the object ‘foo’?
 True
 >>> bar is foo# Is ‘bar’ referring to the same object as ‘foo’?
 True

 >>> baz = foo[:]  # Slice ‘foo’, creating a new list; bind ‘baz’ to that.
 >>> baz   # Show me the object referred to by ‘baz’.
 ['a', 'b', 'c']
 >>> baz == foo# Is the object ‘baz’ equal to the object ‘foo’?
 True
 >>> baz is foo# Is ‘baz’ referring to the same object as ‘foo’?
 False

References which compare identical *are the same* object, guaranteed.
Object identity almost always implies equality.

(“almost always” because some object types have unusual behaviour like
“the object is not equal to itself”. Don't fret about that though, these
exceptions are clearly defined when you find them.)


References which compare equal *may under some conditions* be identical.
This is *not* ever a promise, though, and you should never rely on it,
not even in the same session of a program.

Some of Python's internal optimisations depend on the fact that object
equality *does not* imply object identity. If you happen to notice some
operations producing the same object at one point in time, but the
documentation doesn't promise it, then treat that as an unpredictable
implementation detail and don't rely on it in your code.



Great description, if the OP really wants that level of detail.  But I 
think what he needs to know first is:


If you change foo, like   (untested)
foo[1] = "new"

then you'll see that bar also changes (since it's just another name for 
the exact same object).

>>> bar
['a', 'new', 'c']

But baz does not, since it's bound to a copy of the object.
>>> baz
['a', 'b', 'c'\
--
DaveA
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Unicode encoding and raw_input() in Python 2.7 ?

2015-04-17 Thread Dave Angel

On 04/17/2015 04:39 AM, Samuel VISCAPI wrote:

-BEGIN PGP SIGNED MESSAGE-
Hash: SHA256

Hi,

This is my first post to that mailing list if I remember correctly, so
hello everyone !



Welcome to the list.


I've been stuck on a simple problem for the past few hours. I'd just
like raw_input to work with accentuated characters.


That should mean you want to use unicode.


If you're using raw_input, then you must be using Python 2.x.  Easiest 
first step to doing things right in Unicode would be to switch to 
version 3.xBut I'll assume that you cannot do this, for the duration 
of this message.






For example:

firstname = str.capitalize(raw_input('First name: '))


If you're serious about Unicode, you're getting an encoded string with 
raw_input, so you'll need to decode it, using whatever encoding your 
console device is using.  If you don't know, you're in big trouble.  But 
if you're in Linux, chances are good that it's utf-8.




where firstname could be "Valérie", "Gisèle", "Honoré", etc...





I tried -*- coding: utf-8 -*-, u'', unicode(), but to no avail...



As Alan says, you're not tellins us anything useful.  "No avail" is too 
imprecise to be useful.   I'll comment on them anyway.


The coding statement applies only to literals you use in your source 
code.  It has nothing at all to do with the value returned by raw_input.


u'' likewise is used in your source code.  It has nothing to do with 
what the user may type into your program.


unicode() is a "function" that may decode a string received from 
raw_input, providing you know what the coding was.  You can also 
accomplish it by using the method str.decode().




I'm using str.capitalize and str.lower throughout my code, so I guess
some encoding / decoding will also be necessary at some point.


Those apply to strings.  But if you're doing it right, you should have 
unicode objects long before you apply such methods.  So you'd want the 
unicode methods  unicode.upper and unicode.lower




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


Re: [Tutor] Fraction - differing interpretations for number and string - presentation

2015-04-16 Thread Dave Angel

On 04/16/2015 01:24 PM, Jim Mooney wrote:


Is this "inaccurate"? Well, in the sense that it is not the exact true
mathematical result, yes it is, but that term can be misleading if you
think of it as "a mistake". In another sense, it's not inaccurate, it is
as accurate as possible (given the limitation of only having a certain
fixed number of bits).
--
Steve



---
Understood about the quondam inexactness of floating point bit
representation. I was just wondering why the different implementation of
representing it when using Fraction(float) as opposed to using
Fraction(string(float)).


You didn't use str(float), you used a simple str.  So there was no 
quantization error since it was never converted to binary floating 
point.  If you have a number that happens to be an exact decimal number, 
don't convert it via float().  Either convert it via Decimal() or 
convert it directly to fraction.



  In terms of user presentation, the string usage

has smaller numbers for the ratio, so it would be more understandable and
should, I assume, be chosen for GUI display.



Presumably you didn't read my message.  When you use a literal 1.64 in 
your code, you're telling the compiler to call the float() function on 
the token.  You've already forced the quantization error.  Nothing to do 
with the fraction class.


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


Re: [Tutor] Fraction - differing interpretations for number and string

2015-04-16 Thread Dave Angel

On 04/16/2015 08:11 AM, Dave Angel wrote:

On 04/16/2015 01:03 AM, Jim Mooney wrote:

Why does Fraction interpret a number and string so differently? They come
out the same, but it seems rather odd


from fractions import Fraction
Fraction(1.64)

Fraction(738590337613, 4503599627370496)

Fraction("1.64")

Fraction(41, 25)

41/25

1.64

738590337613 / 4503599627370496

1.64



When a number isn't an exact integer (and sometimes when the integer is
large enough), some common computer number formats cannot store the
number exactly.  Naturally we know about transcendentals, which cannot
be stored exactly in any base.  PI and E and the square-root of two are
three well known examples.

But even rational numbers cannot be stored exactly unless they happen to
match the base you're using to store them.  For example, 1/3 cannot be
stored exactly in any common base.


By "common" I mean 2, 8, 10, or 16.  Obviously if someone implemented a 
base 3 floating point package, the number would be simply  0.1



 In decimal, it'd be a repeating set
of 3's.  And whenever you stopped putting down threes, you've made an
approximation.
 0.33

Python defaults to using a float type, which is a binary floating point
representation that uses the special hardware available in most recent
computers.  And in fact, when you use a literal number in your source,
it's converted to a float by the compiler, not stored as the digits you
typed.

The number you specified in decimal, 1.64, is never going to be stored
in a finite number of binary bits, in a float.

 >>> from fractions import Fraction
 >>> from decimal import Decimal

 >>> y = 1.64
Conversion to float appens at compile time, so the value given to y is
already approximate.
roughly equivalent to the following
 >>> y = float("1.64")

 >>> Fraction(y)
Fraction(738590337613, 4503599627370496)

If you converted it in string form instead to Decimal, then the number
you entered would be saved exactly.

 >>> x = Decimal("1.64")
This value is stored exactly.

 >>> x
Decimal('1.64')

 >>> Fraction(x)
Fraction(41, 25)


Sometimes it's convenient to do the conversion in our head, as it were.
Since 1.64 is shorthand for  164/100, we can just pass those integers to
Fraction, and get an exact answer again.

 >>> Fraction(164, 100)
Fraction(41, 25)


Nothing about this says that Decimal is necessarily better than float.
It appears better because we enter values in decimal form and to use
float, those have to be converted, and there's frequently a loss during
conversion.  But Decimal is slower and takes more space, so most current
languages use binary floating point instead.

I implemented the math on a machine 40 years ago where all user
arithmetic was done in decimal floating point.  i thought it was a good
idea at the time because of a principle I called "least surprise." There
were roundoff errors, but only in places where you'd get the same ones
doing it by hand.

History has decided differently.  When the IEEE committee first met,
Intel already had its 8087 implemented, and many decisions were based on
what that chip could do and couldn't do.  So that standard became the
default standard that future implementations would use, whatever company.




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


Re: [Tutor] Fraction - differing interpretations for number and string

2015-04-16 Thread Dave Angel

On 04/16/2015 01:03 AM, Jim Mooney wrote:

Why does Fraction interpret a number and string so differently? They come
out the same, but it seems rather odd


from fractions import Fraction
Fraction(1.64)

Fraction(738590337613, 4503599627370496)

Fraction("1.64")

Fraction(41, 25)

41/25

1.64

738590337613 / 4503599627370496

1.64



When a number isn't an exact integer (and sometimes when the integer is 
large enough), some common computer number formats cannot store the 
number exactly.  Naturally we know about transcendentals, which cannot 
be stored exactly in any base.  PI and E and the square-root of two are 
three well known examples.


But even rational numbers cannot be stored exactly unless they happen to 
match the base you're using to store them.  For example, 1/3 cannot be 
stored exactly in any common base.  In decimal, it'd be a repeating set 
of 3's.  And whenever you stopped putting down threes, you've made an 
approximation.

0.33

Python defaults to using a float type, which is a binary floating point 
representation that uses the special hardware available in most recent 
computers.  And in fact, when you use a literal number in your source, 
it's converted to a float by the compiler, not stored as the digits you 
typed.


The number you specified in decimal, 1.64, is never going to be stored 
in a finite number of binary bits, in a float.


>>> from fractions import Fraction
>>> from decimal import Decimal

>>> y = 1.64
Conversion to float appens at compile time, so the value given to y is 
already approximate.

   roughly equivalent to the following
>>> y = float("1.64")

>>> Fraction(y)
Fraction(738590337613, 4503599627370496)

If you converted it in string form instead to Decimal, then the number 
you entered would be saved exactly.


>>> x = Decimal("1.64")
This value is stored exactly.

>>> x
Decimal('1.64')

>>> Fraction(x)
Fraction(41, 25)


Sometimes it's convenient to do the conversion in our head, as it were.
Since 1.64 is shorthand for  164/100, we can just pass those integers to 
Fraction, and get an exact answer again.


>>> Fraction(164, 100)
Fraction(41, 25)


Nothing about this says that Decimal is necessarily better than float. 
It appears better because we enter values in decimal form and to use 
float, those have to be converted, and there's frequently a loss during 
conversion.  But Decimal is slower and takes more space, so most current 
languages use binary floating point instead.


I implemented the math on a machine 40 years ago where all user 
arithmetic was done in decimal floating point.  i thought it was a good 
idea at the time because of a principle I called "least surprise." 
There were roundoff errors, but only in places where you'd get the same 
ones doing it by hand.


History has decided differently.  When the IEEE committee first met, 
Intel already had its 8087 implemented, and many decisions were based on 
what that chip could do and couldn't do.  So that standard became the 
default standard that future implementations would use, whatever company.


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


Re: [Tutor] Reference last email message...

2015-04-15 Thread Dave Angel

On 04/15/2015 07:47 PM, Ken G. wrote:

I just emailed that I was unable to correct a message in ModTools
so I went to Yahoo and made the change and then approved it.

Noticing it did not appear on the list, I checked the Activity Log
in Yahoo and it was marked Bounced!

Several days ago, we had another message correction and that
too, bounced.



It's conceivable that you're referring to:

https://pypi.python.org/pypi/modtools/1.0.2

But your message is so garbled that I have no idea how to respond.

You have a gmail address, but you're somehow involved with yahoo.

You refer to "the list," but never say if it's this one.

You refer to "message correction" but there's no standard way to modify 
a message on python-tutor once it's mailed or posted. So perhaps the 
message correction and the list you're referring to are somewhere else.


Python-tutor is a limited mailing list that only takes messages from 
those who have subscribed/joined.  So perhaps you have two different 
email addresses and you've registered using gmail, and are trying to 
post using yahoo.


In any case, if it is ModTools, this is the wrong list to post 
questions.  This list is intended for usage of the Python language and 
the standard library, and while other subjects are permissible, they're 
not as likely to get good responses.


I'd suggest you email to python-l...@python.org a new message, starting 
a new thread.  Be explicit about your question, supplying a URL when you 
refer to a 3rd party package, and giving python version and OS version. 
 Then show exactly what you've tried and what the result was, posting a 
full traceback if you got an exception.


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


Re: [Tutor] Changing a string number to another number

2015-04-15 Thread Dave Angel

On 04/15/2015 08:21 AM, Ken G. wrote:

When running the following code, I get the following
error code:

201504110102030405061
Traceback (most recent call last):
   File "Mega_Millions_Tickets_Change.py", line 11, in 
 datecode[20:21] = "0"
TypeError: 'str' object does not support item assignment


A 'str' object is immutable, which means simply that you cannot modify 
it in place.  All you can do is create a new str object, and rebind your 
variable to that new one.  That means that there are a number of things 
you cannot do directly to a string.  One of them is modifying a slice, 
as you're trying to do.





datecode = "201504110102030405061"
print datecode
if datecode[20:21] == "1":
 datecode[20:21] = "0"
print datecode




I can see that the first part of this is probably a standard datetime, 
and might suggest you convert it to one, and modify that as needed.  But 
you're so far to the right that I have to figure you're doing some 
custom encoding.


If you just want to replace a single character of a string, you could 
use the construct:


datecode = datecode[:20] + "0" + datecode[21:]

If you need something fancier, perhaps you can generalize it.

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


Re: [Tutor] Function not returning 05 as string

2015-04-13 Thread Dave Angel

On 04/13/2015 08:11 AM, Ken G. wrote:

I am sure there is an simple explanation but when I input
5 (as integer), resulting in 05 (as string), I get zero as the end
result. When running the code:

START OF PROGRAM:
Enter the 1st number:  5

05

0
END OF PROGRAM:

START OF CODE:
import sys

def numberentry():
 print
 number01 = raw_input("Enter the 1st number:  ")
 if number01 == "0":
 sys.exit()
 if  len(number01) == 1:
 number01 = "0" + number01
 print
 print number01
 return(number01)

number01 = 0


What is this line intended to do?


numberentry()


Where are you intending to store the return value?  Currently, you're 
just throwing it away.



print
print number01


This variable has no relation to the one in the function.  In fact, I'd 
recommend you use a different name, to make that clear.



END OF CODE:



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


Re: [Tutor] Why is it invalid syntax to have a particular dictionary value as an argument?

2015-04-08 Thread Dave Angel

On 04/07/2015 10:16 PM, boB Stepp wrote:


Despite Mark's warning, I feel I must see if I understand what is going on here.

Switching to Py 3.4 since I am now at home:

Python 3.4.3 (v3.4.3:9b73f1c3e601, Feb 24 2015, 22:44:40) [MSC v.1600
64 bit (AMD64)] on win32
Type "copyright", "credits" or "license()" for more information.

d = {'a': '123'}
def func(s=d['a']):

   print(s)
   print(d['a'])


func()

123
123

d['a'] = 'new value'
func()

123
new value

I added an additional print to the function to show the dictionary
entry's behavior.

First, my current understanding is that this form of the function does
not object to the presence of d['a'] in its parameter list because s
is the real parameter, d['a'] is its default value, but s is not
actually evaluated until run time.


s is not evaluated till the print statement.  s is *bound* at function 
call time.  And at that time it is either bound to the object passed by 
the caller, or to the default object.


In a simple assignment statement:
   a = b + 6

the expression on the right is evaluated.  The name on the left is not 
evaluated, it is bound to.  So we say

   "a is bound to the result of the expression b+6"



But once s *is* evaluated, it stores  a reference to the original


  s is bound to the expression ''default_object'', which is to say it 
copies the same reference that the default object stored earlier.  So it 
is bound to '123'



object, '123'. Changing d['a'] outside the function to a new value
does not alter the fact that s is storing the very same reference to
'123'. After reassigning d['a'] to point to the new object 'new
value', a new call to func() shows s still referencing the original
object and d['a'] referencing the new object. Is my comprehension of
these details correct? If yes, this is why I must constantly remind
myself that identifiers store references to objects, and that some
objects are mutable and some aren't, and these Python facts of life
are constantly challenging my old FORTRAN <= 77 ways of thinking...
~(:>))




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


Re: [Tutor] Why is it invalid syntax to have a particular dictionary value as an argument?

2015-04-06 Thread Dave Angel

On 04/06/2015 03:20 PM, Emile van Sebille wrote:

On 4/6/2015 7:54 AM, boB Stepp wrote:

Python 2.7.8 (default, Jun 30 2014, 16:03:49) [MSC v.1500 32 bit
(Intel)] on win32
Type "copyright", "credits" or "license()" for more information.

d = {'n': 'Print me!'}
d

{'n': 'Print me!'}

d['n']

'Print me!'

def func(d['n']):

SyntaxError: invalid syntax

def func(d):

 print d['n']


func(d)

Print me!

The plain text does not show it, but in the invalid syntax the "[" is
highlighted red.

Why is it invalid syntax to pass a particular dictionary value in a
function? Or does it require a different form to do so?


Maybe this form helps:

Python 2.7.6 (default, Mar 22 2014, 22:59:56)
[GCC 4.8.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
 >>> d = {'a':'123'}
 >>> def func(s=d['a']):
...   print s
...
 >>> func()
123



Only if you know that nobody is going to be changing d.

>>> d = {"a":"123"}
>>> def func(s=d["a"]):
... print s
...
>>> d["a"] = "new value"
>>> func()
123
>>>


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


Re: [Tutor] Why is it invalid syntax to have a particular dictionary value as an argument?

2015-04-06 Thread Dave Angel

On 04/06/2015 12:43 PM, boB Stepp wrote:



I was breaking down longer functions into smaller ones. Along the way
I noticed I was passing an entire dictionary from one function to
another. I only needed to pass one particular value, not the whole
dictionary, so that is how I got into the issue I asked about.


Just to reinforce something you probably know well, passing a dictionary 
takes no more memory or time than passing an item from that dictionary. 
 The real choice is whether the called function should dealing with a 
single item or with a dictionary.  It would have a different name in 
each case, and a different set of reuse possibilities.


I know the following example abuses the dictionary, using it as though 
it were an instance of class Person.  It's just what popped into my head.


def check_person(person):
if person["name"] in list_of_preferred:
 do_something...
 return True
return False

def check_name(name):
if name in list_of_preferred:
 do_something...
 return True
return False

In the first case, the function would be able use other elements of the 
dictionary, like "email_address" or "phone_number".


In the second case, you could call the function from someplace that has 
only names, and isn't worried about what dict the name might be part of.



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


Re: [Tutor] Why is it invalid syntax to have a particular dictionary value as an argument?

2015-04-06 Thread Dave Angel

On 04/06/2015 10:54 AM, boB Stepp wrote:

Python 2.7.8 (default, Jun 30 2014, 16:03:49) [MSC v.1500 32 bit
(Intel)] on win32
Type "copyright", "credits" or "license()" for more information.

d = {'n': 'Print me!'}
d

{'n': 'Print me!'}

d['n']

'Print me!'

def func(d['n']):

SyntaxError: invalid syntax

def func(d):

 print d['n']


func(d)

Print me!

The plain text does not show it, but in the invalid syntax the "[" is
highlighted red.

Why is it invalid syntax to pass a particular dictionary value in a
function? Or does it require a different form to do so?


You're getting confused between defining a function and calling one.

For Python 2.7, see:

https://docs.python.org/2/reference/compound_stmts.html#function-definitions


When defining a function, you provide (not pass) the formal parameters, 
and they must be simple names.  Those names will end up being local 
variables when the function is finally called.


(The only sort-of exception to this in 2.7 is when you define a default 
argument to a function.  In that case, the parameter still must be a 
valid python variable name, but the default value can be an arbitrary 
expression, as long as it's valid at the time of function definition.)



Once the function is being called, then you can use an arbitrary 
expression for your argument.  The results of that expression is bound 
to the formal parameter specified above.


Further reading:
https://docs.python.org/2/faq/programming.html#faq-argument-vs-parameter
https://docs.python.org/2/glossary.html#term-parameter
https://docs.python.org/2/glossary.html#term-argument


Now, it's possible that what you're trying to do is something that can 
be accomplished some other way.  So please elaborate on your purpose in 
using the syntax you did.  Or supply a small program that shows a 
function being defined and called, that would give meaning to the syntax 
you're trying.

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


Re: [Tutor] Functional Programming in Python

2015-04-04 Thread Dave Angel

On 04/04/2015 09:53 PM, WolfRage wrote:






(Pointing to the different classes. Since C++ has virtual methods but
Python does not?)


I'd say that all methods in Python are virtual, except for those which 
are classmethod or staticmethod.



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


Re: [Tutor] Use of "or" in a lambda expression

2015-04-04 Thread Dave Angel

On 04/04/2015 05:57 PM, boB Stepp wrote:

On Sat, Apr 4, 2015 at 3:35 PM, Alan Gauld  wrote:

He could have done it in various other ways too:

eg.
lambda : all(print('Hello lambda world!'), sys.exit() )


Is this what you meant? Because print will always return False. Or did
you actually mean:

lambda: any(print('Hello lambda world!'), sys.exit())


But the OR style is established as a kind of idiom,
not just in Python but several other languages too.


So this is not unusual for Python. BTW, what are some of the other
languages where this type of expression might be commonly used?




I don't think I've ever seen it used in Python.  But it's quite common 
in Perl scripts and bash scripts that I've seen.  In the case of bash, 
one might do something like:


 prog1   &&   prog2

and prog2 gets executed only if prog1 had a successful completion

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


Re: [Tutor] Request review: A DSL for scraping a web page

2015-04-02 Thread Dave Angel

On 04/02/2015 03:49 PM, Albert-Jan Roskam wrote:


-
On Thu, Apr 2, 2015 1:17 PM CEST Alan Gauld wrote:


On 02/04/15 12:09, Dave Angel wrote:


Ah, Jon Bentley (notice the extra 'e').  I should dig out my *Pearls
books, and have a trip down memory lane.  I bet 95% of those are still
useful, even if they refer to much earlier versions of language(s).


Yes, the Pearls books should be required reading for all new programmers. The 
lessons are pretty timeless, it's only the
languages that change - and most of his examples seem to be
in a kind of pseudo Pascal dialect rather than real code anyway.

I believe they've been re-released as a single volume now.


Is this the book you are referring to?
http://www.amazon.com/Programming-Pearls-2nd-Edition-Bentley/dp/0201657880

Thanks!


That is a new edition of "Programming Pearls", but I can't tell from its 
description if it also includes "More Programming Pearls: Confessions of 
a Coder"


If the two were merged, I don't spot it any place on Amazon.

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


Re: [Tutor] New to Programming: TypeError: coercing to Unicode: need string or buffer, list found

2015-04-02 Thread Dave Angel

On 04/02/2015 08:28 AM, Saran Ahluwalia wrote:

Good Morning:

I understand this error message when I run this code. However, I am curious
to know what the most pythonic way is to convert  the list to a string? I
use Python 2.7.

"Traceback (most recent call last):
before = dict([(f, None) for f in os.listdir(dirlist)])
TypeError: coercing to Unicode: need string or buffer, list found"



>
> The sample code that I am trying to run is:
>
> path = "/Users/Desktop/Projects/"
> dirlist = os.listdir(path)
> before = dict([(f, None) for f in os.listdir(dirlist)])


You have two calls to listdir in the code you quote here.  Once you've 
called os.listdir(path)  you get back a list of filenames.  Why you then 
call os.listdir again on that list I have no clue.  And I also have no 
idea what you think the dict is going to do.





def main(dirlist):
 while True:
 time.sleep(10) #time between update check
 after = dict([(f, None) for f in os.listdir(dirlist)])
 added = [f for f in after if not f in before]
 if added:
 print('Successfully added new file - ready to validate')
if __name__ == "__main__":
 main()


You didn't run that code, as this call to main() passes no arguments. 
Last time I saw your whole file, it had two separate  if __name__ == 
"__main__" clauses.  So you'd better make sure one of them is commented 
out, or it'll keep confusing you.


First thing is to pick better names.  And second is to add a comment to 
each function as to what it expects for arguments.  main() expects a 
directory name, so rename the dirlist variable to something like path.


Then figure out what the argument to main() should look like.  it should 
not be  sys.argv[1:], as that's a list.  You want a single item on the 
command line specifying the path.



This whole thing with 'before' and 'after' is the long way around. 
Since you're going to move files from this directory after you analyze 
them, all you need to do is call os.listdir again each time through the 
loop.  Anything you find will be new, by definition.


Then once you have your list, you do NOT want to loop through it, as 
you're going to be calling a function (already written by you) that 
wants a list of filenames.


Incidentally you posted some code earlier, in yet another new thread, 
that calls copyfile() from the function move_to_failure_folder(). 
Shouldn't that function be called movefile()?  and shouldn't it use a 
different shutil function?


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


Re: [Tutor] Request review: A DSL for scraping a web page

2015-04-02 Thread Dave Angel

On 04/02/2015 07:17 AM, Alan Gauld wrote:

On 02/04/15 12:09, Dave Angel wrote:


Ah, Jon Bentley (notice the extra 'e').  I should dig out my *Pearls
books, and have a trip down memory lane.  I bet 95% of those are still
useful, even if they refer to much earlier versions of language(s).


Yes, the Pearls books should be required reading for all new
programmers. The lessons are pretty timeless, it's only the
languages that change - and most of his examples seem to be
in a kind of pseudo Pascal dialect rather than real code anyway.

I believe they've been re-released as a single volume now.



There was somewhere in one of the books a list of 'good practice,' 
including an item something like:


Solve the right problem.

There's a world of wisdom in that one alone.

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


Re: [Tutor] Request review: A DSL for scraping a web page

2015-04-02 Thread Dave Angel

On 04/02/2015 06:41 AM, Alan Gauld wrote:

On 02/04/15 10:50, Dave Angel wrote:

On 04/02/2015 04:22 AM, Alan Gauld wrote:


DSL?


This is "Domain Specific Language".  This is a language built around a
specific problem domain,


Ah, Thanks Dave!
I am used to those being called simply "Little languages" after the
famous Jon Bently ACM article that introduced the concept.

http://c2.com/cgi/wiki?LittleLanguage

DSL especially confused me because we had an in-house language
called that, but it wasn't available outside so I didn't see
how the OP could be using it :-)



Ah, Jon Bentley (notice the extra 'e').  I should dig out my *Pearls 
books, and have a trip down memory lane.  I bet 95% of those are still 
useful, even if they refer to much earlier versions of language(s).


I also should find myself a modern Forth system, and see how that's 
evolved over time.  Years ago I was an observer on the ANSI Forth 
standard, as well as newsletter editor for the local FIG.


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


Re: [Tutor] Request review: A DSL for scraping a web page

2015-04-02 Thread Dave Angel

On 04/02/2015 04:22 AM, Alan Gauld wrote:


DSL?



This is "Domain Specific Language".  This is a language built around a 
specific problem domain, in order to more easily express problems for 
that domain than the usual general purpose languages.


I was a bit surprised to find few google matches, but here's one:

http://www.pcmag.com/encyclopedia/term/41694/domain-specific-language

and of course

http://en.wikipedia.org/wiki/DSL_(disambiguation)



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


Re: [Tutor] Python Idioms?

2015-04-01 Thread Dave Angel

On 04/01/2015 12:50 AM, Jim Mooney wrote:

I'm looking at this and can't see how it works, although I understand
zipping and unpacking. The docs say it's a Python idiom. Does "idiom" mean
it works in a special way so I can't figure it out from basic principles?
It looks to me like the iterator in the list gets doubled, so the zip
should make it [(1,1),(2,2),(3,3),... ], not [(1,2),(3,4),...]

What am I missing here?


s = [1,2,3,4,5,6,7,8]
list(zip(*[iter(s)]*2))
[(1, 2), (3, 4), (5, 6), (7, 8)]


https://docs.python.org/3/library/functions.html#zip




In that same thread, Peter Otten posted the following, which I think is 
probably a bit clearer:



>>> flat_pairs = ['broadcast', '"d8on"', 'broadcast', '"d11on"']
>>> it = iter(flat_pairs)
>>> pairs = list(zip(it, it))
>>> pairs

That does exactly the same thing, but in the first one you can replace 
the '2' with a variable, to make variable sized tuples.


In both cases, the trick is that the same iterator is used twice in the 
expression, so even though zip is taking one from each, there are no 
duplications.


If you know the original data is a list, or at least that it can do 
slices, then you can do Alan's suggestion:



zip(s[::2],s[1::2])

Or you could try:

from itertools import islice

pairs = zip(islice(s, 0, , 2), islice(s, 1, , 2))



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


Re: [Tutor] Unexpected results using enumerate() and .split()

2015-03-31 Thread Dave Angel

On 03/31/2015 04:23 PM, boB Stepp wrote:

The following behavior has me stumped:

Python 2.7.8 (default, Jun 30 2014, 16:03:49) [MSC v.1500 32 bit
(Intel)] on win32
Type "copyright", "credits" or "license()" for more information.

L = ['#ROI:roi_0', '#TXT:text_0', '#1:one^two^three']
for i, item in enumerate(L):

 subitems = item.split(':')
 if subitems[0] == '#ROI':
 print subitems[1]
 if subitems[0] == '#TXT':
 print subitems[1]
 if subitems[0] == '#1' or '#2':


I think what you meant here was:
   if subitems[0] == "#1" or subitems[0] == "#2":


 print subitems[1]


Study the first expression and see if you can figure out what the 
difference is.  If it's not clear, then make a simpler program just to 
test a compound if, and we'll all talk about it.




roi_0ail
roi_0
text_0
text_0
one^two^three




My desired output was:

roi_0
text_0
one^two^three

Oh, wonderful founts of wisdom, where is my understanding lacking?

BTW, I copied and pasted the above into my Gmail window, but it
removed the indentation that was present in the interpreter. I added
spaces manually to get it appear as it did in the interpreter. Anyone
know why Gmail does that to my copy and paste?



Buggy, I guess.  Why not use a program like Thunderbird, which is free 
and available on most PC operating systems?


(Unfortunately, it's not on Android)

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


Re: [Tutor] Dynamic naming of lists

2015-03-31 Thread Dave Angel

On 03/31/2015 10:00 AM, Ian D wrote:

Hi

I have a list that I am splitting into pairs of values. But the list is dynamic 
in size. It could have 4 values or 6 or more.

I originally split the list into pairs, by using a new list and keep a pair in 
the old list by just popping 2 values. But if the list is longer than 4 values. 
I cannot do this. I can only envision I would need to dynamically create lists. 
How would I do this?

while returned_list_of_items:
 for i in range(1):
 new_list.append(returned_list_of_items.pop(0)) #pop first value and 
append
 new_list.append(returned_list_of_items.pop(0)) #pop second value and 
append



It'd really be a lot clearer if you gave one or more examples of input 
and output data.  Like you want list [1,2,3,4]  to become [ (1,2), (3,4) ]


I'll guess you want a list of two-tuples.  It so happens there's a nice 
built-in for the purpose.


https://docs.python.org/3/library/functions.html#zip

>>> s = [1,2,3,4,5,6,7,8]
>>> list(zip(*[iter(s)]*2))
[(1, 2), (3, 4), (5, 6), (7, 8)]



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


Re: [Tutor] trying to convert pycurl/html to ascii

2015-03-29 Thread Dave Angel

On 03/29/2015 09:49 PM, bruce wrote:

Hi.

Doing a quick/basic pycurl test on a site and trying to convert the
returned page to pure ascii.


You cannot convert it to pure ASCII.  You could replace all the invalid 
characters with some special one, like question marks.  But I doubt if 
that's what you really want.




The page has the encoding line




That would mean you should use 8859 in your decode.



The test uses pycurl, and the StringIO to fetch the page into a str.

pycurl stuff
.
.
.
foo=gg.getBuffer()

-at this point, foo has the page in a str buffer.


What's happening, is that the test is getting the following kind of error/

UnicodeDecodeError: 'utf8' codec can't decode byte 0xa0 in position 20:
invalid start byte


That's not the whole error.  You need to show the whole stack trace, not 
just a single line.  It would also be really useful if you showed the 
lines between the  foo= line and the one that gets the error.





The test is using python 2.6 on redhat.


Very good to tell us that.  It makes a huge difference.


I've tried different decode functions based on different
sites/articles/stackoverflow but can't quite seem to resolve the issue.



Pick one, show us the code, and show us the full error traceback, and 
somebody can help.  As it stands all I can tell us is a decode takes a 
byte string and an encoding name, and produces a unicode object.  And 
it's not going to give you a utf-8 error if you're trying to decode 8859.


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


Re: [Tutor] What is wrong with my code?

2015-03-29 Thread Dave Angel

On 01/23/2015 04:40 PM, Antonia van der Leeuw wrote:

Hehey!

I'm learning python on a website called codecademy.com, where I made a
program to decode binary numbers. I guess the site uses a different
compiler, because on the site my code worked fine, but when I copied and
pasted it into the Python IDLE (3.4.2) it didn't work!


When asking a question here, it's really more useful to say in what way 
it didn't work.  Like if you crashed with an exception, show the stack 
trace including the error.


Still, it's a pretty safe guess that you got an exception on the print 
statement(s), which is a function in Python 3.x.


 I'm really don't know

what is wrong with my code, can anyone of you fine sirs help me?



Meh code:



number_input = input("What binary number do you want me to decode? ")



def decoder(number):

 number_backwards = str(number)[::-1] # Because binary numbers go from
right to left.

 result = 0

 value = 1

 br = False

 for n in number_backwards:

 if n != "1" and n != "0":

 print number, "is not a binary number"



 print(number, "is not a binary number")


 br = True

 break

 elif n == "1":

 result += value

 value += value

 if br == False:

 print "The binary number decoded is", result



  print("The binary number decoded is", result)



decoder(number_input)

--

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


Re: [Tutor] Python OO

2015-03-29 Thread Dave Angel

On 03/28/2015 09:16 PM, Juan C. wrote:

Ok, so, let me try to express what I think is 'right' here according to
what you said.

My code structure needs to be something like that:

pycinema
- package: pycinema
- - __init__.py
- - api.py
- - actor.py
- - movie.py
- - serie.py
- __main__.py



I'd suggest that you NEVER call a module  __main__.py   The name 
"__main__" is reserved for identifying the script file, and is faked 
during the program initialization.


By using that name for an imported file, you could get some very 
confusing errors later.


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


Re: [Tutor] escape character regex

2015-03-28 Thread Dave Angel

On 03/28/2015 03:37 PM, Ian D wrote:

Hi


I  run a regex like this:


pchars = re.compile('\x00\x00\x00') #with or without 'r' for raw


Which one did you actually want?  The 3 byte sequence consisting of 
nulls, or the 12 byte one containing zeroes and backslashes?  I'm going 
to assume the former, in which case you cannot use 'r' for raw.  Unless 
you've got a null key on your keyboard.




on a string like this:


data = "['broadcast', 'd8on\x00\x00\x00\x11broadcast', 'd11on']"



print "found pchars :",pchars.findall(data)


which returns:


found pchars : ['\x00\x00\x00']



But if I try to match the extra digits at the end like this:


pchars = re.compile('\x00\x00\x00\x\d+')


I get an error:


ValueError: invalid \x escape


The \x escape sequence must be followed by exactly two hex digits, and 
forms a single byte from them.  What did you want that byte to be, and 
why didn't you specify it?




Or if I use another ide than idle it actually flags it as an "illegal hexadecimal 
escape sequence"



The question is not what the various IDE's produce, but what the Python 
compiler produces.  So once you started getting errors, you really 
should have just run it in the interactive interpreter, without IDE's 
second-guessing you.  Anyway, in 2.7.6's interactive interpreter, I get:


>>> a = '\x00\x00\x00\x\d+'
ValueError: invalid \x escape
>>>

So it has nothing to do with re, and is simply the result of trying an 
invalid string literal.


What string were you hoping to get?  You mention you wanted to match 
digits at the end (end of what?).  Perhaps you wanted a real backslash 
followed by the letter d.  In that case, since you cannot use a raw 
string (see my first response paragraph), you need to double the backslash.


>>> a = '\x00\x00\x00\\d+'
>>> print a
\d+


Your data is funny, too, since it almost looks like it might be a string 
representation of a Python list.  But assuming you meant it exactly like 
it is, there is a funny control character following the nulls.


How could I match the \x00\x00\x00\x11 portion of the string?



There are no digits in that portion of the string, so I'm not sure why 
you were earlier trying to match digits.


Perhaps you meant you were trying to match the single control character 
x'11'.  In that case, you'd want


a = '\x00\x00\x00\x11'
pchars = re.compile(a)


But if you wanted to match an arbitrary character following the nulls, 
you'd want something different.


I think you'd better supply several strings to match against, and show 
which ones you'd expect a match for.


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


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

2015-03-23 Thread Dave Angel

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

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




Not really.  See Steve's


OOPS.  Peter's

> response for some numbers. If I had to guess,

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




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


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

2015-03-23 Thread Dave Angel

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

On Thu, Mar 19, 2015 at 12:10 AM, Dave Angel  wrote:

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


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


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


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



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


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


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




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


Re: [Tutor] Reversi Game Logic

2015-03-20 Thread Dave Angel

On 03/20/2015 06:20 PM, niyanax...@gmail.com wrote:


Thank you Danny Yoo for replying.

I figured out what to do for the isLegalMove but I ran into another problem. I 
now get a traceback error every chip is black.

This is the traceback:

Traceback (most recent call last):
   File "C:\Python34\lib\tkinter\__init__.py", line 1487, in __call__
 return self.func(*args)
   File "u:\code\reversiguiapp.py", line 83, in _cbMouseClick
TypeError: makeMove() takes 2 positional arguments but 3 were given
Exception in Tkinter callback







   # Performs an actual move in the game. That is the current player places
   # one of his chips in the square at position (row, col).
   def makeMove( row, col ):


Don't you need a 'self' parameter to this method, like all the others?


 if isALineOfAttack(row, col, 1, 1) is True :
   if self._currentPlayer == 1 :
 self._gameBoard[row, col] = BLACK
   else :
 self._gameBoard[row, col] = WHITE






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


Re: [Tutor] Reversi Game Logic

2015-03-20 Thread Dave Angel

On 03/20/2015 01:28 PM, niyanax...@gmail.com wrote:




You have more than one copy of some lines of previous messages, and more 
than one version of code in the message.  So I have to guess which one 
you intend to be current.





Thank you Mark for replying. I fixed the note you provided on the isLegalMove. 
However the lineOfAttack function is a function my Professor did so students 
are not allowed to touch it.




For the isOver function, are you able to guide me on that?

I am very new to Comp Science and am still learning.

I have attached the programs needed for testing to show that I am testing my 
code as well as the instructions provided for my project.

Please help me out!




   # Returns a boolean indicating whether the game is over.
   def isOver(self) :
 isOver = 0
 for i in range(8) :
   for j in range(8) :
 if self._gameBoard[i, j] != 0 :
   isOver + 1


The above line does NOT change isOver variable.  Try again.  By the way, 
it's not usually a good idea to use the function name as a local within 
the function, even though it'll work.




 if isOver == 64 :
 self._gameOver = True
 return True
 else:
 return False


   # Returns the
   def isLegalMove( self, row, col):
 if row < 8 > col:
   if self._gameBoard[row,col] != EMPTY:
 return True
 else:
   return False


This function is still buggy.  It does not return either True or False 
if the selected row is non-empty.





# Returns the player number whose chip occupies the given square.
   def occupiedBy(self, row, col):


How is the following function body any different from:
 return self._gameBoard[row, col]



 if self._gameBoard[row, col] == BLACK :
   return 1
 if self._gameBoard[row, col] == WHITE :
   return 2
 else:
   return 0




   # Performs an actual move in the game. That is the current player places
   # one of his chips in the square at position (row, col).
   def makeMove( row, col ):
 if isALineOfAttack(row, col, 1, 1) is True :


How are the four following lines any different from:
  self._gameBoard[row, col] = self._currentPlayer



   if self._currentPlayer == 1 :
 self._gameBoard[row, col] = BLACK
   else :
 self._gameBoard[row, col] = WHITE






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


Re: [Tutor] Reversi Game Logic

2015-03-20 Thread Dave Angel

On 03/19/2015 08:50 PM, niyanax...@gmail.com wrote:

I am having trouble with a function in my reversi logic code. The function is the 
isLegalMove I am asked to "Return a Boolean indicating if the current player can 
place their chip in the square at position (row, col). Both row and col must be valid 
indices​." So I came up with my code below, however a move I make in the game says 
Error: not a legal move. Please help!




I see lots of things wrong with the code, just by visual inspection. 
That should tell us that unit tests are necessary.  If nothing else, 
unit tests help you refine just what each method is supposed to do, and 
under what conditions.


I don't recall the rules for Othello, as it's been about 25 years since 
I've played it, and even then I didn't play much.


But there are lots of things about the code that the comments don't 
describe.  For example, it would seem from some of your code that the 
first player is always BLACK, and the second player is always WHITE. But 
in other places, you keep them distinct.


I see Mark gave you a number of markers into your code for problems that 
already exist.  So I'm going to concentrate only on the method you mention.





   # Returns the


Finish the comment


   def isLegalMove( self, row, col):
 if row < 8 and col < 8:
   if self._gameBoard[row,col] != EMPTY:
 return True
 else:
   return False


There are 3 exit points from the above function, and only two of them 
have return statements.  Your unit test could detect that by assuring 
that the return value is always either True or False.  The above 
function sometimes returns None.


Have you been taught yet what happens when a function falls off the end 
without a return statement?



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


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

2015-03-18 Thread Dave Angel

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

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

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

The generalized problem:

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

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

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

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

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

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

All I can say is: WOW!!!




That's very innovative.

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


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


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

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


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

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


Re: [Tutor] using json to pass a dict thru a file

2015-03-17 Thread Dave Angel

On 03/17/2015 06:30 PM, Doug Basberg wrote:

I appreciate the advise to use json to pass a dict thru a file.  Below is
the code
To 'dump' the dict to a file and the code to 'load' the dict and the error
message
I get testing this.

What am I doing wrong?  Thanks.


First two things I see are that you used the "ab" mode to write the 
file, and "r" to read it.


if you're appending, then the second time you run it, there'll be extra 
junk at the end.


If you're reading in text mode, then linefeeds might get abused.  When 
dealing with binary data, be sure and use "rb".



.


Traceback (most recent call last):
   File "C:/Python27/myTestRcv00.py", line 17, in 
 dataDict = json.load(f)
   File "C:\Python27\lib\json\__init__.py", line 290, in load
 **kw)
   File "C:\Python27\lib\json\__init__.py", line 338, in loads
 return _default_decoder.decode(s)
   File "C:\Python27\lib\json\decoder.py", line 368, in decode
 raise ValueError(errmsg("Extra data", s, end, len(s)))
ValueError: Extra data: line 1 column 85 - line 1 column 421 (char 84 - 420)



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


Re: [Tutor] print string using triple quote

2015-03-17 Thread Dave Angel

On 03/17/2015 05:54 AM, Alan Gauld wrote:

On 17/03/15 04:13, Nick Nguyen wrote:


Hi,
I use python 3.4.3.
I'm using print function with triple quote,


 > as I understand all the character will be printed

as exactly within the triple quote, even with

 > the backslash character.

You understand wrongly.
Triple quotes are no different to any other kind
of quote except that they can span lines. If you want
to print all the characters (with any kind of quote)
you must precede the quotes with r, for raw.

 >>> print ("""A string with \t in it""")
A string with  in it
 >>> print (r"""A string with \t in it""")
A string with \t in it
 >>>


And a raw string literal cannot easily have a backslash as the final 
character.  Sometimes it's good enough to just add a space at the end of 
a raw string.



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


Re: [Tutor] set current working dir

2015-03-17 Thread Dave Angel

On 03/16/2015 02:29 PM, Rajbir Singh wrote:

i need to know how i can set current working dir in an executing phython
using os module


os.chdir() will change the current directory, but it changes it for the 
whole program (all threads), and the change lasts till the program 
terminates.


Very often, one of these "buts" is a problem, so most people prefer to 
find a different way of solving the problem.  I prefer to have a policy 
of never changing the current directory once started, and for all file 
names make them either relative to that original current directory, or 
just make them absolute.


There are a number of functions that let you manipulate the file name 
strings, mostly in os.path



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


Re: [Tutor] Rearranging a list of numbers with corresponding index

2015-03-13 Thread Dave Angel

On 03/13/2015 09:57 AM, Ken G. wrote:

I have been keeping track of numbers drawn in our local lotto drawings
into a list format as shown in a short example below. Using such list, I
am able to determine how often a number appears within the last 100 plus
drawings.

The length of my lists range from 5, 15, 35, 59and 75 long. I will give
an example of one of my short list.

PowerPlay = [0, 0, 61, 32, 11, 14]

Disregarding index 0 and 1, I can see and print the following:

IndexNumber
2 61
3 32
4 11
5 14

showing that number 2 appears 61 times, number 3 appears 32 times,
number 4 appears 11 times and number 5 appears 14 times within last 100
plus drawings.

How I best rearrange the numbers from high to low with its corresponding
index number such as below:

Number Index
612
323
14 5
11 4

showing the number 2 appears 61 times, number 3 appears 32 times, number
5 appears 14 times and number 4 appears 11 times. I know that using

MegaBall.reverse()

sort the number from high to low but the index numbers still remain in
the same positions.

Thanks for pointing out the way to do this.



Make a list of tuples by doing something like:
new_list = [ (cnt, index) for index, cnt in enumerate(power_play) ]

to produce:
  [ (0, 0), (0, 1), (61, 2), (32, 3), (11, 4), (14, 5) ]

then sort it with reverse=True.  When you print it, just omit the items 
that have zero as their count.  (they'll be at the end, anyway)


Lots of other variants, some more concise.  And other approaches might 
be cleaner if we change how we generate the list.


(I tried it briefly using Python 3.4)


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


Re: [Tutor] How linux software centers make “search” operation?

2015-03-11 Thread Dave Angel

On 03/11/2015 07:21 PM, metis wisdom wrote:

Hello, I want to develop a software center in Ubuntu similar to Ubuntu
software center.



You forgot the rest of the caps.  It's "Uuntu Software Center".

Why?  Is there something wrong with what it does, that you need 
something different?  Is this actually a school assignment?


What was the actual assignment you were given, and when is it due?  What 
course material have you already covered?  Are you supposed to make this 
software work with live Linux data, or with some madeup samples?



In ubuntu software center, when we type a keyword and hits
enter button, it displays us the related results. For example, when i
searched for "eclipse" keyword, 5 result are listed in ubuntu software
center.


Is that good, or do you wish it showed 100 results?



I want to do the similar functionality in my software center.


Why?



I tried to solve this problem by making search in apt package manager using
bash command(apt search package_name), but it gives all packages as result,
approximately more than 100 packages.

How ubuntu software center and other software centers search a keyword?


What's a software center?  Now you're using the term as though it's a 
generic term, rather than the name of a particular software package.



Where do they search the keyword and retrieve results?


They probably issue an SQL command. to some database.  Or maybe they 
issue some Perl code that looks something up in a hash table.  Or maybe 
a SOAP call.


Does it matter?


Source code of
ubuntu software center is so complex and i cannot find what i need. Any
guide will be appreciated. Thanks in advance.


You've looked at the source?  What languages is it implemented in?  You 
mention technologies, but not what they are.




I analysed all source code of ubuntu software center. These codes includes
so many technologies that it is very hard to understand it. IN order to
understand these codes, i have to learn many technologies , it may take at
least one month,maybe this time may not be enough. After i spent so many
times learning these technologies, what if these technologies does not
solve my problem? I know only python, i am not familiar with os library
etc, and i have a limited time, please guide me. I need to build a simple
software center, not a sophisticated one.


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


Re: [Tutor] String method "strip()" not working

2015-03-07 Thread Dave Angel

On 03/07/2015 08:15 AM, Akash Shekhar wrote:

I am trying to learn how to use strip() method. It is supposed to cut out
all the whitespace as I read in the tutorial. But the code is not working.

Here's my code:

sentence = "Hello, how are you?"




print(sentence)




print(sentence.strip())




input("\n\nPress enter key to exit.")





Here's it's output:

Hello, how are you?

Hello, how are you?

Press enter key to exit.




Both results are same.

P.S.: I am using Python 3.1 IDLE on Windows 7.


Thanks for mentioning the python version and OS.

You don't have any whitespace at the beginning nor end of the string 
bound to sentence.  So there's nothing to strip.  By the way, if you're 
checking such a function, it's sometimes more informative to write

   print(repr(sentence))
which will add quotes at begin and end, and show newlines and tabs as 
escape sequences.


If you only want to strip from one end of the string, you'd use lstrip() 
or rstrip().


If you're also trying to remove characters from the middle of the 
string, you might use translate() or the string method replace().  For 
example, to remove all spaces from a string, use

sentence.replace(" ", "")

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


Re: [Tutor] Idle - ImportError: No module named numpy

2015-03-06 Thread Dave Angel

On 03/06/2015 01:27 PM, Markos wrote:

Hi,

I'm beginning to study the numpy.



And what does this have to do with the
   """Strengths & weaknesses of Python lists compared to
   "old school" arrays [Was "Fixed Vector Array"]"""
thread?  Please don't hijack a thread by replying with an unrelated 
message.  Just start a new one with "Write email" or equivalent. 
Address it to tutor@python.org, and it'll be fine.




When I open a terminal (Debian Squeeze) and run the python interpreter
the command "import numpy as np" run without errors.

But when I run the same command on idle3 the following error appears.

 >>> import numpy as np
Traceback (most recent call last):
   File "", line 1, in 
 import numpy as np
ImportError: No module named numpy

How configure idle to load the numpy module?



As others have said, you probably have a version mismatch.  When you ran 
Python from the terminal, what did you call it?  Which version did you get?


When you ran idle3, you presumably ran some version 3 installation of 
Python.


From each interactive session, you can check the Python version with:

 import sys
 sys.version

Unless they're identical in the two environments you describe, you can't 
assume they'll both have numpy loaded.



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


Re: [Tutor] Python 3 - bugs or installation problem

2015-03-04 Thread Dave Angel

On 03/04/2015 09:11 PM, boB Stepp wrote:

On Wed, Mar 4, 2015 at 7:53 PM, Phil  wrote:

I hope this is not another embarrassingly obvious answer to a simple
question.

Python 3, under Kubuntu.

xrange() fails whereas range() is accepted. Could this be an installation
problem?
etc


This may fall into the obvious answer. ~(:>))

My Python reference says that the xrange function was discontinued in
Python 3, which you are using.

"In Python 3.x, the original range() function is changed to return an
iterable instead of producing a result in memory, and thus subsumes
and [sic?] Python 2.x's xrange(), which is removed." -- Python Pocket
Reference, 5th ed., by Mark Lutz.



And the other half of the answer is that your IDLE is apparently using 
the Python 2 interpreter, in which print is defined differently.



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


Re: [Tutor] Fixed Vector Array

2015-03-04 Thread Dave Angel

On 03/04/2015 10:40 AM, niyanax...@gmail.com wrote:

Need help trying to implement insert, remove, indexof, and reverse functions.

I tried to do them but am not sure if it is correct. I am struggling with 
arrays.


This is python and using ezarrays.



I don't know any Python that includes something called ezarrays in its 
library.  What version of Python are you using, and where do you get 
ezarrays?


In general, the tutor list is for learning about Python and its standard 
library.  You might get lucky, and find someone who knows your special 
library, but that's more likely on either python-list, or in a forum 
that is specifically for that library.


We'll try to help here, but it'll be based on a bunch of guesses, rather 
than experience.  Not the best way to get help.


I'm going to speculate and guess you're talking about
http://courses.necaiseweb.org/EZArrays/EZArrays




Assignment:


Seems like it's trying to teach you pascal, or java, not Python.



A fixed vector is very similar to the vector in that it is a sequence container 
that can grow and shrink as needed and include many useful operations. But the 
fixed vector has a maximum capacity beyond which it can not expand.

• FixedVector(maxSize): Creates an empty fixed vector with the given maximum 
capacity.

• length(): Returns the number of elements contained in the vector.


You called the method __len__(), rather than the requested length().
It's not clear what they want here, but it's a reasonable guess that 
they want 1+ the index of the highest item that isn't None.




• isFull(): Returns a Boolean indicating if the vector is full.

• getitem(index): Returns the element stored in the vector at position index. 
The value of index must be within the valid range.


Again, you implemented __getitem__() rather than the requested getitem()


• setitem(index, item): Sets the element at position index to contain the given 
item. The value of index must be within the valid range, which includes one 
position beyond the end of the vector. In the latter case, the item is simply 
appended onto the end.


And again here.


• contains(item): Determines if the given item is contained in the vector.


And again here.



• toString(): Returns a string representation of the vector.


But you called it __str__



• append(item): Adds the given item to the end of the vector. An item can not 
be appended to a full vector.

• clear(): Removes all elements from the vector.

• insert(index, item): Inserts the given item into the vector at position 
index. The elements at and following the given position are shifted down to 
make room for the new item. The index must be within the valid range and the 
vector can not be full. If index is one position beyond the end of the vector, 
the item is appended onto the vector.

• remove(index): Removes the element at position index from the vector. The 
removed element is returned. The index must be within the valid range.



Not clear if this is supposed to be symmetric with insert.  If so, then 
you have to slide things left, like you slid them right in the previous 
method.



• indexOf(item): Returns the index of the element containing the given item. 
The item must be in the list.

• reverse(): Performs a list reversal by reversing the order of the elements 
within the vector.





My Code:


from ezarrays import Array


class FixedVector :
# Creates a new empty fixed vector with the given maximum capacity.
   def __init__(self, maxSize) :
 self._theItems = Array(maxSize)
 self._numItems = 0

# Returns the number of elements contained in the vector.
   def __len__(self) :
 return self._numItems

# Returns a Boolean indicating if the vector is full.
   def isFull(self) :
 return self._numItems == len(self._theItems)

# Returns the element stored in the vector at position index.
# The value of index must be within the valid range.
   def __getitem__(self, index) :
 assert index >= 0 and index < self._numItems, "Index out of Range."


assert should never be used to check data values, but only for program 
invariants.  It should be an if statement with a raise statement in the 
body.  Same thing for other asserts in this code.



 return self._theItems[index]

# Sets the element at position index to contain the given item. The
# value of index must be within the valid range, which includes one
# position beyond the end of the vector. In the latter case, the item
# is simply appended onto the end.
   def __setitem__(self, index, item) :
 assert index >= 0 and index <= self._numItems, "Index out of range."

 if index == self._numItems :
   self.append(item)


   At this point, the _numItems value is incorrect


 else :
   self._theItems[index] = item

# Determines if the given item is contained in the vector.
   def __contains__(self, item) :
 i = 0
 while i < self._numItems :
   if self._theItems[i] == item :
   

Re: [Tutor] What exactly is "state"?

2015-03-02 Thread Dave Angel

On 03/02/2015 01:42 PM, Sydney Shall wrote:


Thank you very much, Joel, Danny, Alan and Dave.
Your explanations are all very clear and very enlightening.
I shall have to change several of my unittests now. In good time.
I am particularly pleased with the examples; they clarify matters
considerably for me.

Out of subject, I wonder from this exchange whether teaching should not
always involve at least several teachers. Your replies are very
complimentary!



Your reply was very complimentary, our replies were complementary. 
Notice the e instead of the i.


Yes, multiple teachers is frequently useful.  When I was in college, 
many classes had both a professor (lecturer) and assistant professors 
(or teaching assistants, or ...).  One lecture in a big hall, one 
relatively small class where you could more easily interact.  I found 
the two different viewpoints useful, though sometimes the leaders of the 
small class were almost afraid to challenge the full prof.


I also advocated a dual-manager role in one company.  Idea didn't 
formally go anywhere, but I did manage to escape from management -- went 
from 50 people to 1, and a promotion at the same time.



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


Re: [Tutor] What exactly is "state"?

2015-03-02 Thread Dave Angel

On 03/02/2015 11:25 AM, Sydney Shall wrote:

I am a beginner and I am now at the strage of learning to write unittests.
I have followed the current discussion entitled "How to test a class in
pyhton", and I am not clear precisely what is meant by state. In its
common meaning I can see some relevance. But is there a technical aspect
to the notion. I see it mentioned often and feel rather uncomfortable
that I know so little about it.
I have deliberately started a new thread.
Thanks.


When I started composing this, there were no other replies.  Sorry for 
any duplication caused by that.


Starting with a dictionary definition:

http://www.merriam-webster.com/dictionary/state
"the overall physical condition of something : the ability of something 
to be used, enjoyed, etc."


Others:


"The particular condition that someone or something is in at a specific 
time"


"In computer science and automata theory, the state of a digital logic 
circuit or computer program is a technical term for all the stored 
information, at a given instant in time, to which the circuit or program 
has access."


That last comes the closest to what I'd like to explain.

For a given fragment of executing code, the state includes all local 
variables, all parameters, all closures, all visible globals (ie the 
ones that *could* be visible to the code.  It also includes indirectly 
the values of all environment variables, lots of system information like 
the current directory, the time, the network IP address.  It also 
includes the current phase of the moon, the astrological sign of the 
current president of France, and the number of specs of sand on the 
eastern shore of a certain Martian lake.

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


Re: [Tutor] Issue in date difference in Python 2.7.8

2015-02-20 Thread Dave Angel

On 02/20/2015 04:28 AM, Puruganti Ramesh wrote:

Hi Friends,

I have an issue in comparing dates in python 2.7.8
I have written code as below but i am getting error
Code is :
import datetime as dt
from datetime import datetime
from datetime import datetime, timedelta, date

dt_str='2014-5-11'
dt_strq='2014-9-11'

dt_datea = datetime.strptime(dt_str, '%Y-%m-%d').date()
dt_dateb = datetime.strptime(dt_strq, '%Y-%m-%d').date()
dt_diff = dt_dateb - dt_datea
print dt_diff.days

I am getting below excption
Traceback (most recent call last):
File "FunctionUpdate.py", line 204, in 
dt_dateb = datetime.strptime(dt_strq, '%Y-%m-%d').date()
File "/usr/local/lib/python2.7/_strptime.py", line 328, in _strptime
data_string[found.end():])
ValueError: unconverted data remains:



I think it's great that you reduced a 200+ line program into a 9 line 
simple case.  that's always a good idea, and frequently it helps you 
solve your own problem, reducing it for public comment.


But the other requirement is that you actually test that the code you 
show produces the error you show.  It does not, probably because those 
strings in the literals are not exactly what you had in the original.



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


Re: [Tutor] Python 3 simple socket issue

2015-02-18 Thread Dave Angel

On 02/18/2015 10:48 AM, Juan C. wrote:

Code:

# !/usr/bin/env python3
# -*- coding: utf-8 -*-

import socket

def main():
target_host = 'www.google.com'
target_port = 80

client = socket.socket()
client.connect((target_host, target_port))
client.send(b"GET HTTP/1.1\r\nHost:google.com\r\n\r\n")

response = client.recv(4096)
print(response)



When I run that, I get:

davea@think2b:~/zzztemp$ python juan.py
  File "juan.py", line 8
target_host = 'www.google.com'
  ^
IndentationError: expected an indented block
davea@think2b:~/zzztemp$


So you might want to fix the indentation.  And add a call to main() at 
top level.


Once I do that, I get approximately the same thing you post below.



Output:

C:\Python34\python.exe D:/Documents/PyCharm/Test/__main__.py
b'HTTP/1.0 403 Forbidden\r\nContent-Length: 1180\r\nContent-Type:
text/html; charset=UTF-8\r\nDate: Wed, 18 Feb 2015 15:43:16 GMT\r\nServer:
GFE/2.0\r\nAlternate-Protocol: 80:quic,p=0.08\r\n\r\nSorry... body { font-family: verdana,
arial, sans-serif; background-color: #fff; color: #000;
}GoogleSorry...We\'re sorry.. but your computer or network may be
sending automated queries. To protect our users, we can\'t process your
request right now.See https://support.google.com/websearch/answer/86640";>Google Help for more
information.https://www.google.com";>Google
Home'

Process finished with exit code 0

Why a I getting 403? The code seems fine.



Could it be because google.com doesn't want automated queries?  That's 
what they say in the text there.


See:
   http://www.google.com/intl/en/policies/terms/




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


Re: [Tutor] Python Question: Excluding certain keywords.

2015-02-17 Thread Dave Angel

On 02/17/2015 03:30 PM, Arnold Chung wrote:

Dear Python Tutor.


Welcome to the tutor list.  As far as I can tell, this is your first 
post.  And thank you for using text mail, rather than html.




First of all, thank you for your kindness in advance. I am learning python by 
myself and having some difficulties in a problem that I encounter.

Here I attach my python file.


This mailing list doesn't support attachments.  What that means is that 
even if some subscribers might see the attachment you presumably did, 
others will not.  I do not.  Please paste the relevant code into the 
message.  If it's too large for that, then strip it down to a simpler 
case that is reasonable.


You probably will also need to tell us your Python version.


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


Re: [Tutor] monkey patching question

2015-02-17 Thread Dave Angel

On 02/17/2015 04:53 PM, Albert-Jan Roskam wrote:

Hi,

I would like to monkey patch a function 'decode' that is defined inside a class. It is 
defined there because it is a logical place, next to its counterpart *method* 'encode'. I 
can successfully monkey patch meth1, but when I call meth2, it does not use the patched 
decorator. How can this be done? In this example, I would like to effectively "turn 
off" @decode. I am hoping for a solution that works on Python 2.7 and 3.3+.


import inspect, functools
class Foo(object):

 def decode(func):
 @functools.wraps(func)
 def wrapped(*args, **kwargs):
 print "original decorator was called"
 return func(*args, **kwargs).decode("utf-8")
 return wrapped

 def encode(self):
 """this is just here to show why decode() is defined
 within Foo"""
 pass

 def meth1(self):
 return "original method was called"

 @decode
 def meth2(self):
 return b"python rocks"



I assume the monkey patching happens in some other file which will 
import this one.


So by the time the import is finished, the meth2() method has already 
been decorated by the decode function.




#  works -
f = Foo()
print f.meth1()
Foo.meth1 = lambda self: "new method was called"
print f.meth1()
print "---"


#  does not work -
def patched_decode(func):
 @functools.wraps(func)
 def wrapped(*args, **kwargs):
 print "patched decorator was called"
 return func(*args, **kwargs)
 return wrapped

f = Foo()
print 'ORIGINAL'
print inspect.getsource(Foo.decode)  # shows source code of regular decode (as 
expected)
result = f.meth2()
print repr(result), type(result)

#setattr(Foo, "decode", patched_decode)
Foo.decode = patched_decode

print 'PATCHED'
print inspect.getsource(f.decode)  # shows source code of patched_decode (as 
expected)
result = f.meth2()
print repr(result), type(result)   # not patched at all! it's still unicode!



# output:
In [1]: %run monkey_patch.py
original method was called
new method was called
---
ORIGINAL
def decode(func):
@functools.wraps(func)
 def wrapped(*args, **kwargs):
 print "original decorator was called"
 return func(*args, **kwargs).decode("utf-8")
 return wrapped

original decorator was called
u'python rocks' 
PATCHED
def patched_decode(func):
@functools.wraps(func)
 def wrapped(*args, **kwargs):
 print "patched decorator was called"
 return func(*args, **kwargs)
 return wrapped

original decorator was called
u'python rocks' 



I think you're going to have to patch meth2().  Patching decode won't 
help, since it's already done its work.



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


Re: [Tutor] Potential problem with Game Over 2.0 problem in "Python Programming for the Absolute Beginner, 3rd Ed."

2015-02-17 Thread Dave Angel

On 02/17/2015 02:12 PM, boB Stepp wrote:

See 
https://docs.python.org/3.4/reference/lexical_analysis.html#string-and-bytes-literals


At this point in the text he is not talking about raw literal strings.
I examined the author's source and he has obviously inserted at least
one space between each use of a backslash at the end of a line and the
EOL terminating characters.


Then he's teaching you wrong. Backslash followed by space is not a valid 
escape sequence, and to do it at the end of line is particularly odious. 
 I wouldn't even suggest it in real code, never mind in something 
that's published on paper.


The docs admit that the invalid escape sequences behave differently than 
C, in that the backslash is retained.  I think it should be a syntax 
error to have an invalid sequence.


If the backslash immediately precedes the newline, then the two 
characters both get eaten, and the two lines are combined into one. 
That can be useful if you want to define a string that's too long to fit 
in your source file.


I would never intentionally make any trailing whitespace in source code 
be significant.  And years ago I used an editor that routinely deleted 
any such invisible characters.  From the rest of your message, it looks 
like IDLE may have that behavior.




He did not do this with the "Game" portion
of the code, which did not make any use of "\" . When the file is run
everything behaves as desired. But if, as my son did, you leave no
spaces between the last backslash and the EOL termination characters,
then the problem behavior occurs.




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


Re: [Tutor] Hey guys!

2015-02-17 Thread Dave Angel

On 02/16/2015 11:22 PM, Levi Adissi wrote:

Thank you for using text email, rather than the html mail that so many 
newcomers use.



So I'm kind of stuck trying to program a function that returns a list of
tuples. The function takes 2 lists containing circles of which it should
compare list1[0] to list2[0] to see if they intersect. If they intersect or
touch then I should return them on a list of tuples(in the tuple would be
both intersecting circles).

I can't get circles_only to work the way I see it I'm comparing h to x only
if they're both in the same place on the list (hence my "h==x") I know it
doesn't work because the test returns None so I would really appreciate an
alternative method if you guys see one.

Here are my functions:


def circles_overlap(c1, c2):
x=(c2.center.y-c1.center.y)**2
y=(c2.center.x-c1.center.x)**2
distancemid=math.sqrt(x+y)
distancerad=(c1.radius+c2.radius)
if distancemid > distancerad:
return 1
elif distancemid < distancerad:
return -1
elif distancemid == distancerad:
return 0

def circles_only(lst1, lst2):
newlst=[]
for h in lst1:
   for x in lst2:
  if h==x:


That's silly.  You don't want to compare the two circles to see if 
they're equal.  Remove this line.



 if circles_overlap(lst1[h],lst2[x])== -1:


Why don't you tell us the exception this line causes?  lst1 is 
subscripted by integers, not by circle objects.


What you really want in this line is something like:
   if circles_overlap(h, x) ! = 1:
   newlst.append(h, x)



newlst.append(lst1[h],lst2[x])

 elif circles_overlap(lst1[h],lst2[x])== 0:
newlst.append(lst1[h],lst2[x])

print newlst


Don't print it, return it.  Otherwise, you're returning None.




TEST CASE:

 def test_circles_olap1(self):
 list1=[data_2.Circle(data_2.Point(2,3),
2),data_2.Circle(data_2.Point(2,3), 2), data_2.Circle(data_2.Point(2,3), 2)
]
 list2=[data_2.Circle(data_2.Point(6,3),
2),data_2.Circle(data_2.Point(10,3), 2), data_2.Circle(data_2.Point(5,3), 2)
]
 testor=functions_2.circles_only(list1,list2)
 newlist=[(data_2.Circle(data_2.Point(2,3),
2),data_2.Circle(data_2.Point(6,3), 2)),(data_2.Circle(data_2.Point(2,3),
2),data_2.Circle(data_2.Point(10,3), 2))]
 self.assertEqual(testor, newlist)



The test code makes no sense to me at all.  it's a method of some 
unspecified class, and it uses some namespaces called data_2  and 
functions_2 for an unknown purpose.




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


Re: [Tutor] Help with program

2015-02-16 Thread Dave Angel

On 02/16/2015 11:27 AM, Courtney Skinner wrote:

Hello,

I am trying to build a program that approximates the value of cosine - this is 
my program so far. It is not returning the right values. Could you tell me what 
I am doing wrong?




You've got several answers that point out several problems in your code. 
 But I think you're missing a key concept.


If you're faced with a problem that's beyond your present abilities, or 
that's got you stumped, always consider factoring the problem into 
simpler ones.


To me the first thing you should factor out is a factorial function. 
Write one, that takes a positive int and returns the factorial, and test 
it against the one in the math library.


Once it's correct, then use it in the cosine problem.  Now you've got a 
simpler loop to write.  And you know part of the code works.


Next, see if you can avoid most of those three variables you're using. 
For example, What do you get when you calculate

   (-1) ** (i)

Can you use that to simplify things?


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


Re: [Tutor] trivial simple program..can it be made more concise?

2015-02-14 Thread Dave Angel

On 02/14/2015 07:51 AM, Steven D'Aprano wrote:

On Sat, Feb 14, 2015 at 06:40:56AM -0500, Dave Angel wrote:

On 02/14/2015 04:07 AM, Steven D'Aprano wrote:

On Sat, Feb 14, 2015 at 03:17:28AM +, steve10br...@comcast.net wrote:


[...]

for i in range (a):
 print i, '\r',

[...]


BUT I'm not sure why you are worried about making it more concise when
your code doesn't do what you want, as far as I can tell. You want the
counter to be written on the same line, not 640 thousand lines, but when
I try it, I get each number written to a different line.


That's probably because you've dropped the trailing comma that the OP
used in the print statements.


So I did :-(

Have I mentioned recently just how awesome Python 3's print is?

for i in range(10):
 print(i, end='\r')

Much nicer :-)




Agreed.  But don't you need " \r" so when you're counting down you don't 
have the trailing crud?  The space was implicit on Python 2, because it 
mistakenly thought the code was printing two elements.



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


Re: [Tutor] trivial simple program..can it be made more concise?

2015-02-14 Thread Dave Angel

On 02/14/2015 04:07 AM, Steven D'Aprano wrote:

On Sat, Feb 14, 2015 at 03:17:28AM +, steve10br...@comcast.net wrote:

Hi all,

I was playing with Python tonight and created a simple program that
outputs numbers counting up then counting down all on the same
terminal line. The code is as follows:

#
a = 32 #number to count up to

for i in range (a):
 print i, '\r',

for i in range ((a-1),0,-1):
 print i, '\r',

#

It works as desired. However, I was trying to figure out a way to make
it more concise but cannot see a way since the 'range' parameters must
be integers (no functions allowed?).



Parameters to range can be anything which evaluates to integers, but
I'm not sure how that will help you. Also, in Python 2 xrange is a
little more efficient than range.

How's this?

a = 32
counts = (xrange(a), xrange(a-1, 0, -1))
for counter in counts:
 for i in counter:
 print i, '\r'


BUT I'm not sure why you are worried about making it more concise when
your code doesn't do what you want, as far as I can tell. You want the
counter to be written on the same line, not 640 thousand lines, but when
I try it, I get each number written to a different line.


That's probably because you've dropped the trailing comma that the OP 
used in the print statements.




Try this instead:

import sys
a = 32
counts = (xrange(a), xrange(a-1, 0, -1))
for counter in counts:
 for i in counter:
 sys.stdout.write(str(i) + '\r')
 sys.stdout.flush()





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


Re: [Tutor] How to pass varying number of arguments to functions called by a dictionary?

2015-02-11 Thread Dave Angel

On 02/11/2015 10:29 AM, boB Stepp wrote:

On Wed, Feb 11, 2015 at 8:45 AM, Dave Angel  wrote:

On 02/11/2015 08:27 AM, boB Stepp wrote:

[...]


Sure, it's viable, but the best approach depends on your goal (use case),
and your restrictions.  Are these functions really totally unrelated to each
other?  You not only don't have the same number of arguments, but the values
don't even have anything in common?


The file/module containing functions extract information from another
software application (with its own scripting language) and ask that
software to perform certain calculations in its scripting language.
The dictionary keys are conventional symbols for types of calculations
that someone might request. I have a current set of requested
calculations, but this will likely be augmented with new ones in the
future. Depending on the request, there might be no arguments passed,
meaning there is a simple request for information from the software
application that requires only a look-up, or the actual software
application may have to do calculations requiring one or more passed
values. Which and how many values depends on the type of calculation
requested.


There's an implied constraint that you're not permitted to change the
functions.  Are you really constrained to only change the caller?


I think this is the case, but I am open to other ideas.


Assuming that you seriously want to be able to do this, the only use case I
can imagine are:
1) you're writing an interpreter


I was not thinking explicitly in this way, but in effect I am
translating requests in Python code into a proprietary scripting
language, and vice versa.

[...]


In each case, there are probably better ways...


I am open to suggestions!



So where does the data for these parameters come from?  In other words, 
who is your user?  Why isn't that user just calling the functions 
directly?  You mention you're getting the function code-letters from a 
data file.  Are you getting the data for the parameters from there as well?


If all the data, and the corresponding function codes, are coming from 
the data file, then you must be deserializing that file in some way. 
And unless the data is always strings, there's more work to do there 
than in the wrapping of the calls themselves.


There are libraries for serializing and deserializing arbitrary data. 
Some use xml, some use json, axon, csv, YAML, and probably tons of 
others.  Likewise there are protocols such as SOAP, for remote procedure 
calls.


Is the file entirely linear, or are you going to be doing branching, 
subroutining, etc?  If there's any more complexity, you need to see the 
whole picture before you just do the call.


Do any of these functions have return values?  How are you handling that?


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


Re: [Tutor] How to pass varying number of arguments to functions called by a dictionary?

2015-02-11 Thread Dave Angel

On 02/11/2015 08:27 AM, boB Stepp wrote:

Python 2.4.4, Solaris 10

I have a file of functions. Based on what is read in a data file,
different functions in the file of functions will need to be called. I
have been trying to make the following approach work, so far
unsuccessfully as, in general, each function may have a different
number of arguments that might have to be passed to it.

def func1(x1, x2, x3):
 pass

def func2(y1, y2):
 pass

def func3(z):
 pass

call_fcn = {'a': func1, 'b': func2, 'c': func3}

call_fcn[key_letter](???)

How can I successfully pass the needed arguments needed for each
possible function with this approach? I naively tried to do something
like:

pass_args = {'a': (x1, x2, x3), 'b': (y1, y2), 'c': (z)}
call_fcn[key_letter](key_letter)

But ran into the syntax error that I was giving one argument when
(possibly) multiple arguments are expected.

Is what I am trying to do a viable approach that can be made to work?
Otherwise, I will brute-force my way through with if-elif-else
statements.

Thanks!



Sure, it's viable, but the best approach depends on your goal (use 
case), and your restrictions.  Are these functions really totally 
unrelated to each other?  You not only don't have the same number of 
arguments, but the values don't even have anything in common?


There's an implied constraint that you're not permitted to change the 
functions.  Are you really constrained to only change the caller?


Assuming that you seriously want to be able to do this, the only use 
case I can imagine are:

   1) you're writing an interpreter
   2) you're interfacing some network channel, where something at the 
opposite end is sending you messages that you have to turn into local 
function calls, and return results.  A kind of RPC.


In each case, there are probably better ways.  But you want this way, so 
here goes:  (code is untested)


pass_arg_dictionary = {'a': (x1, x2, x3), 'b': (y1, y2), 'c': (z)}
pass_args = pass_arg_dictionary[key_letter]  #a list
call_fcn[key_letter]( *pass_args )


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


Re: [Tutor] Creating a pojo in python

2015-02-09 Thread Dave Angel

On 02/09/2015 02:20 AM, rakesh sharma wrote:

How can one create a POJO in python.I mean a class like this
class A {   private a;   private b;   public getA() {   return a;   }   
public getB() {  return b   }}
I tried creating class in python but the variables were accessible as public 
data members.
Any help?   



The other respondents so far (Danny, Alan, and Mark) are right on.  But 
there are times when you might want APPROXIMATELY what you call POJO in 
Python.


Obviously you wouldn't want exactly that, since that class is totally 
useless.  Without any setters or constructor, those class members cannot 
be initialized to any value.  (I don't know if java has the equivalent 
of C++ friends, or whether derived classes could change those private 
values, so I may be wrong here)


So the real question is why DO you want the Python version of this.

If it's because your teacher is trying to make some point, and assigned 
you to figure this out, then try using the @property decorator on the 
get function.  Naturally, the get function is called a, and the private 
data is _a_hidden_attribute_that_you_dont_want_the_caller_to_use


The public interface of that class is then just the same as though the 
class had a and b attributes, except that writing to those will give a 
runtime error.


If it's because you have a bunch of code that you already transliterated 
from java, and it uses this class you haven't written yet, then my 
sympathies.  I've been there, and the cure is to go back to all those 
uses, and change each function call of the form:


obj.getA()to
obj.a

If all that code was transliterated by somebody else, and you're not 
allowed to mess with it, then go back to the teacher example.


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


Re: [Tutor] Explanation of this print statement

2015-02-08 Thread Dave Angel

On 02/08/2015 06:01 PM, Shawn Byers wrote:

Hello I was wondering if someone could explain this print statement

for r in range(6,0,-1):
  print((6-r)*''+r*'o')



You probably intended to have a blank between the first two single-quotes.

 for r in range(6,0,-1):
   print((6-r)*' '+r*'o')


Perhaps it'd be more interesting to put some other character in the quotes:

 for r in range(6,0,-1):
   print( (6-r)*'X' + r*'o' )

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


Re: [Tutor] Need help writing code with python

2015-02-08 Thread Dave Angel

On 02/07/2015 05:36 PM, Conner Wood wrote:

I fell behind 2 weeks in my class due to surgery and have a coding project
due tonight (Saturday, Feb. 7).  I've attached my project to this email.
Please help!  Also, I'm using a Mac laptop if that helps in anyway.  Please
get back to me as soon as you can.



Welcome to Python-tutor.  This seems to be your first post.

Thanks for making it a text email.  And for mentioning your OS.  But you 
also should be specifying the Python version.


There's no attachment to your message in the mailing list.  And many 
people here can't see attachments anyway.  If your project is too big to 
include directly in your email message, you may be out of luck.


How big a project is it, and how much of it have you been able to do so 
far?  Is there some particular problem that has you stumped?


We're here to help you get past some sticking point, not to do your 
assignment for you.  I'd expect your prof would give you an extension if 
you can't get it in because of unexpected surgery.





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


  1   2   3   4   5   6   7   8   9   10   >