[Tutor] Converting integers into digit sum (Python 3.3.0)

2013-12-09 Thread Rafael Knuth
Hej there,

I wrote a program that converts an integer into a digit sum:

def DigitSum(YourNumber):
DigitList = []
YourNumber = str(YourNumber)
for i in YourNumber:
DigitList.append(int(i))
print(sum(DigitList))

DigitSum(55)

>>>
10

It actually works but I was wondering if that's the only way to solve
the task of converting an integer into a digit sum?  I learned from
past conversations on this mailing list that often times there is a
better, more elegant and shorter way to write a program, and I was
wondering if that's the case here.

Thanks!

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


Re: [Tutor] No module named '_tkinter'

2013-12-09 Thread eryksun
On Sun, Dec 8, 2013 at 2:36 PM, pierre dagenais  wrote:
> I'm running Ubuntu 10.04 and I've installed python 3.3.3 from the
> tarball at http://python.org/ftp/python/3.3.3/Python-3.3.3.tar.xz
>
> Here is the error I get when trying to run tkinter.
>
> ImportError: No module named '_tkinter'
>
> I've tried installing python3-tk from the Ubuntu repository but it
> doesn't help.

It looks like you didn't install the development dependencies before
building. The build-dep for Lucid's 3.1 package should do the trick.

sudo apt-get update
sudo apt-get build-dep python3.1

For good measure run the following, too:

sudo apt-get install build-essential \
  libbz2-dev libdb-dev libexpat1-dev libffi-dev \
  libgdbm-dev liblzma-dev libncursesw5-dev \
  libreadline6-dev libsqlite3-dev libssl-dev \
  tk-dev zlib1g-dev

Then do a `make clean` and rebuild.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Converting integers into digit sum (Python 3.3.0)

2013-12-09 Thread Amit Saha
On Mon, Dec 9, 2013 at 6:08 PM, Rafael Knuth  wrote:
> Hej there,
>
> I wrote a program that converts an integer into a digit sum:
>
> def DigitSum(YourNumber):
> DigitList = []
> YourNumber = str(YourNumber)
> for i in YourNumber:
> DigitList.append(int(i))
> print(sum(DigitList))
>
> DigitSum(55)
>

> 10
>
> It actually works but I was wondering if that's the only way to solve
> the task of converting an integer into a digit sum?  I learned from
> past conversations on this mailing list that often times there is a
> better, more elegant and shorter way to write a program, and I was
> wondering if that's the case here.

>>> sum([int(digit) for digit in str(55)])
10

That's using list comprehensions. Since a string is basically a
sequence, you can do the above.

Best,
Amit.

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


Re: [Tutor] Converting integers into digit sum (Python 3.3.0)

2013-12-09 Thread Asokan Pichai
On Mon, Dec 9, 2013 at 1:38 PM, Rafael Knuth  wrote:

> Hej there,
>
> I wrote a program that converts an integer into a digit sum:
>
> def DigitSum(YourNumber):
> DigitList = []
> YourNumber = str(YourNumber)
> for i in YourNumber:
> DigitList.append(int(i))
> print(sum(DigitList))
>
> DigitSum(55)
>
> >>>
> 10
>
> It actually works but I was wondering if that's the only way to solve
> the task of converting an integer into a digit sum?  I learned from
> past conversations on this mailing list that often times there is a
> better, more elegant and shorter way to write a program, and I was
> wondering if that's the case here.
>

Why extract the digit and then store it and then sum it?

def digitSum(n):
 return sum([int(digit) for digit in str(n)])

Or
def num2Digits(n):
  return [int(ch) for ch in str(n)]
def digitSum(n):
 return sum(num2Digits(n))


Asokan Pichai

"So, if I look into my foggy crystal ball at the future of computing
science education, I overwhelmingly see the depressing picture of "Business
as usual". The universities will continue to lack the courage to teach hard
science, they will continue to misguide the students, and each next stage
of infantilization of the curriculum will be hailed as educational
progress."

Edsger W Dijkstra in Dec 1988, in an article titled "on the cruelty of
really teaching Computer Science" Link:
http://www.cs.utexas.edu/~EWD/transcriptions/EWD10xx/EWD1036.html
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Converting integers into digit sum (Python 3.3.0)

2013-12-09 Thread Rafael Knuth
Thanks, guys - got it! I was suspecting that my solution is too
complex and that there must be a simpler way to convert integers into
a digit sum. Have a great morning/day/evening, Raf

On Mon, Dec 9, 2013 at 9:23 AM, Amit Saha  wrote:
> On Mon, Dec 9, 2013 at 6:08 PM, Rafael Knuth  wrote:
>> Hej there,
>>
>> I wrote a program that converts an integer into a digit sum:
>>
>> def DigitSum(YourNumber):
>> DigitList = []
>> YourNumber = str(YourNumber)
>> for i in YourNumber:
>> DigitList.append(int(i))
>> print(sum(DigitList))
>>
>> DigitSum(55)
>>
>
>> 10
>>
>> It actually works but I was wondering if that's the only way to solve
>> the task of converting an integer into a digit sum?  I learned from
>> past conversations on this mailing list that often times there is a
>> better, more elegant and shorter way to write a program, and I was
>> wondering if that's the case here.
>
 sum([int(digit) for digit in str(55)])
> 10
>
> That's using list comprehensions. Since a string is basically a
> sequence, you can do the above.
>
> Best,
> Amit.
>
> --
> http://echorand.me
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Converting integers into digit sum (Python 3.3.0)

2013-12-09 Thread Wolfgang Maier
Rafael Knuth  gmail.com> writes:

> 
> Hej there,
> 
> I wrote a program that converts an integer into a digit sum:
> 
> def DigitSum(YourNumber):
> DigitList = []
> YourNumber = str(YourNumber)
> for i in YourNumber:
> DigitList.append(int(i))
> print(sum(DigitList))
> 
> DigitSum(55)
> 
> >>>
> 10
> 
> It actually works but I was wondering if that's the only way to solve
> the task of converting an integer into a digit sum?  I learned from
> past conversations on this mailing list that often times there is a
> better, more elegant and shorter way to write a program, and I was
> wondering if that's the case here.
> 
> Thanks!
> 
> Raf
>

Hi Raf,
your way is legitimate, but can be improved slightly through the use of
comprehensions as others have pointed out
(one side note though since you are asking specifically for Python 3.3:
you can simplify expressions like

sum([int(digit) for digit in str(55)])

to just:

sum(int(digit) for digit in str(55))

turning the comprehension into a generator expression.)



A different approach avoiding the str conversion and working only in the
domain of integer arithmetics would be:

def digsum (integer):
s = 0
while integer != 0:
integer, remainder = divmod(integer, 10)
s += remainder
return s

>From a quick and dirty test, i.e.,
comparing:

for i in range(100):
a=digsum(i)

and

for i in range(100):
a=sum(int(c) for c in str(i))

the arithmetic solution also seems to be a bit faster.

Best,
Wolfgang


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


Re: [Tutor] Converting integers into digit sum (Python 3.3.0)

2013-12-09 Thread Oscar Benjamin
On 9 December 2013 08:08, Rafael Knuth  wrote:
> Hej there,
>
> I wrote a program that converts an integer into a digit sum:
>
> def DigitSum(YourNumber):
> DigitList = []
> YourNumber = str(YourNumber)
> for i in YourNumber:
> DigitList.append(int(i))
> print(sum(DigitList))
>
> DigitSum(55)
>

> 10
>
> It actually works but I was wondering if that's the only way to solve
> the task of converting an integer into a digit sum?  I learned from
> past conversations on this mailing list that often times there is a
> better, more elegant and shorter way to write a program, and I was
> wondering if that's the case here.

I don't know if everyone would consider this more elegant but it's
certainly shorter:

>>> def DigitSum(YourNumber):
... return sum(map(int, YourNumber))
...
>>> DigitSum('55')
10


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


[Tutor] What is a namespace? What is meant by "A namespace is a mapping from names to objects"

2013-12-09 Thread Varuna Seneviratna
>
> Let’s begin with some definitions.
>
> A *namespace* is a mapping from names to objects. Most namespaces are
> currently implemented as Python dictionaries, but that’s normally not
> noticeable in any way (except for performance), and it may change in the
> future. Examples of namespaces are: the set of built-in names (containing
> functions such as abs(),
> and built-in exception names); the global names in a module; and the local
> names in a function invocation. In a sense the set of attributes of an
> object also form a namespace. The important thing to know about namespaces
> is that there is absolutely no relation between names in different
> namespaces; for instance, two different modules may both define a function
> maximize without confusion — users of the modules must prefix it with the
> module name.
>
   The above paragraph was extracted from the description about namespaces
from the Python tutorial(Python Scopes and
Namespaces).I
do not understand what is meant by "A *namespace* is a mapping from names
to objects". How I understand to be a namespace is a particular space
within which a particular name is unique.For a example within the space set
of built-in names the name "abs()" is used to denote the function which
returns the absolute value of a number and no other function(operation) can
be named abs() as a built-in function.Am I right?. But what is meant by "A
*namespace* is a mapping from names to objects"
Thanks Varuna
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Converting integers into digit sum (Python 3.3.0)

2013-12-09 Thread Alan Gauld

On 09/12/13 08:08, Rafael Knuth wrote:


def DigitSum(YourNumber):
 DigitList = []
 YourNumber = str(YourNumber)
 for i in YourNumber:
 DigitList.append(int(i))
 print(sum(DigitList))

DigitSum(55)
10

It actually works but I was wondering if that's the only way to solve
the task


You can simplify the code by using a list comprehension but that's 
really just doing the same thing more compactly.


The other way of doing it is to stay in the number domain and use the 
divmod function to peel off the digits and add them.


>>> total, num = 0, 75
>>> num,rem = divmod(num,10)  # num=7, rem = 5
>>> total = num + rem
>>>

For longer numbers you need to wrap that in a while loop but
you get the idea. However, converting to a string and back
is probably the simplest option.

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

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


Re: [Tutor] What is a namespace? What is meant by "A namespace is a mapping from names to objects"

2013-12-09 Thread Amit Saha
On Mon, Dec 9, 2013 at 2:46 PM, Varuna Seneviratna
 wrote:
>> Let’s begin with some definitions.
>>
>> A namespace is a mapping from names to objects. Most namespaces are
>> currently implemented as Python dictionaries, but that’s normally not
>> noticeable in any way (except for performance), and it may change in the
>> future. Examples of namespaces are: the set of built-in names (containing
>> functions such as abs(), and built-in exception names); the global names in
>> a module; and the local names in a function invocation. In a sense the set
>> of attributes of an object also form a namespace. The important thing to
>> know about namespaces is that there is absolutely no relation between names
>> in different namespaces; for instance, two different modules may both define
>> a function maximize without confusion — users of the modules must prefix it
>> with the module name.
>
>The above paragraph was extracted from the description about namespaces
> from the Python tutorial(Python Scopes and Namespaces).I do not understand
> what is meant by "A namespace is a mapping from names to objects". How I
> understand to be a namespace is a particular space within which a particular
> name is unique.For a example within the space set of built-in names the name
> "abs()" is used to denote the function which returns the absolute value of a
> number and no other function(operation) can be named abs() as a built-in
> function.Am I right?.

You can name anything else as abs - a function, for example. But that
will override the built-in abs() function. For example:

>>> abs(1) # built-in abs
1
>>> def abs(num):
... print('In my abs')
...
...
>>> abs(1)
In my abs


Similarly:

>>> abs = 1
>>> abs()
Traceback (most recent call last):
  File "", line 1, in 
TypeError: 'int' object is not callable


But what is meant by "A namespace is a mapping from
> names to objects"

I don't think I can explain this clearly enough to help elucidate the
literal meaning, so I hope somebody else will.

Best,
Amit.

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


Re: [Tutor] What is a namespace? What is meant by "A namespace is a mapping from names to objects"

2013-12-09 Thread Steven D'Aprano
On Mon, Dec 09, 2013 at 10:16:30AM +0530, Varuna Seneviratna wrote:

> I do not understand what is meant by "A *namespace* is a mapping from names
> to objects". How I understand to be a namespace is a particular space
> within which a particular name is unique.For a example within the space set
> of built-in names the name "abs()" is used to denote the function which
> returns the absolute value of a number and no other function(operation) can
> be named abs() as a built-in function.Am I right?. 

Mostly right. Only one function can be called "abs" in the built-in 
names at the one time. You can (but you shouldn't!) change that 
function, so it is not necessarily the "abs" function that you expect. 
Nevertheless, the basic idea is okay.


> But what is meant by "A
> *namespace* is a mapping from names to objects"

When Python sees the code "abs(x)", it needs to know which function to 
call. The name "abs" alone isn't a function. There needs to be some sort 
of connection, some link, between the name "abs" and the function which 
returns the absolute value. That is what is called a mapping.

Likewise, the name "x" isn't a number. There needs to be a link, a 
mapping, between the name "x" and some value like 23 or -17.

Both functions and data values (like numbers and strings) are objects, 
so instead of saying "a mapping between names and functions or numbers 
or strings or lists or ..." we just say "between names and objects".

When Python sees a name, say, "spam", it first looks in the *local* 
namespace for a variable called "spam". If there is no such variable, it 
then looks in the *global* namespace, and if still not found it looks in 
the built-in namespace. Finally if still not found it raises NameError.

(I have simplified a little bit, but not too much.)

Does this help?



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


Re: [Tutor] Converting integers into digit sum (Python 3.3.0)

2013-12-09 Thread spir

On 12/09/2013 09:08 AM, Rafael Knuth wrote:

Hej there,

I wrote a program that converts an integer into a digit sum:

def DigitSum(YourNumber):
 DigitList = []
 YourNumber = str(YourNumber)
 for i in YourNumber:
 DigitList.append(int(i))
 print(sum(DigitList))

DigitSum(55)




10

It actually works but I was wondering if that's the only way to solve
the task of converting an integer into a digit sum?  I learned from
past conversations on this mailing list that often times there is a
better, more elegant and shorter way to write a program, and I was
wondering if that's the case here.


Tu sum it up (aha!): you algorithm is the right and only one, but there are ways 
in python to express it more succintly, if not elegantly.


What is missing is checking that the input is actually a natural number 
(unsigned integer), and a number at all. In particular, I guess from the name 
YourNumber it is supposed to come from user input. (In the following, I stop the 
program with an error message, because you may not know yet about exceptions and 
exception catching.)


Another point is changing the name of the str variable: it does not mean the 
same thing and represents another programming element, so should not be called 
the same way. Since we are at naming:
* In python common conventions, names with capitals (as yours) represent 
programmer-defined types (you may not know that yet), rather than functions or 
simple variables.
* Your function name looks like telling us it produces a sum, while instead it 
writes it.


Without using comprehensions (maybe a little advanced), you can still (learn to) 
directly traverse a string as a sequence of digit characters


All in all, it could look like:

def write_digit_sum (your_number):
# Check input:
# (Python has not type for natural numbers.)
if (type(your_number) is not int) or (your_number < 0):
msg = "Input to 'write_digit_sum' should be a natural number. Found: "
print(msg + repr(your_number))  # using repr in case it is a string
exit()
# If we arrive here, your_number is ok.

# Write sum:
numeral = str(your_number)
summ = 0
for digit in numeral:
summ += int(digit)
print(summ)

def test_write_digit_sum ():
write_digit_sum(0)
write_digit_sum(1)
write_digit_sum(345)
write_digit_sum(9)

# execution failures on invalid input:
# (to comment out once tested)

#~ write_digit_sum(-1)
#~ write_digit_sum(1.1)
#~ write_digit_sum('a')
write_digit_sum((1,2,3))

test_write_digit_sum()

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


Re: [Tutor] Converting integers into digit sum (Python 3.3.0)

2013-12-09 Thread Wolfgang Maier
spir  gmail.com> writes:

> 
> Tu sum it up (aha!): you algorithm is the right and only one

No, it's not the only one. It's certainly the most obvious one, but there is
also the pure numbers approach pointed out by me and Alan.




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


Re: [Tutor] Converting integers into digit sum (Python 3.3.0)

2013-12-09 Thread Rafael Knuth
>> Tu sum it up (aha!): you algorithm is the right and only one
>
> No, it's not the only one. It's certainly the most obvious one, but there is
> also the pure numbers approach pointed out by me and Alan.

So far I received 7 different alternative suggestions, both pure
numbers & mixed int/str approach, which is great because I learn far
more than I would expect given that the subject discussed is a tiny,
little string to digit sum program. I play around with each piece of
code I receive, I take notes and I memorize as much as possible for
upcoming challenges. Although it's sometimes confusing to me as a
novice to programming, I actually like the idea that one and the same
task can be solved in different ways in Python (it spurs my
creativity). And, again: Thank you all for your elaborate and
extremely helpful responses!
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] What is a namespace? What is meant by "A namespace is a mapping from names to objects"

2013-12-09 Thread spir

On 12/09/2013 05:46 AM, Varuna Seneviratna wrote:


Let’s begin with some definitions.

A *namespace* is a mapping from names to objects. Most namespaces are
currently implemented as Python dictionaries, but that’s normally not
noticeable in any way (except for performance), and it may change in the
future. Examples of namespaces are: the set of built-in names (containing
functions such as abs(),
and built-in exception names); the global names in a module; and the local
names in a function invocation. In a sense the set of attributes of an
object also form a namespace. The important thing to know about namespaces
is that there is absolutely no relation between names in different
namespaces; for instance, two different modules may both define a function
maximize without confusion — users of the modules must prefix it with the
module name.


The above paragraph was extracted from the description about namespaces
from the Python tutorial(Python Scopes and
Namespaces).I
do not understand what is meant by "A *namespace* is a mapping from names
to objects". How I understand to be a namespace is a particular space
within which a particular name is unique.For a example within the space set
of built-in names the name "abs()" is used to denote the function which
returns the absolute value of a number and no other function(operation) can
be named abs() as a built-in function.Am I right?. But what is meant by "A
*namespace* is a mapping from names to objects"
Thanks Varuna


A namespace (yes, the term is weird, even wrong, but this applies to nearly all 
terms in programming) is a set of symbols. A symbol in programming is:
* like any symbol a relation between a form (the id, or name) and a meaning (or 
"semantics" if you want to look pedantic)
* plus, in programming, nearly all symbols relate with elements of the program, 
usually called data, value, or object.


# definition of a symbol
board_size = 8

After that definition:

id: "board_size"  <---> meaning: 
(in code, maybe memory) (in our minds)
^
|
v
value: 8 (type `int`)
(in code and computer memory)

A namespace is a set of such symbols, whatever their value. Since an id 
(identifier) by definition identifies a symbol, it can only be unique. In python 
and many other languages, there are such kinds of namespace:
* function scope: the local symbols of a function (parameters, constants, 
variables, other function or types defined there...)
* global space: should be used to define the top-level elements of the world 
(the system you describe), else avoided
* composite elements: objects usually hold attributes which are sub-symbols, 
thus they are namespaces as well. For instance, a position could hold (x, y) or 
(radius, angle).


Some languages make separate namespaces for different kinds of elements. In 
particular, functions or types may be stored apart; this is not the case in Python.


You will also find the term "symbol table", which would be, and in fact is, a 
far better term for "namespace", but used in compilation. In addition to name 
and value, a compiler stores other information about symbols found in a program 
it is decoding.


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


Re: [Tutor] Converting integers into digit sum (Python 3.3.0)

2013-12-09 Thread spir

On 12/09/2013 02:42 PM, Rafael Knuth wrote:

Tu sum it up (aha!): you algorithm is the right and only one


No, it's not the only one. It's certainly the most obvious one, but there is
also the pure numbers approach pointed out by me and Alan.


So far I received 7 different alternative suggestions, both pure
numbers & mixed int/str approach, which is great because I learn far
more than I would expect given that the subject discussed is a tiny,
little string to digit sum program. I play around with each piece of
code I receive, I take notes and I memorize as much as possible for
upcoming challenges. Although it's sometimes confusing to me as a
novice to programming, I actually like the idea that one and the same
task can be solved in different ways in Python (it spurs my
creativity). And, again: Thank you all for your elaborate and
extremely helpful responses!


It is indeed a tiny little piece of code, but an interesting one, and also with 
fundaments of computing! Think at this:
* all programming languages have to decode numerals (number written 
representations) into numbers (or rather their representations in memory)
* sum is also a basic algo, and the archetype of a whole series of "aggregating" 
algos, that turn a set of elements into a single element by operating on each 
one (and there are tons of discussions on the proper way to do that)


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


Re: [Tutor] Converting integers into digit sum (Python 3.3.0)

2013-12-09 Thread spir

On 12/09/2013 02:29 PM, Wolfgang Maier wrote:

spir  gmail.com> writes:



Tu sum it up (aha!): you algorithm is the right and only one


No, it's not the only one. It's certainly the most obvious one, but there is
also the pure numbers approach pointed out by me and Alan.


You are right in a sense, but this is what int() does, isn't it? So in another 
sense I thought it is still the same algo, and it was simpler to present it that 
way. But I also agree with your point of view.


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


Re: [Tutor] Converting integers into digit sum (Python 3.3.0)

2013-12-09 Thread Wolfgang Maier
spir  gmail.com> writes:

> 
> On 12/09/2013 02:29 PM, Wolfgang Maier wrote:
> > spir  gmail.com> writes:
> >
> >>
> >> Tu sum it up (aha!): you algorithm is the right and only one
> >
> > No, it's not the only one. It's certainly the most obvious one, but there is
> > also the pure numbers approach pointed out by me and Alan.
> 
> You are right in a sense, but this is what int() does, isn't it? So in
another 

Interesting question!
I would assume str() and int() to use a similar algorithm, but I never
looked at their actual implementation, so this is just speculation.
Also, as a general rule I thought one shouldn't rely on implementation
details since they could change (admittedly, quite unlikely for something as
basic as this though).

> sense I thought it is still the same algo, and it was simpler to present
it that 
> way. But I also agree with your point of view.
> 
> Denis

Fair enough.

Best,
Wolfgang



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


Re: [Tutor] Converting integers into digit sum (Python 3.3.0)

2013-12-09 Thread Alan Gauld

On 09/12/13 13:48, spir wrote:

On 12/09/2013 02:29 PM, Wolfgang Maier wrote:

spir  gmail.com> writes:



Tu sum it up (aha!): you algorithm is the right and only one


No, it's not the only one. ...
also the pure numbers approach pointed out by me and Alan.


You are right in a sense, but this is what int() does, isn't it?


No. int() can be done in several ways but usually it's based on taking 
the character code and adding/subtracting some base value. (or uses a 
lookup table). But to get the individual characters for conversion
it will loop over a string so in that respect its similar to the string 
based approaches. But the OP didn't start with a string, he started with 
an int.



another sense I thought it is still the same algo,


The string based algorithms are effectively all the same whether
using loops, comprehensions or map.

But the numerical solution is fundamentally different since it never 
looks at the characters it relies on math to generate the digits.


Neither is better than the other; they both work reasonably efficiently.
But they are fundamentally different algorithms.

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

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


Re: [Tutor] What is a namespace? What is meant by "A namespace is a mapping from names to objects"

2013-12-09 Thread Alan Gauld

On 09/12/13 04:46, Varuna Seneviratna wrote:


do not understand what is meant by "A /namespace/ is a mapping from
names to objects". How I understand to be a namespace is a particular
space within which a particular name is unique.


That's correct.
But a name on its own can refer to anything.
But it can't refer to nothing, in Python every name must refer to some 
kind of object for it to exist (even if the object is None).


So for python to know what a given name refers to it must have a mapping 
between name and object(data, function, class etc)



space set of built-in names the name "abs()" is used to denote the
function which returns the absolute value of a number and no other
function(operation) can be named abs() as a built-in function.


That's not true. Names and objects (including functions) are only 
loosely bound together. I can easily create another name for the

abs function:

>>> oldabs = abs
>>> oldabs(5) == abs(5)
True

I can even name a completely different function 'abs'

>>> def abs(n): return n

Now abs is a completely different function, but oldabs is still 
referring to the original built-in function.


Every name refers to exactly one object, but what object it refers to is 
not necessarily what it started out as. And there may be several names 
for the same object. So you need to maintain a mapping. And that mapping 
defines what the namespace contains.


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

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


Re: [Tutor] Converting integers into digit sum (Python 3.3.0)

2013-12-09 Thread spir

On 12/09/2013 03:49 PM, Alan Gauld wrote:

On 09/12/13 13:48, spir wrote:

On 12/09/2013 02:29 PM, Wolfgang Maier wrote:

spir  gmail.com> writes:



Tu sum it up (aha!): you algorithm is the right and only one


No, it's not the only one. ...
also the pure numbers approach pointed out by me and Alan.


You are right in a sense, but this is what int() does, isn't it?


No. int() can be done in several ways but usually it's based on taking the
character code and adding/subtracting some base value. (or uses a lookup table).
But to get the individual characters for conversion
it will loop over a string so in that respect its similar to the string based
approaches. But the OP didn't start with a string, he started with an int.


another sense I thought it is still the same algo,


The string based algorithms are effectively all the same whether
using loops, comprehensions or map.

But the numerical solution is fundamentally different since it never looks at
the characters it relies on math to generate the digits.

Neither is better than the other; they both work reasonably efficiently.
But they are fundamentally different algorithms.


All right; I thought int numeral decoding was always more or less the same algo 
(for having studied and implemented several versions), using integer division 
remainders, but obviously ws wrong. Thank you for the correction, Alan.


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


Re: [Tutor] No module named '_tkinter'

2013-12-09 Thread pierre dagenais


On 13-12-08 10:57 PM, Reuben wrote:
> Can you try importing the module '_tkinter'
> On 09-Dec-2013 6:43 AM, "pierre dagenais"  wrote:
> 
>> Hi,
>> I'm running Ubuntu 10.04 and I've installed python 3.3.3 from the
>> tarball at http://python.org/ftp/python/3.3.3/Python-3.3.3.tar.xz
>>
>> Here is the error I get when trying to run tkinter.
>>
>> pierre@Sprint:~$ python3.3
>> Python 3.3.3 (default, Dec  2 2013, 11:10:53)
>> [GCC 4.6.3] on linux
>> Type "help", "copyright", "credits" or "license" for more information.
> import tkinter
>> Traceback (most recent call last):
>>   File "", line 1, in 
>>   File "/usr/local/lib/python3.3/tkinter/__init__.py", line 40, in 
>> import _tkinter # If this fails your Python may not be configured for
>> Tk
>> ImportError: No module named '_tkinter'
>
>>
>> I've tried installing python3-tk from the Ubuntu repository but it
>> doesn't help.
>>
>> Any suggestion on how to install the tkinter module with this version?
>>
>> Thank you,
>>
>> PierreD.
>> ___
>> Tutor maillist  -  Tutor@python.org
>> To unsubscribe or change subscription options:
>> https://mail.python.org/mailman/listinfo/tutor
>>
> 
I get a similar error.

ImportError: No module named '_tkinter'
>>> import _tkinter
Traceback (most recent call last):
  File "", line 1, in 
ImportError: No module named '_tkinter'
>>>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] No module named '_tkinter' ***solved***

2013-12-09 Thread pierre dagenais


On 13-12-09 03:14 AM, eryksun wrote:
> On Sun, Dec 8, 2013 at 2:36 PM, pierre dagenais  wrote:
>> I'm running Ubuntu 10.04 and I've installed python 3.3.3 from the
>> tarball at http://python.org/ftp/python/3.3.3/Python-3.3.3.tar.xz
>>
>> Here is the error I get when trying to run tkinter.
>>
>> ImportError: No module named '_tkinter'
>>
>> I've tried installing python3-tk from the Ubuntu repository but it
>> doesn't help.
> 
> It looks like you didn't install the development dependencies before
> building. The build-dep for Lucid's 3.1 package should do the trick.
> 
> sudo apt-get update
> sudo apt-get build-dep python3.1
> 
python3.1 is not available on precise pangolin, so used python3.2 instead.

> For good measure run the following, too:
> 
> sudo apt-get install build-essential \
>   libbz2-dev libdb-dev libexpat1-dev libffi-dev \
>   libgdbm-dev liblzma-dev libncursesw5-dev \
>   libreadline6-dev libsqlite3-dev libssl-dev \
>   tk-dev zlib1g-dev
> 
A few of these were missing, installed now.

> Then do a `make clean` and rebuild.
> 
Don't know what a 'make clean' is. I skipped it and rebuilt, looks good
now. I can 'import tkinter' without error.


Thank you, much appreciated,

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


Re: [Tutor] Converting integers into digit sum (Python 3.3.0)

2013-12-09 Thread Dave Angel

On Mon, 09 Dec 2013 17:00:49 +0100, spir  wrote:

On 12/09/2013 03:49 PM, Alan Gauld wrote:
> On 09/12/13 13:48, spir wrote:
>> On 12/09/2013 02:29 PM, Wolfgang Maier wrote:
>> You are right in a sense, but this is what int() does, isn't it?


> No. int() can be done in several ways but usually it's based on 

taking the
> character code and adding/subtracting some base value. (or uses a 

lookup table).

> But to get the individual characters for conversion
> it will loop over a string so in that respect its similar to the 

string based
> approaches. But the OP didn't start with a string, he started 

with an int.

It's str() which is similar,  not int ()

--
DaveA

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


Re: [Tutor] What is a namespace? What is meant by "A namespace is a mapping from names to objects"

2013-12-09 Thread Marc Tompkins
On Sun, Dec 8, 2013 at 8:46 PM, Varuna Seneviratna <
varunasenevira...@gmail.com> wrote:

> But what is meant by "A *namespace* is a mapping from names to objects"
>
Steven touched on this, but I'd like to emphasize: in Python, EVERYTHING is
an object - variables, functions, integers, strings, you name it.  (Even
names and namespaces, but that might be getting a little TOO meta.)
When I first came to Python, after years of languages where some things are
objects and other things aren't, this concept gave me a little trouble;
once I got my head around it, namespaces made sense too.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Converting integers into digit sum (Python 3.3.0)

2013-12-09 Thread Roel Schroeven

Alan Gauld schreef:

On 09/12/13 13:48, spir wrote:

On 12/09/2013 02:29 PM, Wolfgang Maier wrote:

spir  gmail.com> writes:



Tu sum it up (aha!): you algorithm is the right and only one

No, it's not the only one. ...
also the pure numbers approach pointed out by me and Alan.

You are right in a sense, but this is what int() does, isn't it?


No. int() can be done in several ways but usually it's based on taking 
the character code and adding/subtracting some base value. (or uses a 
lookup table). But to get the individual characters for conversion
it will loop over a string so in that respect its similar to the string 
based approaches. But the OP didn't start with a string, he started with 
an int.


spir should have said "..., but this is what str() does, ..." I think.

Extracting the individual digits from the number is the core of both 
algorithms, and I would think str() uses an algorithm similar to the 
divmod() approach (but in C instead of Python, possible simply using the 
relevant function from the C standard library).


The difference is that str() converts the digits to chars (which have to 
be converted back to ints later) while the pure divmod() approach 
doesn't do that.


All in all I think the two algorithms don't differ that much, the main 
difference being that in the str() approach part of the algorithm is 
hidden behind the str() call.




--
"Met een spitsvondig citaat bewijs je niets."
-- Voltaire

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


Re: [Tutor] Converting integers into digit sum (Python 3.3.0)

2013-12-09 Thread Alan Gauld

On 09/12/13 17:57, Roel Schroeven wrote:


You are right in a sense, but this is what int() does, isn't it?


No. int() can be done in several ways...


spir should have said "..., but this is what str() does, ..." I think.


Doh! Yes, that makes sense I should have realized.


All in all I think the two algorithms don't differ that much, the main
difference being that in the str() approach part of the algorithm is
hidden behind the str() call.


The common feature in both is that you extract the individual digits and 
add them.


The bit that is different is how you get the individual digits
(by building a string or by using some math). The fact that the
string conversion uses the same math approach(presumably) is
a coincidental implementation detail not part of the algorithm.

Incidentally, I just remembered another completely different
way to do it, although I can't recall how it works! Maybe one
of the math gurus can explain it, and how to extend it. This
version only works for 2 digit numbers... and has a huge gotcha!

To get the sum for a two digit number X using 17 as example...

subtract X from 100 17->83
Sum the digits of that number   83->11
Subract that number from 19 11->8
That's the sum of the digits of X

Of course the problem is the second step since it requires
you to sum the digits of the new number!

I've no idea how I remembered that or from where but it
popped into my brain. It seems to work reliably but I've no
idea how... :-/



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

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


[Tutor] Writing to CSV string containing quote and comma

2013-12-09 Thread J Sutar
# Re-sending from registered email address #.

Hi,

Posting for first time so hope I get the forum etiquette and rules right,
please let me know otherwise.

I'm trying to write to csv a string which contains double quotation marks
and a comma however I'm finding that the write reads the comma as a
delimiter. If try wrap the string around double quotes it clashes with the
raw quotes originally within the string text (which I'd like to/must
preserve). Replacing double quotes with single quotes is neither an option
as I may have text containing single quotes (as in the number four example
below).


Numbers=[1,2,3,4,5]
Words=["One", "Two", "Three, with comma", "Four 'with single quote'",
"Five"]

NumPlusWordQuoted=[]
for (i, j) in zip(Numbers,Words):
NumPlusWordQuoted.append([str(i) + " " + chr(34) +  j + chr(34)])

print NumPlusWordQuoted

outputfile="c:/temp/test.csv"
ofile = open(outputfile, 'wb')
ofile.write(",".join(str(n) for n in Numbers)) # 1. Numbers works ok

ofile.write("\n" + ",".join(chr(34) + w + chr(34) for w in Words)) #
2. Words works ok

ofile.write("\n"+",".join(chr(34) + i[0] + chr(34) for i in
NumPlusWordQuoted)) #3. Number plus words in quotes fails

ofile.close()


A helping hand on this would be very much appreciated.

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


Re: [Tutor] Writing to CSV string containing quote and comma

2013-12-09 Thread Joel Goldstick
On Mon, Dec 9, 2013 at 4:52 PM, J Sutar  wrote:

> # Re-sending from registered email address #.
>
> Hi,
>
> Posting for first time so hope I get the forum etiquette and rules right,
> please let me know otherwise.
>
> I'm trying to write to csv a string which contains double quotation marks
> and a comma however I'm finding that the write reads the comma as a
> delimiter. If try wrap the string around double quotes it clashes with the
> raw quotes originally within the string text (which I'd like to/must
> preserve). Replacing double quotes with single quotes is neither an option
> as I may have text containing single quotes (as in the number four example
> below).
>
> Python has a csv reader and writer module.  You should check it out.
>
>
> A helping hand on this would be very much appreciated.
>
> Thanks in advance.
> Jignesh
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>
>


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


Re: [Tutor] Converting integers into digit sum (Python 3.3.0)

2013-12-09 Thread Dave Angel
On Mon, 09 Dec 2013 20:27:38 +, Alan Gauld 
 wrote:

Incidentally, I just remembered another completely different
way to do it, although I can't recall how it works! Maybe one
of the math gurus can explain it, and how to extend it. This
version only works for 2 digit numbers... and has a huge gotcha!




To get the sum for a two digit number X using 17 as example...




subtract X from 100 17->83
Sum the digits of that number   83->11
Subract that number from 19 11->8
That's the sum of the digits of X



popped into my brain. It seems to work reliably but I've no


Unfortunately it doesn't work for 10, 20, ...
This is related to a technique called casting out nines (and nine is 
magic because it's one less than the base we work in).


When you cast out nines you get the remainder, modulo 9. But to cast 
out nines you keep adding up the digits till you get a one digit 
result. So:


149 == 14 == 5.

There's more but it's probably more fruitful to read the Wikipedia 
post.


--
DaveA

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


Re: [Tutor] Writing to CSV string containing quote and comma

2013-12-09 Thread Steven D'Aprano
Joel, 

You don't appear to have actually written anything in your response. 
Every line in your post starts with a ">" quoting J Sutar's original 
post, with nothing new added apart from your signature at the end.




On Mon, Dec 09, 2013 at 04:57:50PM -0500, Joel Goldstick wrote:
> On Mon, Dec 9, 2013 at 4:52 PM, J Sutar  wrote:
> 
> > # Re-sending from registered email address #.
> >
> > Hi,
> >
> > Posting for first time so hope I get the forum etiquette and rules right,
> > please let me know otherwise.
> >
> > I'm trying to write to csv a string which contains double quotation marks
> > and a comma however I'm finding that the write reads the comma as a
> > delimiter. If try wrap the string around double quotes it clashes with the
> > raw quotes originally within the string text (which I'd like to/must
> > preserve). Replacing double quotes with single quotes is neither an option
> > as I may have text containing single quotes (as in the number four example
> > below).
> >
> > Python has a csv reader and writer module.  You should check it out.
> >
> >
> > A helping hand on this would be very much appreciated.
> >
> > Thanks in advance.
> > Jignesh
> >
> > ___
> > Tutor maillist  -  Tutor@python.org
> > To unsubscribe or change subscription options:
> > https://mail.python.org/mailman/listinfo/tutor
> >
> >
> 
> 
> -- 
> Joel Goldstick
> http://joelgoldstick.com

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

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


Re: [Tutor] Writing to CSV string containing quote and comma

2013-12-09 Thread Joel Goldstick
On Mon, Dec 9, 2013 at 5:28 PM, Steven D'Aprano  wrote:

> Joel,
>
> You don't appear to have actually written anything in your response.
> Every line in your post starts with a ">" quoting J Sutar's original
> post, with nothing new added apart from your signature at the end.
>
>
>
More 'google (gmail) hate'!.  Sorry y'all.  I actually wrote this:

Python has a csv reader and writer module.  You should check it out.  It
makes lots of csv stuff very easy
--

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



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


Re: [Tutor] Writing to CSV string containing quote and comma

2013-12-09 Thread Dave Angel
On Tue, 10 Dec 2013 09:28:32 +1100, Steven D'Aprano 
 wrote:
Joel, 
You don't appear to have actually written anything in your 
response. 
Every line in your post starts with a ">" quoting J Sutar's 
original 

post, with nothing new added apart from your signature at the end.


I cannot read either of those posts, but I'd guess the line starting 
"Python has a csv" is probably Joel's.


Anybody got a suggestion for a newsreader for Android that doesn't 
throw out all these messages with html in them?
I'm using groundhog and it gets frustrating. 


On Mon, Dec 09, 2013 at 04:57:50PM -0500, Joel Goldstick wrote:
> On Mon, Dec 9, 2013 at 4:52 PM, J Sutar  wrote:





> > Python has a csv reader and writer module.  You should check it 

out.

--
DaveA

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


Re: [Tutor] Converting integers into digit sum (Python 3.3.0)

2013-12-09 Thread Alan Gauld

On 09/12/13 22:28, Dave Angel wrote:

On Mon, 09 Dec 2013 20:27:38 +, Alan Gauld
 wrote:

Incidentally, I just remembered another completely different
way to do it, although I can't recall how it works!



Unfortunately it doesn't work for 10, 20, ...


Ah, I knew it must be too good to be true :-)


This is related to a technique called casting out nines (and nine is
magic because it's one less than the base we work in).


OK, Thanks for the pointer.

I still have no idea how I knew about that technique but it just
appeared, fully formed, in my brain. Bizarro!

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

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


Re: [Tutor] Writing to CSV string containing quote and comma

2013-12-09 Thread Steven D'Aprano
On Mon, Dec 09, 2013 at 09:52:34PM +, J Sutar wrote:

> I'm trying to write to csv a string which contains double quotation marks
> and a comma however I'm finding that the write reads the comma as a
> delimiter. If try wrap the string around double quotes it clashes with the
> raw quotes originally within the string text (which I'd like to/must
> preserve). Replacing double quotes with single quotes is neither an option
> as I may have text containing single quotes (as in the number four example
> below).

Rather than manually writing strings to a file and hoping you get the 
rules right for a CSV file, you might find that it is easier to use 
Python's standard CSV module. It will handle all the escaping and 
quoting for you.

http://docs.python.org/2/library/csv.html

That is the best way to handle CSV in Python.

I haven't tried this, but I think this should handle your problem:


import csv

words = ["One", "Two", "Three, with comma", "Four 'with single quote'", "Five"]
numbers = [1, 2, 3, 4, 5]

with open("c:/temp/test.csv", "wb") as f:
writer = csv.writer(f)
writer.writerow(numbers)
writer.writerow(words)
writer.writerow(["%d %s" % (n, s) for n, s in zip(numbers, words)])



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


Re: [Tutor] Writing to CSV string containing quote and comma

2013-12-09 Thread J Sutar
Thanks all. Yes csv module make it whole lot easier. I did try using it
before posting to list but couldn't get it working for some reason.

Steven, I updated the very last line of code as below, as I need to get the
word wrapped around quotes. Is that a good way of achieving that?

import csv
words = ["One", "Two", "Three, with comma", "Four 'with single quote'",
"Five"]
numbers = [1, 2, 3, 4, 5]
with open("c:/temp/test3.csv", "wb") as f:
writer = csv.writer(f)
writer.writerow(numbers)
writer.writerow(words)
writer.writerow([str(n) + " " + chr(34) + s + chr(34) for n, s in
zip(numbers, words)])


On 9 December 2013 22:54, Steven D'Aprano  wrote:

> On Mon, Dec 09, 2013 at 09:52:34PM +, J Sutar wrote:
>
> > I'm trying to write to csv a string which contains double quotation marks
> > and a comma however I'm finding that the write reads the comma as a
> > delimiter. If try wrap the string around double quotes it clashes with
> the
> > raw quotes originally within the string text (which I'd like to/must
> > preserve). Replacing double quotes with single quotes is neither an
> option
> > as I may have text containing single quotes (as in the number four
> example
> > below).
>
> Rather than manually writing strings to a file and hoping you get the
> rules right for a CSV file, you might find that it is easier to use
> Python's standard CSV module. It will handle all the escaping and
> quoting for you.
>
> http://docs.python.org/2/library/csv.html
>
> That is the best way to handle CSV in Python.
>
> I haven't tried this, but I think this should handle your problem:
>
>
> import csv
>
> words = ["One", "Two", "Three, with comma", "Four 'with single quote'",
> "Five"]
> numbers = [1, 2, 3, 4, 5]
>
> with open("c:/temp/test.csv", "wb") as f:
> writer = csv.writer(f)
> writer.writerow(numbers)
> writer.writerow(words)
> writer.writerow(["%d %s" % (n, s) for n, s in zip(numbers, words)])
>
>
>
> --
> Steven
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Writing to CSV string containing quote and comma

2013-12-09 Thread Danny Yoo
>
>  I'm trying to write to csv a string which contains double quotation
>> marks and a comma however I'm finding that the write reads the comma as a
>> delimiter. If try wrap the string around double quotes it clashes with the
>> raw quotes originally within the string text (which I'd like to/must
>> preserve). Replacing double quotes with single quotes is neither an option
>> as I may have text containing single quotes (as in the number four example
>> below).
>>
>> Python has a csv reader and writer module.  You should check it out.
>>
>>
Hi Jignesh,

I agree with Joel.  Don't try to build a csv writer from scratch unless you
have unusual requirements.  Whatever rules you're using to try to escape
quotes are most likely incomplete.


Here's an example:


>>> import io
>>> import csv
>>> b = io.BytesIO()
>>> writer = csv.writer(b)
>>> writer.writerow(["One", "Two", "Three, with comma", "Four 'with single
quote'", "Five"])
59L
>>> print(b.getvalue())
One,Two,"Three, with comma",Four 'with single quote',Five

## Let's try another example:
>>> writer.writerow(["This has a quote: \"", "and another one: '"])
43L
>>> print(b.getvalue())
One,Two,"Three, with comma",Four 'with single quote',Five
"This has a quote: """,and another one: '



As we can see from this example, the csv library knows how to deal with
commas, and also how to escape double quotes, all using the rules described
in RFC 4180.


You can find out more about the csv library here:

http://docs.python.org/3/library/csv.html
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Writing to CSV string containing quote and comma

2013-12-09 Thread Steven D'Aprano
On Mon, Dec 09, 2013 at 11:14:38PM +, J Sutar wrote:

> Steven, I updated the very last line of code as below, as I need to get the
> word wrapped around quotes. Is that a good way of achieving that?
[...]
> writer.writerow([str(n) + " " + chr(34) + s + chr(34) for n, s in
>  zip(numbers, words)])


Not really a good way, no.

Python has two different quote characters ' and " so you can use one for 
delimiters and the other inside the string:

s = "this string contains ' single quote"
s = 'this string contains " double quote'

If you need both, you can escape the one that matches the delimiter:

s = 'this string contains both \' single and " double quotes'

Rather than assembling the final string piece by piece using string 
concatenation (the + operator), it is usually better to use template 
strings. Python has three standard ways to do template strings:

the % operator (like C's printf);

the format() method;

the string module's Template class.

I won't talk about the Template class, as it is fairly specialised and 
less convenient. Compare your version:

str(number) + " " + chr(34) + word + chr(34)

with the formatting versions:

'%d "%s"' % (number, word)

'{0} "{1}"'.format(number, word)


In Python 2.7, you can abbreviate that last one slightly:

'{} "{}"'.format(number, word)


Either should be preferred to building the string by hand with + signs. 
The rule of thumb I use is to say that adding two substrings together is 
fine, if I need more than one + sign I use a format string. So these 
would be okay:

plural = word + "s"
line = sentence + '\n'

but anything more complex and I would use % or format().



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


Re: [Tutor] Writing to CSV string containing quote and comma

2013-12-09 Thread Alan Gauld

On 09/12/13 23:46, Steven D'Aprano wrote:


Python has two different quote characters ' and " so you can use one for
delimiters and the other inside the string:


And if you need both you can also use triple quotes.


If you need both, you can escape the one that matches the delimiter:

s = 'this string contains both \' single and " double quotes'


Or using triple quotes:

> s = '''this string contains both ' single and " double quotes'''

Python will then do the escaping for you.

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

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


Re: [Tutor] Converting integers into digit sum (Python 3.3.0)

2013-12-09 Thread spir

On 12/09/2013 09:27 PM, Alan Gauld wrote:

On 09/12/13 17:57, Roel Schroeven wrote:


You are right in a sense, but this is what int() does, isn't it?


No. int() can be done in several ways...


spir should have said "..., but this is what str() does, ..." I think.


Doh! Yes, that makes sense I should have realized.


Yep! I was not attentive enough (and/or maybe it was late, here). My bad, sorry 
for the confusion..


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


Re: [Tutor] Unit testing in Python (3.3.0) for beginners

2013-12-09 Thread Amit Saha
On Sun, Dec 8, 2013 at 8:22 PM, Rafael Knuth  wrote:
> Hey there,
>
> I struggle to understand what unit testing specifically means in
> practice and how to actually write unit tests for my code (my gut is
> telling me that it's a fairly important concept to understand).
>
> Over the last few days I learned how to write and work with classes, I
> learned quite a lot about functions, nested loops and I currently walk
> through every program in the Python.org wiki "Simple Programs"
> https://wiki.python.org/moin/SimplePrograms ... and here's the unit
> test program they provide:
>
> import unittest
> def median(pool):
> copy = sorted(pool)
> size = len(copy)
> if size % 2 == 1:
> return copy[(size - 1) / 2]
> else:
> return (copy[size/2 - 1] + copy[size/2]) / 2
> class TestMedian(unittest.TestCase):
> def testMedian(self):
> self.failUnlessEqual(median([2, 9, 9, 7, 9, 2, 4, 5, 8]), 7)
> if __name__ == '__main__':
> unittest.main()
>
> Also, I went through the "Beginning Test-Driven Development in Python"
> http://net.tutsplus.com/tutorials/python-tutorials/test-driven-development-in-python/
> but I have to admit I still don't fully understand how unit tests work
> in practice and how to write my own unit tests.
>
> As it turned out over the last few weeks, the best modus operandi for
> me as an absolute beginner is to grab a small program, take it apart
> in the first place, understand how each component works through trial
> & error, then put all those pieces together and then I kind of get the
> big picture. Once I "get  it" I practice as much as possible to
> memorize what I just learned and *then* I start readying as many
> blogs, tutorials etc. as possible to deepen my understanding (I
> frankly find most tutorials & blogs too complex and confusing from a
> beginner's viewpoint, and I learn faster by taking code apart and
> learning through trial & error in the first place). So, what I am
> specifically searching for is a very simple code sample which I can
> take apart and iterate through each component, and I was wondering if
> you are aware of resources that might be helpful?
>
> My understanding of unit testing is that I have to embed my code into
> a test and then I have to define conditions under which my code is
> supposed to fail and pass. Is that assumption correct?
>
> I am a bit lost & confused here .. any help & hing is highly appreciated!

Here is an article I came across today that you may find useful:
http://www.jeffknupp.com/blog/2013/12/09/improve-your-python-understanding-unit-testing/

Best, Amit.

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


Re: [Tutor] Unit testing in Python (3.3.0) for beginners

2013-12-09 Thread Danny Yoo
By the way, there's a nice book by Kent Beck called "Test Driven
Development by Example" that might be helpful to look at:

http://en.wikipedia.org/wiki/Test-Driven_Development_by_Example
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor