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

2013-12-10 Thread Rafael Knuth
Hej there,

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

Thanks!

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

I don't understand yet what the "map" function does - can you explain?
I read the Python 3.3.0 documentation on that topic but I frankly
didn't really understand it
http://docs.python.org/3/library/functions.html#map. My search for
simple code examples using "map" wasn't really fruitful either.

Other than that, I went through each of the 7 alternatives to my
"Integer to Digit Sum" program you guys sent me, I understand what
each of those programs does. My favorite one is:

def DigSum (integer):
s = 0
while integer != 0:
integer, remainder = divmod(integer, 10)
s += remainder
print(s)

DigSum(537)

It's really a beautiful, elegant solution IMHO and way better than my
original code (convert int to string, store each digit in an empty
list, then convert them back to int and sum them).

Again, thank you all!

Raf
___
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-10 Thread Jignesh Sutar
Thanks Steve, Alan. Sound advice. Very much a novice so trying to pick up
good habits. Will definitely take on board your comments!
Thanks again.
Jignesh


On 10 December 2013 00:46, Alan Gauld  wrote:

> 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
>
___
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-10 Thread Oscar Benjamin
On 10 December 2013 09:39, Rafael Knuth  wrote:
>
> def DigitSum(YourNumber):
>> ... return sum(map(int, YourNumber))
>> ...
> DigitSum('55')
>> 10
>
> I don't understand yet what the "map" function does - can you explain?
> I read the Python 3.3.0 documentation on that topic but I frankly
> didn't really understand it
> http://docs.python.org/3/library/functions.html#map. My search for
> simple code examples using "map" wasn't really fruitful either.

The map function is easier to understand in Python 2. It takes a
function and a list (or any sequence/iterable) and calls the function
on each element of the list. The values returned from the function are
placed in a new list that is returned by map:

$ python
Python 2.7.5 (default, May 15 2013, 22:43:36) [MSC v.1500 32 bit
(Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> def square(x):
... return x * x
...
>>> values = [1, 3, 2, 4]
>>> map(square, values)
[1, 9, 4, 16]

In Python 3 the situation is slightly more complicated since map
returns an iterator rather than a list:

$ python3
Python 3.3.2 (v3.3.2:d047928ae3f6, May 16 2013, 00:03:43) [MSC v.1600
32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> def square(x):
... return x * x
...
>>> values = [1, 3, 2, 4]
>>> map(square, values)


To get the values out of the iterator we have to loop over it:

>>> for x in map(square, values):
... print(x)
...
1
9
4
16

Or if you just want a list you can call list in the map object:

>>> list(map(square, values))
[1, 9, 4, 16]


Oscar
___
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-10 Thread Steven D'Aprano
On Tue, Dec 10, 2013 at 10:39:34AM +0100, Rafael Knuth wrote:

> I don't understand yet what the "map" function does - can you explain?
> I read the Python 3.3.0 documentation on that topic but I frankly
> didn't really understand it

The "map" function comes from so-called functional programming 
languages like Lisp, Scheme and Haskell. The idea, and the name, comes 
from the concept of a "mapping" in mathematics. The idea is that you 
have some relationship between the things over here and the things over 
there, e.g. the places on a map and the places in real life. "Here we 
are at the Town Hall, so on the map we must be here..." sort of thing.

So, in mathematics we might have a mapping between (let's say) counting 
numbers 1, 2, 3, 4, ... and the even numbers larger than fifty, 52, 54, 
56, ... and so on. The mapping function is 50 + 2*x:

x = 1 --> 50 + 2*1 = 52
x = 2 --> 50 + 2*2 = 54
x = 3 --> 50 + 2*3 = 56
x = 4 --> 50 + 2*4 = 58

and so on, where we might read the arrow --> as "maps to".

So the fundamental idea is that we take a series of elements (in the 
above case, 1, 2, 3, ...) and a function, apply the function to each 
element in turn, and get back a series of transformed elements (52, 54, 
56, ...) as the result.

So in Python, we can do this with map. First we define a function to do 
the transformation, then pass it to map:

def transform(n):
return 50 + 2*n

result = map(transform, [1, 2, 3, 4, 5, 6])


For short, simple functions, we don't even need to create the function 
ahead of time:

result = map(lambda n: 50 + 2*n, [1, 2, 3, 4, 5, 6])


works the same way.

In Python 3, map doesn't actually perform the calculations immediately. 
To turn the result into a list, just call the list() function:

result = list(result)

I should emphasis that it's not just mathematical functions where this 
is useful. We can use any function that takes a single argument:

def transform(astr):
return "Hello " + astr.strip().title() + "!"

for item in map(transform, [" George   ", "SUE\n", "bobby", "MicheLLE", 
"fred"]):
print(item)


prints:

Hello George!
Hello Sue!
Hello Bobby!
Hello Michelle!
Hello Fred!


or even multiple arguments, in which case you need to pass multiple 
data streams:

for item in map(lambda a,b,c: a+b-c, [1000, 2000, 3000], [100, 200, 300], [1, 
2, 3]):
print(item)

gives:

1099
2198
3297



-- 
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-10 Thread Asokan Pichai
On Tue, Dec 10, 2013 at 3:09 PM, Rafael Knuth wrote:

> Hej there,
>
> > I don't know if everyone would consider this more elegant but it's
> > certainly shorter:
>
> Thanks!
>
>  def DigitSum(YourNumber):
> > ... return sum(map(int, YourNumber))
> > ...
>  DigitSum('55')
> > 10
>
> I don't understand yet what the "map" function does - can you explain?
> I read the Python 3.3.0 documentation on that topic but I frankly
> didn't really understand it
> http://docs.python.org/3/library/functions.html#map. My search for
> simple code examples using "map" wasn't really fruitful either.
>
> Other than that, I went through each of the 7 alternatives to my
> "Integer to Digit Sum" program you guys sent me, I understand what
> each of those programs does. My favorite one is:
>
> def DigSum (integer):
> s = 0
> while integer != 0:
> integer, remainder = divmod(integer, 10)
> s += remainder
> print(s)
>
> DigSum(537)
>
> It's really a beautiful, elegant solution IMHO and way better than my
> original code (convert int to string, store each digit in an empty
> list, then convert them back to int and sum them).
>
> If you liked it, I will give you one that uses one less variable :-)

def digitSum(n):
  dsum = 0
  while n > 0:
dsum += n % 10
n /= 10
  return dsum


> Again, thank you all!
>
You are welcome.


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-10 Thread Asokan Pichai
On Tue, Dec 10, 2013 at 4:06 PM, Asokan Pichai wrote:

>
>
>
> On Tue, Dec 10, 2013 at 3:09 PM, Rafael Knuth wrote:
>
>> Hej there,
>>
>> > I don't know if everyone would consider this more elegant but it's
>> > certainly shorter:
>>
>> Thanks!
>>
>>  def DigitSum(YourNumber):
>> > ... return sum(map(int, YourNumber))
>> > ...
>>  DigitSum('55')
>> > 10
>>
>> I don't understand yet what the "map" function does - can you explain?
>> I read the Python 3.3.0 documentation on that topic but I frankly
>> didn't really understand it
>> http://docs.python.org/3/library/functions.html#map. My search for
>> simple code examples using "map" wasn't really fruitful either.
>>
>> Other than that, I went through each of the 7 alternatives to my
>> "Integer to Digit Sum" program you guys sent me, I understand what
>> each of those programs does. My favorite one is:
>>
>> def DigSum (integer):
>> s = 0
>> while integer != 0:
>> integer, remainder = divmod(integer, 10)
>> s += remainder
>> print(s)
>>
>> DigSum(537)
>>
>> It's really a beautiful, elegant solution IMHO and way better than my
>> original code (convert int to string, store each digit in an empty
>> list, then convert them back to int and sum them).
>>
>> If you liked it, I will give you one that uses one less variable :-)
>
> def digitSum(n):
>   dsum = 0
>   while n > 0:
> dsum += n % 10
> n /= 10
>   return dsum
>
>
>> Again, thank you all!
>>
> You are welcome.
>
>
> 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
>

Stupid of me not to have mentioned that this Python 2.x only. Sorry
___
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-10 Thread Steven D'Aprano
On Tue, Dec 10, 2013 at 10:39:34AM +0100, Rafael Knuth wrote:

> def DigSum (integer):
> s = 0
> while integer != 0:
> integer, remainder = divmod(integer, 10)
> s += remainder
> print(s)

A thought comes to mind... an very important lesson is to learn the 
difference between return and print, and to prefer return.

You have written a function that calculates the digit sum. But it is not 
*reusable* in other functions, since it cannot do anything but *print* 
the digit sum. What if you want to store the result in a variable, and 
print it later? Or print it twice? Or put it in a list? Or add one to 
it? You're screwed, the function is no use to you at all.

This is because the function does *two things*, when it should do one. 
First it calculates the digit sum, and then it prints it.

My advice is, (nearly) always use return, not print, inside functions. 
Once you return a result, it is easy to print it if you so desire:

print(digit_sum(23))


Or do anything else:

x = digit_sum(42952)
y = digit_sum(1032897) + digit_sum(8234)
z = [1, 2, digit_sum(99742), 3]


but you can't do anything *but* print if your function automatically 
calls print.



-- 
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-10 Thread Wolfgang Maier
Asokan Pichai  talentsprint.com> writes:

> 
> If you liked it, I will give you one that uses one less variable 
> 
> def digitSum(n):
>       dsum = 0
>       while n > 0:
>             dsum += n % 10
> 
>             n /= 10
>       return dsum
>
> Stupid of me not to have mentioned that this Python 2.x only. Sorry 
> 

but very easy to fix:

def digitSum(n):
dsum = 0
while n > 0:
dsum += n % 10
n //= 10# explicit floor division works in Python2 & 3
return dsum

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-10 Thread spir

On 12/10/2013 11:56 AM, Steven D'Aprano wrote:

This is because the function does *two things*, when it should do one.
First it calculates the digit sum, and then it prints it.


print's inside functions are a sign of debug not completely cleaned ;-)

(and also a sign that test funcs do not provide enough information, or not the 
right kind; but this is not always possible, I guess)


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-10 Thread Wolfgang Maier
Steven D'Aprano  pearwood.info> writes:

> 
> On Tue, Dec 10, 2013 at 10:39:34AM +0100, Rafael Knuth wrote:
> 
> > def DigSum (integer):
> > s = 0
> > while integer != 0:
> > integer, remainder = divmod(integer, 10)
> > s += remainder
> > print(s)
> 
> A thought comes to mind... an very important lesson is to learn the 
> difference between return and print, and to prefer return.
> 
> You have written a function that calculates the digit sum. But it is not 
> *reusable* in other functions, since it cannot do anything but *print* 
> the digit sum. What if you want to store the result in a variable, and 
> print it later? Or print it twice? Or put it in a list? Or add one to 
> it? You're screwed, the function is no use to you at all.
> 
> This is because the function does *two things*, when it should do one. 
> First it calculates the digit sum, and then it prints it.
> 
> My advice is, (nearly) always use return, not print, inside functions. 
> Once you return a result, it is easy to print it if you so desire:
> 
> print(digit_sum(23))
> 
> Or do anything else:
> 
> x = digit_sum(42952)
> y = digit_sum(1032897) + digit_sum(8234)
> z = [1, 2, digit_sum(99742), 3]
> 
> but you can't do anything *but* print if your function automatically 
> calls print.
> 

A very valuable lesson for sure.
Along the same lines: if you look very closely, you will see that
digit_sum() still performs two tasks. It breaks down an integer into digits
*and* it calculates the sum of these digits.
A more atomic function would return just the digits, but leave it up to the
caller what to do with them. E.g., you might decide to multiply them instead
of adding them.
Asokan split the functionality exactly like that in one of the first replies
here, but using the int -> str -> int method.
>From his post:

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

For the number approach, using a generator function, this could look like:

def digits(n):
"""Generator that breaks down an integer into digits from right to left."""
while n>0:
yield n % 10
n //= 10

with it you can do things like:

sum(digits(819))
list(digits(819))
sorted(digits(819))

from functools import reduce
reduce(lambda x, y: x*y, digits(99))

Best,
Wolfgang 

___
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-10 Thread spir

On 12/10/2013 12:46 AM, Steven D'Aprano wrote:

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

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


Why 2.7? By me also works with 3.3.


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().


That's also my rule, except if I use %-strings or format around, I also use it 
for a single, binary catenation.


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-10 Thread spir

[off-topic]

On 12/10/2013 01:39 PM, Wolfgang Maier wrote:

def digits(n):
 """Generator that breaks down an integer into digits from right to left."""
 while n>0:
 yield n % 10
 n //= 10


Aha! one more sign that we write numbers backwards!

Denis
___
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-10 Thread Steven D'Aprano
On Tue, Dec 10, 2013 at 01:43:57PM +0100, spir wrote:
> On 12/10/2013 12:46 AM, Steven D'Aprano wrote:
> >In Python 2.7, you can abbreviate that last one slightly:
> >
> >'{} "{}"'.format(number, word)
> 
> Why 2.7? By me also works with 3.3.

Sorry, I meant "Python 2.7 or later".


-- 
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-10 Thread Rafael Knuth
Hej Steven,

thanks for the clarification.
I have two questions - one about map function and the other about return.

> So, in mathematics we might have a mapping between (let's say) counting
> numbers 1, 2, 3, 4, ... and the even numbers larger than fifty, 52, 54,
> 56, ... and so on. The mapping function is 50 + 2*x:
>
> x = 1 --> 50 + 2*1 = 52
> x = 2 --> 50 + 2*2 = 54
> x = 3 --> 50 + 2*3 = 56
> x = 4 --> 50 + 2*4 = 58
>
> and so on, where we might read the arrow --> as "maps to".
>
> So the fundamental idea is that we take a series of elements (in the
> above case, 1, 2, 3, ...) and a function, apply the function to each
> element in turn, and get back a series of transformed elements (52, 54,
> 56, ...) as the result.
>
> So in Python, we can do this with map. First we define a function to do
> the transformation, then pass it to map:
>
> def transform(n):
> return 50 + 2*n
>
> result = map(transform, [1, 2, 3, 4])

#1 Question

In which cases should I use a map function instead of a for loop like
this for example:

def transform(n, m):
for i in range (n, m):
print (50 + 2*i)

transform(1,5)

>>>
52
54
56
58

> A thought comes to mind... an very important lesson is to learn the
> difference between return and print, and to prefer return.
>
> You have written a function that calculates the digit sum. But it is not
> *reusable* in other functions, since it cannot do anything but *print*
> the digit sum. What if you want to store the result in a variable, and
> print it later? Or print it twice? Or put it in a list? Or add one to
> it? You're screwed, the function is no use to you at all.

#2 Question

Strangely, I get entirely different results depending on whether I use
return or print within a function.
Example:

def transform(n, m):
for i in range (n, m):
print (50 + 2*i)

transform(1,5)

>>>
52
54
56
58

Versus:

def transform(n, m):
for i in range(n, m):
return (50 + 2*i)

print(transform(1,5))

>>>
52

Why do I get entirely different results in each case? &:
How do I prevent my loop from breaking after the first round when
using return instead of print?

All the best,

Raf
___
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-10 Thread Steven D'Aprano
On Tue, Dec 10, 2013 at 02:31:55PM +0100, Rafael Knuth wrote:

> > So in Python, we can do this with map. First we define a function to do
> > the transformation, then pass it to map:
> >
> > def transform(n):
> > return 50 + 2*n

Notice here that transformation function takes *one* value, and 
calculates *one* result.

> > result = map(transform, [1, 2, 3, 4])

And here the map() function takes care of looping through the four items 
in the list, passing them to the transform function, and generating a 
new list in Python 2. In Python 3, it holds off generating the list 
unless you ask.

The call to map is (almost) equivalent to this for-loop:

result = []
for item in [1, 2, 3, 4]:
tmp = transform(item)
result.append(tmp)


or to this list comprehension:

result = [transform(item) for item in [1, 2, 3, 4]]

So now you can see three equivalent ways to do more or less the same 
thing. 


> #1 Question
> 
> In which cases should I use a map function instead of a for loop like
> this for example:
> 
> def transform(n, m):
> for i in range (n, m):
> print (50 + 2*i)

Use whichever seems best for whatever job you need to do. In the above 
function, you calculate the results you want, and print them, and you 
are done. This is not reusable -- it can only do one thing. The only 
part that you can control is the starting and ending value of the range. 
Everything else is fixed -- the transformation equation is always 50 + 
2*i, the result is always printed.

Are you satisfied with that? Great! Then the above is fine.

But if you need more control over what gets done -- perhaps you want to 
change the equation, perhaps you want to save the results in a list 
instead of print them -- then you should look at using map, or a list 
comprehension, instead.


> #2 Question
> 
> Strangely, I get entirely different results depending on whether I use
> return or print within a function.

Not strangely at all. Remember, "return" returns a result back to the 
caller. Once you reach a return line, the function is done and nothing 
else gets calculated, control jumps back to whatever called the 
function.


> Example:
> 
> def transform(n, m):
> for i in range (n, m):
> print (50 + 2*i)

Since print does not exit the function, after printing the first value, 
the loop continues, the second value is printed, then the third, and so 
on.

> def transform(n, m):
> for i in range(n, m):
> return (50 + 2*i)

Since return exits the function, after the first value is calculated, it 
is returned, and no more values are calculated.

What happens when the result is returned?

Normally, you would assign it to a variable, for later use:

x = transform(1, 5)
# now x == 52

Or perhaps put it in a list:

mylist = []
mylist.append(transform(1, 5)


Or something, anything. The choices are endless: write it to a file, 
pass it to another function, put it in a tuple, a set, a dict or a 
class, turn it into a string, compare it to another result... even print 
it!

What happens if you don't assign it to anything? That depends. In a 
script, Python just ignores the value, and it goes away. In the 
interactive interpreter, Python prints it, as a convenience. You can 
think of the interactive interpreter as treating lines like:

some_function(x, y, z)

as if you wrote something quite similar to:

print( repr(some_function(x, y, z)) )

This is just a convenience for interactive work, and does not apply when 
running as a script.

> Why do I get entirely different results in each case? &:
> How do I prevent my loop from breaking after the first round when
> using return instead of print?

Move the return outside of the loop. First you have to accumulate the 
results somewhere, then only when the loop is finished, return them.

def transform(n, m):
results = []
for i in range(n, m):
results.append(50 + 2*i)
return results


But you know what? That can be written much more cleanly as:

def transform(n, m):
return [50 + 2*i for i in range(n, m)]



-- 
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-10 Thread spir

On 12/10/2013 02:31 PM, Rafael Knuth wrote:

Hej Steven,

thanks for the clarification.
I have two questions - one about map function and the other about return.


So, in mathematics we might have a mapping between (let's say) counting
numbers 1, 2, 3, 4, ... and the even numbers larger than fifty, 52, 54,
56, ... and so on. The mapping function is 50 + 2*x:

x = 1 --> 50 + 2*1 = 52
x = 2 --> 50 + 2*2 = 54
x = 3 --> 50 + 2*3 = 56
x = 4 --> 50 + 2*4 = 58

and so on, where we might read the arrow --> as "maps to".

So the fundamental idea is that we take a series of elements (in the
above case, 1, 2, 3, ...) and a function, apply the function to each
element in turn, and get back a series of transformed elements (52, 54,
56, ...) as the result.

So in Python, we can do this with map. First we define a function to do
the transformation, then pass it to map:

def transform(n):
 return 50 + 2*n

result = map(transform, [1, 2, 3, 4])


#1 Question

In which cases should I use a map function instead of a for loop like
this for example:

def transform(n, m):
 for i in range (n, m):
 print (50 + 2*i)

transform(1,5)




52
54
56
58


Apparently, you make a confusion (actually ) between:
* true functions, "function-functions", which produce a new piece of data (like 
math functions)
* "action-functions", which perform an effect, such as modifying the world or 
writing something to output


'map' is for true functions: it collects the sequence of products of such a 
function on a sequence of input. Therefore, map also returns a product. Right?


There is another standard tool called 'apply' in general, which sequentially 
*performms* the effect of an action on a sequence of inputs. Since it just 
applies action, 'apply' does not return any result. 'apply' is rarely used (even 
more than map; actually I think apply does not even exist in Python), because it 
is more practicle to write a simple loop. To use apply, as for map, you need to 
define a function that holds the block of code to be executed, which is often 1 
or 2 lines of code. Pretty annoying.


There is no magic in such functions as map & apply (there are also filter & 
reduce in that category), actually they are trivial. Here is an example of 
writing apply, with an example usage:


def apply (items, action):
for item in items:
action(item)

def show_cube (item):
print(item, "-->", item*item*item)
items = [1,2,3,4,5]
apply(items, show_cube)

==>

1 --> 1
2 --> 8
3 --> 27
4 --> 64
5 --> 125

But as you can guess, it is far simpler to just write:

for item in items:
print(item, "-->", item*item*item)


Now, an example of writing map, with an example usage:

def map_bis (items, func):  # different name, as 'map' exists in Python
new_items = []
for item in items:
new_item = func(item)
new_items.append(new_item)
return new_items

def transform(n):
return 50 + 2*n
items = [1,2,3,4,5]
new_items = map_bis(items, transform)
print(new_items)# ==> [52, 54, 56, 58, 60]

Here, as you have seen and written yourself, map gives us a very slight 
advantage over writing the loop by hand, namely that we don't need to initialise 
the new list to []. This gives in fact another advantage, that we can chains 
maps (also with filters).

items2 = map(f3, filter(f2, map(f1, items1)))

Apart from that, it is still *very* annoying to be forced to write 
mini-functions just for tiny blocks of codes to be used by map (or filter, 
or...). The solution in Python is comprehensions, where you write the code 
directly. Soon, you'll meet and learn about them, and probably soon later you'll 
start to love them ;-).


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-10 Thread spir

On 12/10/2013 02:31 PM, Rafael Knuth wrote:

Hej Steven,

thanks for the clarification.
I have two questions - one about map function and the other about return.


So, in mathematics we might have a mapping between (let's say) counting
numbers 1, 2, 3, 4, ... and the even numbers larger than fifty, 52, 54,
56, ... and so on. The mapping function is 50 + 2*x:

x = 1 --> 50 + 2*1 = 52
x = 2 --> 50 + 2*2 = 54
x = 3 --> 50 + 2*3 = 56
x = 4 --> 50 + 2*4 = 58

and so on, where we might read the arrow --> as "maps to".

So the fundamental idea is that we take a series of elements (in the
above case, 1, 2, 3, ...) and a function, apply the function to each
element in turn, and get back a series of transformed elements (52, 54,
56, ...) as the result.

So in Python, we can do this with map. First we define a function to do
the transformation, then pass it to map:

def transform(n):
 return 50 + 2*n

result = map(transform, [1, 2, 3, 4])


#1 Question

In which cases should I use a map function instead of a for loop like
this for example:

def transform(n, m):
 for i in range (n, m):
 print (50 + 2*i)

transform(1,5)




52
54
56
58


A thought comes to mind... an very important lesson is to learn the
difference between return and print, and to prefer return.

You have written a function that calculates the digit sum. But it is not
*reusable* in other functions, since it cannot do anything but *print*
the digit sum. What if you want to store the result in a variable, and
print it later? Or print it twice? Or put it in a list? Or add one to
it? You're screwed, the function is no use to you at all.


#2 Question

Strangely, I get entirely different results depending on whether I use
return or print within a function.
Example:

def transform(n, m):
 for i in range (n, m):
 print (50 + 2*i)

transform(1,5)




52
54
56
58

Versus:

def transform(n, m):
 for i in range(n, m):
 return (50 + 2*i)

print(transform(1,5))




52

Why do I get entirely different results in each case? &:
How do I prevent my loop from breaking after the first round when
using return instead of print?

All the best,

Raf
___
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] Converting integers into digit sum (Python 3.3.0)

2013-12-10 Thread Mark Lawrence

On 10/12/2013 18:08, spir wrote:


There is another standard tool called 'apply' in general, which
sequentially *performms* the effect of an action on a sequence of
inputs.


The apply function has been deprecated since 2.3 and never got into 
Python 3.


--
My fellow Pythonistas, ask not what our language can do for you, ask 
what you can do for our language.


Mark Lawrence

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


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

2013-12-10 Thread eryksun
On Tue, Dec 10, 2013 at 1:08 PM, spir  wrote:
> There is another standard tool called 'apply' in general, which sequentially
> *performms* the effect of an action on a sequence of inputs. Since it just
> applies action, 'apply' does not return any result. 'apply' is rarely used
> (even more than map; actually I think apply does not even exist in Python),

There's a deprecated function named "apply" in 2.x, but it doesn't
apply a function iteratively to a sequence. apply(f, args, kwds) is
the same as the extended call syntax f(*args, **kwds).

Since the 3.x map class is an iterator, you could consume its output
in a zero-length deque:

from collections import deque

def apply(f, seq):
deque(map(f, seq), maxlen=0)

> Apart from that, it is still *very* annoying to be forced to write
> mini-functions just for tiny blocks of codes to be used by map (or filter,
> or...). The solution in Python is comprehensions, where you write the code
> directly. Soon, you'll meet and learn about them, and probably soon later
> you'll start to love them ;-).

The case for using map and filter was weakened by comprehensions and
generator expressions. In CPython, however, map and filter are faster
at applying a built-in function or type to a built-in sequence type,
such as sum(map(int, str(n))) as opposed to sum(int(d) for d in
str(n)).
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] Subprocess communications query

2013-12-10 Thread Reuben
Hi,

There exists two Linux machines A and B. Machine B contains python script
which needs to be run e.g. Test.py

In order to run that script, machine A needs to telnet into machine B and
then execute "python Test.py"

How can this be implemented? Is subprocess library to be used?if yes, an
example would help

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


Re: [Tutor] Subprocess communications query

2013-12-10 Thread Danny Yoo
On Tue, Dec 10, 2013 at 11:28 AM, Reuben  wrote:
> Hi,
>
> There exists two Linux machines A and B. Machine B contains python script
> which needs to be run e.g. Test.py
>
> In order to run that script, machine A needs to telnet into machine B and
> then execute "python Test.py"

Nothing about this sounds like Python.  Is there anything specifically
Python-related to this question, besides the detail that machine B is
running a Python program?

This really sounds like more like a Linux system administration
question.  If that's the case, you probably want to ask on a forum for
system administrators, like:

http://unix.stackexchange.com/

where they'll be able to point you in a better direction than us.

(By the way, when you say "telnet", I do hope you do not literally
mean telnet, which is not known to be secure.  You need to talk with
other system administrators and learn about tools like ssh.)
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Subprocess communications query

2013-12-10 Thread Reuben
I want to implement a python script on machine A to do telnet/ssh into
machine B (this might be easy)and then run the Test.py (this is challenging)
On 11-Dec-2013 1:05 AM, "Danny Yoo"  wrote:

> On Tue, Dec 10, 2013 at 11:28 AM, Reuben  wrote:
> > Hi,
> >
> > There exists two Linux machines A and B. Machine B contains python script
> > which needs to be run e.g. Test.py
> >
> > In order to run that script, machine A needs to telnet into machine B and
> > then execute "python Test.py"
>
> Nothing about this sounds like Python.  Is there anything specifically
> Python-related to this question, besides the detail that machine B is
> running a Python program?
>
> This really sounds like more like a Linux system administration
> question.  If that's the case, you probably want to ask on a forum for
> system administrators, like:
>
> http://unix.stackexchange.com/
>
> where they'll be able to point you in a better direction than us.
>
> (By the way, when you say "telnet", I do hope you do not literally
> mean telnet, which is not known to be secure.  You need to talk with
> other system administrators and learn about tools like ssh.)
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Subprocess communications query

2013-12-10 Thread Danny Yoo
Ok; so in your situation, it sounds like machine A is also running a
Python script, and you want to automate the remote administration of
machine B through that program.  If that's the case, you may want to
look at the "Fabric" library, or other libraries that help with
driving ssh through Python:

http://docs.fabfile.org/en/1.8/

There are a few more links in:

https://wiki.python.org/moin/SecureShell

http://stackoverflow.com/questions/1233655/what-is-the-simplest-way-to-ssh-using-python
http://python-for-system-administrators.readthedocs.org/en/latest/index.html

that might be relevant to you.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Subprocess communications query

2013-12-10 Thread Steve Willoughby
Reuben  wrote:
>I want to implement a python script on machine A to do telnet/ssh into
>machine B (this might be easy)and then run the Test.py (this is
>challenging)
>On 11-Dec-2013 1:05 AM, "Danny Yoo"  wrote:
>
>> On Tue, Dec 10, 2013 at 11:28 AM, Reuben 
>wrote:
>> > Hi,
>> >
>> > There exists two Linux machines A and B. Machine B contains python
>script
>> > which needs to be run e.g. Test.py
>> >
>> > In order to run that script, machine A needs to telnet into machine
>B and
>> > then execute "python Test.py"
>>
>> Nothing about this sounds like Python.  Is there anything
>specifically
>> Python-related to this question, besides the detail that machine B is
>> running a Python program?
>>
>> This really sounds like more like a Linux system administration
>> question.  If that's the case, you probably want to ask on a forum
>for
>> system administrators, like:
>>
>> http://unix.stackexchange.com/
>>
>> where they'll be able to point you in a better direction than us.
>>
>> (By the way, when you say "telnet", I do hope you do not literally
>> mean telnet, which is not known to be secure.  You need to talk with
>> other system administrators and learn about tools like ssh.)
>>
>
>
>
>
>___
>Tutor maillist  -  Tutor@python.org
>To unsubscribe or change subscription options:
>https://mail.python.org/mailman/listinfo/tutor

You could do many different things depending on your needs. You could write a 
daemon in python on one machine which waits for a python program on the other 
to command it to run a process. 

You could find out how to accomplish this using ssh and then just write a 
python script to execute that ssh command for you. 

Without more details it's hard too say what is more appropriate but I would 
suggest reading up on python subprocess module, ssh, and internet protocol and 
server modules in the standard library.
-- 
Sent from my Android device with K-9 Mail. Please excuse my brevity.___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Subprocess communications query

2013-12-10 Thread Steven D'Aprano
On Wed, Dec 11, 2013 at 12:58:16AM +0530, Reuben wrote:
> Hi,
> 
> There exists two Linux machines A and B. Machine B contains python script
> which needs to be run e.g. Test.py
> 
> In order to run that script, machine A needs to telnet into machine B and
> then execute "python Test.py"

Using telnet is not a good idea. Telnet is provably insecure -- it is a 
great big security hole. ssh is a better solution for machines which are 
on any untrusted network.


> How can this be implemented? Is subprocess library to be used?if yes, an
> example would help

An even better solution would be to use a library like Pyro or rpyc for 
executing remote procedure calls.

https://wiki.python.org/moin/DistributedProgramming

I strongly recommend you use an existing solution rather than hack 
together your own.



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


[Tutor] Need to create code

2013-12-10 Thread Matthew Thomas

Write a function named SSN2Name with an interactive loop. The function takes 
the dictionary named data as
 input argument where this dictionary stores the key, value pairs of 
SSN, name of person. The SSN is in the string format 'xxx-xx-' and
 name is also a string. Each iteration of the functions's loop should 
prompt the user to enter an SSN in the required format and next, it 
should print the name of the person if he/she is found in the 
dictionary, otherwise a message like "person not found" if that SSN does
 not exist in the keys of the dictionary. The loop should stop iterating
 when the user inputs the empty string "" when prompted for SSN.
  Write the full function definition in your answer. The function outline is 
given below with comments provided as code hints -
  def SSN2Name(data):  
   # create a loop that repeats forever (while True loop) 
# within the loop prompt user for SSN
# if user input is empty string break out of loop
# if user input is an SSN found as a key in the dictionary, print 
the value corresponding to that key
# if user input is not found as a key in the dictionary print 
message saying person was not found

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


[Tutor] recursive function example

2013-12-10 Thread ugajin
I am looking at a simple recursive function, and oxymoron aside, I am having 
difficulty in seeing what occurs. I have tried adding some debug print commands 
to help break the thing down. This helps a lot, but I still have a question 
that I need help with.

Here is original code:
def mult(a, b):
if b == 0:
return 0
rest = mult(a, b - 1)
value = a + rest
return value
print "3 * 2 = ", mult(3, 2)

I see how python outputs the string "mult(3,2)" before running the function, 
and then adds the return value to the output, 
and I see how the 'if' condition is met, 
but I do not see how the variable 'rest' is assigned a value, and a single 
value at that. 
'rest' must have a value of 3 (for this example) for the function to return the 
correct 
value, and 'rest' must be assigned the value of '3' but when, prior, to b == 0?
When 'b' == 0 (zero) the 'if' condition is escaped.
In the first iteration, 'rest' is shown with the value '0' (zero), 
and in the second it is '3'.
1st, run rest = mult(3, 1)
2nd. run rest = mult(3, 0) and the 'if' condition is met
Is there some inherent multiplication e.g. 3*1 = 3 and 3*0 = 0, 
and even if so, it seems backwards?

I am once again perplexed!
Help please. . . if you can.

-A

Here is my debugging code:

#! /usr/bin/env python

def mult(a, b):
if b == 0:
return 0
print
print 'a =', a
print 'b =', b
rest = mult(a, b - 1)
print
print 'rest =', rest
value = a + rest
print 'value =', value, '(a + rest ==',a, '+', rest,')'
return value
print
print 'mult(3,2) value = ', '\n', '\nreturn = ' + str(mult(3, 2))


Here is the output from the debugging code:

mult(3,2) value =  

a = 3
b = 2

a = 3
b = 1

rest = 0
value = 3 (a + rest == 3 + 0 )

rest = 3
value = 6 (a + rest == 3 + 3 )

return = 6



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


Re: [Tutor] Need to create code

2013-12-10 Thread Alan Gauld

On 10/12/13 15:45, Matthew Thomas wrote:

Write a function named *SSN2Name* with an interactive loop.


This is obviously some kind of homework exercise. We do
not do your homework for you but we will give you pointers
or clarify issues if you get stuck.

But we expect you to make a start, post your code and
any questions. If you have any errors post the entire error
message, do not summarize.

If you are stuck tell us what happened, what you expected,
what version of python, what OS you use. The more specific
the question and information you give us the better we can
answer.


takes the dictionary named*data*as input argument where this dictionary
stores the key, value pairs of SSN, name of person.


Do you know how to write a function?
Do you know how to create/use a dictionary?


string format 'xxx-xx-' and name is also a string. Each iteration of
the functions's loop should prompt the user to enter an SSN in the
required format and next, it should print the name of the person if
he/she is found in the dictionary, otherwise a message like "person not
found" if that SSN does not exist in the keys of the dictionary.


Do you know how to write a loop?
How to get input from a user? How to access a dictionary?
How to print output?



loop should stop iterating when the user inputs the empty string "" when
prompted for SSN.


Do you know how to test for an empty string?
And how to exit a loop when you find one?


Write the full function definition in your answer. The function outline
is given below with comments provided as code hints -



def SSN2Name(data):
  # create a loop that repeats forever (while True loop)
 # within the loop prompt user for SSN
 # if user input is empty string break out of loop
 # if user input is an SSN found as a key in the dictionary,
print the value corresponding to that key
# if user input is not found as a key in the dictionary print message
saying person was not found


What part of that description, if any, do you have a problem with?

If you don't have a specific question yet then just go ahead and
try to create the code. Come back when you have a specific question
and we can try to help.

--
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] recursive function example

2013-12-10 Thread Alan Gauld

On 10/12/13 14:48, uga...@talktalk.net wrote:


Here is original code:
def mult(a, b):
 if b == 0:
 return 0
 rest = mult(a, b - 1)
 value = a + rest
 return value
print "3 * 2 = ", mult(3, 2)

I see how python outputs the string "mult(3,2)" before running the
function,


No it doesn't.
It outputs the string "3 * 2 - " before running the function!


and then adds the return value to the output,


Again no. It adds the first parameter to the return value of the 
recursive call to mult()



and I see how the 'if' condition is met,



but I do not see how the variable 'rest' is assigned a value, and a
single value at that.


Because it calls mult with a new set of arguments (a, b-1) instead of 
the original (a,b). Each call to mult calls mult with a new (a, b-1) 
until eventually b is equal to zero and the if test returns zero.



'rest' must have a value of 3 (for this example) for the function to
return the correct value, and 'rest' must be assigned the value
of '3' but when, prior, to b == 0?


No after b=0. the first return from mult is the b-0 case of zero.
the next return value will be a + 0 = 3 and the final return value
is 3 + 3 which is 6, the correct result.


When 'b' == 0 (zero) the 'if' condition is escaped.


By escaped you mean the functions returns zero.


In the first iteration, 'rest' is shown with the value '0' (zero),
and in the second it is '3'.


That's correct, zero + a where a=3. So value = 3


1st, run rest = mult(3, 1)
2nd. run rest = mult(3, 0) and the 'if' condition is met
Is there some inherent multiplication e.g. 3*1 = 3 and 3*0 = 0,


There is no multiplication at all. The function works on the basis that 
multiplication is equivalent to repeated addition.

So 3 * 2 = 0+2+2+2 or 0+3+3

Try reversing the arguments to see the first case at work...


and even if so, it seems backwards?


It is backwards in so far as the recursion has to drill down
to the zero case then unwind back up to the initial case.
That's often the case with recursion.

It often helps to do it on paper rather than using the computer.
Try drawing a table like

a   b   b==0   b-1  return
---
3   2   False   1
3   1   False   0
3   0   True-10
3   1   3+0=3
3   2   3+3=6

Work your way through it line by line.

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] Need to create code

2013-12-10 Thread Mark Lawrence

On 10/12/2013 15:45, Matthew Thomas wrote:

Write a function named *SSN2Name* with an interactive loop. The function
takes the dictionary named*data*as input argument where this dictionary
stores the key, value pairs of SSN, name of person. The SSN is in the
string format 'xxx-xx-' and name is also a string. Each iteration of
the functions's loop should prompt the user to enter an SSN in the
required format and next, it should print the name of the person if
he/she is found in the dictionary, otherwise a message like "person not
found" if that SSN does not exist in the keys of the dictionary. The
loop should stop iterating when the user inputs the empty string "" when
prompted for SSN.
Write the full function definition in your answer. The function outline
is given below with comments provided as code hints -
def SSN2Name(data):
  # create a loop that repeats forever (while True loop)
 # within the loop prompt user for SSN
 # if user input is empty string break out of loop
 # if user input is an SSN found as a key in the dictionary,
print the value corresponding to that key
# if user input is not found as a key in the dictionary print message
saying person was not found



An alternative to the hints kindly provided already by Alan Gauld is to 
write out a sizeable cheque made payable to the Python Software 
Foundation, where the size of the cheque refers to the amount in words 
and figures and not the physical dimensions.  Then and only then will 
you see some actual code.


--
My fellow Pythonistas, ask not what our language can do for you, ask 
what you can do for our language.


Mark Lawrence

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


Re: [Tutor] Need to create code

2013-12-10 Thread Danny Yoo
Hi Thomas,

In order to use mailing list like Python-tutor effectively, you'll
probably want to read:

 http://www.catb.org/~esr/faqs/smart-questions.html

In particular, pay special attention to:

http://www.catb.org/~esr/faqs/smart-questions.html#homework

You're basically violating the "Don't post homework questions" taboo.
This isn't rent-a-coder.  We'll be happy to help you learn how to
program, but we're not writing your program for you.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor