Re: [Tutor] Are there any Python-based GUI builders for tkinter

2015-10-28 Thread Laura Creighton
In a message of Tue, 27 Oct 2015 15:20:56 -0500, boB Stepp writes:
>I have a friend at work and he is trying to develop GUI applications
>in Python, but he does not want to hand-code them.  Are there any
>commercial or non-commercial products that would do this for him?  He
>tried his own online search but was unsuccessful.
>
>His OS is Mac OS 10.10 and is using Python 3.5.
>
>TIA!
>
>-- 
>boB

check out QtDesigner

http://doc.qt.io/qt-5/qtdesigner-manual.html

or QtCreator 
http://www.qt.io/ide/

if you want the whole process to happen inside an IDE.

https://wiki.python.org/moin/PyQt/Creating_GUI_Applications_with_PyQt_and_Qt_Designer
 may be useful as well, though its a little old by now.

Laura

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


Re: [Tutor] How to parse large files

2015-10-28 Thread Peter Otten
Danny Yoo wrote:

> There are several out there; one that comes standard in Python 3 is
> the "dbm" module:
> 
> https://docs.python.org/3.5/library/dbm.html
> 
> Instead of doing:
> 
> diz5 = {}
> ...
> 
> we'd do something like this:
> 
> with diz5 = dbm.open('diz5, 'c'):
> ...
> 
> And otherwise, your code will look very similar!  This dictionary-like
> object will store its data on disk, rather than in-memory, so that it
> can grow fairly large.  The other nice thing is that you can do the
> dbm creation up front.  If you run your program again, you might add a
> bit of logic to *reuse* the dbm that's already on disk, so that you
> don't have to process your input files all over again.

dbm operates on byte strings for both keys and values, so there are a few 
changes. Fortunately there's a wrapper around dbm called shelve that uses 
string keys and allows objects that can be pickled as values:
 
https://docs.python.org/dev/library/shelve.html

With that your code may become

with shelve.open("diz5") as db:
with open("tmp1.txt") as instream:
for line in instream:
assert line.count("\t") == 1
key, _tab, value = line.rstrip("\n").partition("\t")
values = db.get(key) or set()
values.add(value)
db[key] = values

Note that while shelve has a setdefault() method it will only work as 
expected when you set writeback=True which in turn may require arbitrary 
amounts of memory.

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


[Tutor] Demystification of Lambda Functions

2015-10-28 Thread Hunter Jozwiak
Hello,

 

I am not sure exactly why there would be a practical use for a lambda
function, other than the fact that you can make one-liner functions that
take parameters in to a variable. Or at least that is how things look when
they are written. Can I have some demystification?

 

Thanks,

 

Hunter

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


Re: [Tutor] Demystification of Lambda Functions

2015-10-28 Thread Laura Creighton
In a message of Tue, 27 Oct 2015 21:04:45 -0400, "Hunter Jozwiak" writes:
>Hello,
>
> 
>
>I am not sure exactly why there would be a practical use for a lambda
>function, other than the fact that you can make one-liner functions that
>take parameters in to a variable. Or at least that is how things look when
>they are written. Can I have some demystification?
>
> 
>
>Thanks,
>Hunter

Practically the only time I use them is to code callbacks in Tkinter
functions.

see: https://pythonconquerstheuniverse.wordpress.com/2011/08/29/lambda_tutorial/

for why it is useful.

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


Re: [Tutor] Demystification of Lambda Functions

2015-10-28 Thread Alan Gauld

On 28/10/15 01:04, Hunter Jozwiak wrote:


I am not sure exactly why there would be a practical use for a lambda
function, other than the fact that you can make one-liner functions that
take parameters in to a variable. Or at least that is how things look when
they are written. Can I have some demystification?


One thing to remember when dealing with Python is that it started out as 
a teaching language. That is, a language used to teach computer science 
and programming. As such, many of its features are designed
to be easy to use. Others are there to demonstrate computer science 
concepts.


One of those concepts is the idea of functional programming, where 
functions are treated like data objects. Many of those ideas in turn 
come from Church's "Lambda Calculus" and the idea of a lambda being an 
executable object. In other languages lambdas are much more powerful but 
in Python they were limited to a single expression so their full

power is harder to see.

If you look at JavaScript (or Lisp) it uses the concepts behind Lambda
much more and the use of anonymous functions is almost endemic in
modern Javascript libraries like JQuery, Angular, Node and so on.
In Python we are forced to define complex functions as separate 
entities, so the JScript style cannot be used.


So what are we left with in Python?

1) lambda makes programmers aware of the term 'lambda' and that
it is somehow significant in computer science. (Just like with
you, it stimulates curiosity).

2) lambdas are useful for teaching that

def f(x): return expression(x)

is the same as writing

f = lambda x: expression(x)

where f is just a variable name like any other.
(Whereas the def syntax tends to suggest that the f name is
somehow different to other names, that it has some kind of
superpowers just because its a function name, when in fact
it doesn't. Its just a name.)

3) lambdas allow us to create short anonymous functions in call
backs or to wrap longer generic functions with specific values.

HTH
--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
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] Demystification of Lambda Functions

2015-10-28 Thread Anshu Kumar
Hi,

Lambda or anonymous function is core of functional programming which was
not in java.

With lambda you can pass not just define an anonymous function but can pass
them to other functions which really makes life easier.

You would like to read
http://www.python-course.eu/lambda.php
http://www.python-course.eu/lambda.php

Thanks,
Anshu

On Wed, Oct 28, 2015 at 6:34 AM, Hunter Jozwiak 
wrote:

> Hello,
>
>
>
> I am not sure exactly why there would be a practical use for a lambda
> function, other than the fact that you can make one-liner functions that
> take parameters in to a variable. Or at least that is how things look when
> they are written. Can I have some demystification?
>
>
>
> Thanks,
>
>
>
> Hunter
>
> ___
> 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] Demystification of Lambda Functions

2015-10-28 Thread Steven D'Aprano
On Tue, Oct 27, 2015 at 09:04:45PM -0400, Hunter Jozwiak wrote:
> Hello,
> 
> I am not sure exactly why there would be a practical use for a lambda
> function, other than the fact that you can make one-liner functions that
> take parameters in to a variable. Or at least that is how things look when
> they are written. Can I have some demystification?

To understand why lambda is useful will require a bit of background. So 
let me start at the beginning.

The first thing you have to understand is that in modern languages like 
Python, functions are not just things that operate on values, but they 
are values themselves. So you can have a function which returns a new 
function as its result. Here is a simple example:

py> def make_adder(n):
... def adder(x):
... return x + n
... return adder
...
py> add_one = make_adder(1)
py> add_one(100)
101
py> add_five = make_adder(5)
py> add_five(100)
105

"make_adder" is a function which takes an argument, n, and returns a new 
function which takes one argument and returns that value plus the 
earlier value "n". So make_adder(1) builds a function that adds 1 to its 
argument, and make_adder(2) builds a function that adds 5 to its 
argument.

Functions can not merely return functions, they can also take them as an 
argument. Here's a simple example:


py> def add(a, b):  # Function that adds two values.
... return a + b
...
py> def times(a, b):  # Function that multiplies two values.
... return a*b
...
py> def builder(func):
... def op3(x):
... return func(x, 3)
... return op3
...
py> add_three = builder(add)
py> add_three(5)
8
py> times_three = builder(times)
py> times_three(5)
15


Now, those two examples themselves aren't terribly useful, it isn't very 
often that you need a whole bunch of functions:

add_one
add_two
add_three 

etc. But the ability to manipulate functions as arguments itself is 
useful. For example, suppose you have a set of strings, and you need to 
find out how long they all are:

py> strings = ["cat", "dog", "cheese", "aardvark", "elephant", "hamburger"]
py> lengths = []
py> for s in strings:
... lengths.append(len(s))
...
py> print lengths
[3, 3, 6, 8, 8, 9]


Having to build up a list yourself is a bit tedious, but there's another 
way:

py> print map(len, strings)  # Python 2 version.
[3, 3, 6, 8, 8, 9]


The "map" function takes a function (in this case, len) and applies it 
to each item in strings, consolidating the results. The Python 3 version 
is a little different, but the basic concept remains the same.

Suppose we had a list of numbers, and we wanted to create a new list 
with each number doubled and then one added. We could do this:

py> def double_and_add_one(x):
... return 2*x + 1
...
py> map(double_and_add_one, [2, 3, 4, 5])
[5, 7, 9, 11]


but it seems a bit wasteful to have that function "double_and_add_one" 
floating around in our program after we've used it, doing nothing 
useful. It has a name and everything.

Python lets us create an unnamed function, right there in the expression 
where it is being used. Once used, the interpreter can delete the 
function and reclaim its memory. To do this, we use lambda:

py> map(lambda x: 2*x+1, [2, 3, 4, 5])
[5, 7, 9, 11]


If you have a function that looks like this:

def FUNCTION(args):
return EXPRESSION

that can be written using the lambda syntax:

lambda args: EXPRESSION

dropped right in the place where you are planning to use it, instead of 
having to pre-define it using "def".

That makes lambda especially convenient for callback functions. For 
example, many GUI toolkits let you set callbacks. Suppose you create a 
button using some toolkit, like this, say:

save_button = Button("save", style="round")

What does the button do? So far, nothing: you can click on it, and 
nothing happens. To give the button an action, you have to give it a 
callback function. A callback is a function that the button will call 
when you click on it:

def save(thebtn):
# whatever code you need to save the document

save_button = Button("save", style="round", callback=save)


Sometimes callbacks are particularly short and simple. Suppose you are 
programming a calculator, and you have ten buttons 0...9 which all do 
precisely the same thing: they add their own name to the calculator 
display:


for num in range(0, 10):
btn = Button(str(num), style="rectangle", 
 callback = lambda thebtn: display.add(thebtn.name)
 )


Much better than having to pre-define ten functions and add them to each 
of the buttons.

These functions are called "anonymous functions", because unlike 
functions created with "def", they don't have a name. Well, technically 
they do, but they're all the same name:

py> (lambda x: x+1).__name__
''

which is only used for display, say, if there is an error. What makes 
anonymous functions especially useful in languages other than Python is 
that they are created at runtime, not compil

[Tutor] Messy - Very Messy string manipulation.

2015-10-28 Thread Vusa Moyo
Hi Guys,

I've written a script to remove vowels from a string/sentence.

the while loop I'm using below is to take care of duplicate vowels found in
a sentence, ie

anti_vowel('The cow moos louder than the frog')

It works, but obviously its messy and n00by. Any suggestions on how I can
write this code better?



def anti_vowel(text):
vowel = ['a', 'e', 'i', 'o', 'u']
VOWEL = ['A', 'E', 'I', 'O', 'U']
manip = []

for i in text:
manip.append(i)
fufu = 0
#
while fufu < 16:
for x in vowel:
if x in manip:
manip.remove(x)

for y in VOWEL:
if y in manip:
manip.remove(y)

fufu = fufu + 2

strong = ''.join(manip)
return strong



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


[Tutor] How do I (idiomatically) determine when I'm looking at the last entry in a list?

2015-10-28 Thread Flynn, Stephen (L & P - IT)
Afternoon,

Python 3.

I'm iterating through a list and I'd like to know when I'm at
the end of the said list, so I can do something different. For example

list_of_things = ['some', 'special', 'things']
for each_entry in list_of_things:
print(each_entry)
if each_entry == list_of_things[-1]: # do something special to
last entry
...etc


Is this the idiomatic way to detect you're at the last entry in a list
as you iterate through it?



For context, I'm working my way through a (csv) file which describes
some database tables. I'm building the Oracle DDL to create that table
as I go. When I find myself building the last column, I want to finish
the definition with a ");" rather than the usual "," which occurs at the
end of all other column definitions...

e.g.
CREATE TABLE wibble
(
Col1CHAR(2),
Col2NUMBER(5,2),
);

Regards,

Steve.


This email is security checked and subject to the disclaimer on web-page: 
http://www.capita.co.uk/email-disclaimer.aspx
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Are there any Python-based GUI builders for tkinter (fwd)

2015-10-28 Thread Laura Creighton
Ooops, didn't send this to the list.  sorry.


Laura
--- Forwarded Message

>Laura,
>
>I checked out QtCreator but see zero sign of it supporting python - even tried 
>a search and the only hit was a job opening.  Am I missing something?
>
>
>Jon Paris

The Qt Creator announcment for the 2.8.0 release says:

An editor specific for Python was added, with highlighting and
indentation, and a Python class wizard

http://blog.qt.io/blog/2013/07/11/qt-creator-2-8-0-released/

so I thought that meant it supported Python.  Seems the support is
rather rough around the edges, but I found some good information
here: 

http://stackoverflow.com/questions/24100602/developing-python-applications-in-qt-creator

Laura


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


Re: [Tutor] Messy - Very Messy string manipulation.

2015-10-28 Thread Zachary Ware
On Wed, Oct 28, 2015 at 11:09 AM, Zachary Ware
 wrote:
>assert remove_vowels('Did It work? Looks like.') == 'Dd t wrk? Lks Lke.'

Of course I typo'd here (that's what you get for not testing!): there
should be no final 'e' and the last 'L' should be lower-case.

   assert remove_vowels('Did It work? Looks like.') == 'Dd t wrk? Lks lk.'

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


Re: [Tutor] Messy - Very Messy string manipulation.

2015-10-28 Thread Zachary Ware
On Wed, Oct 28, 2015 at 10:09 AM, Vusa Moyo  wrote:
> Hi Guys,
>
> I've written a script to remove vowels from a string/sentence.
>
> the while loop I'm using below is to take care of duplicate vowels found in
> a sentence, ie
>
> anti_vowel('The cow moos louder than the frog')
>
> It works, but obviously its messy and n00by. Any suggestions on how I can
> write this code better?

First off, the code that works (by "works" I mean "passes its tests")
is far better than the code that doesn't, no matter what form that
code takes.  That said, there are several tricks you can use to
significantly shorten your function here.

> def anti_vowel(text):

I'd rather name this "remove_vowels", since that's what it *does*
rather than what it *is* is an English sense.

> vowel = ['a', 'e', 'i', 'o', 'u']
> VOWEL = ['A', 'E', 'I', 'O', 'U']

Strings can be thought of as tuples optimized for characters, with
some special methods.  Tuples, in turn, can be thought of as immutable
lists.  So the above can be shortened to:

   vowel = 'aeiou'
   VOWEL = 'AEIOU'

Using one of those special methods I mentioned:

   vowel = 'aeiou'
   VOWEL = vowel.upper()

But do we really need two separate vowel containers?

   vowels = 'aeiou'
   all_vowels = vowels + vowels.upper()

Or to save a name, and some typing:

   vowels = 'aeiou'
   vowels += vowels.upper()

> manip = []
>
> for i in text:
> manip.append(i)

Any time you have the pattern "create an empty list, then append to it
in a for loop", think "comprehension".  The above could be shortened
to:

   manip = [i for i in text]

Or, since the list constructor takes an iterable argument and strings
give characters upon iteration:

   manip = list(text)

But we don't really need manip at all, as I'll show further down.

> fufu = 0
> #
> while fufu < 16:

This is a fairly weird way to spell "loop 8 times", if I'm honest :).
A more idiomatic approach would be to get rid of 'fufu' and do this
instead:

   for each in range(8):

Which loops 8 times and assigns the number of the loop (0-7) to the
name 'each' each time around.  'each' could be any valid identifier
('_' is commonly used for this), 'each' just makes sense reading the
line as English.

> for x in vowel:
> if x in manip:
> manip.remove(x)
>
> for y in VOWEL:
> if y in manip:
> manip.remove(y)

Above, we combined 'vowel' and 'VOWEL' into 'vowels', so these can be
shortened into a single loop by removing the second loop and changing
the first to iterate over 'vowels' instead of 'vowel'.  But instead of
removing values from a list we just built, it's easier to build the
list without those values in the first place, see below.

> fufu = fufu + 2

This line goes away with the change from 'while' to 'for each in range'.

> strong = ''.join(manip)
> return strong

I suspect this was meant to be 'string' :).  Anyway, 'return' can
return any expression not just a name, so this could be just:

   return ''.join(manip)

So, what was I talking about with not needing 'manip' and building the
list without the values in the first place?  Combining some other
stuff mentioned above, we can build a list of the characters of the
given text, minus vowels, using a comprehension:

   list_of_chars_without_vowels = [c for c in text if c not in vowels]

To better understand what's going on here, you can "unroll" the
comprehension by initializing the name to an empty list, then moving
the initial expression (the "c" in "c for ...") to an append call all
the way inside:

   list_of_chars_without_vowels = []
   for c in text:
   if c not in vowels:
   list_of_chars_without_vowels.append(c)

'list_of_chars_without_vowels' is then in the same state your 'manip'
was in after the loops, so the loops go away entirely.
'list_of_chars_without_vowels' is an unwieldy name, but we don't
actually need to name it:

   return ''.join([c for c in text if c not in vowels])

And one final optimization (which in this case is more of a finger
optimization than a performance optimization), we can drop the square
brackets to turn the list comprehension into a generator expression:

   return ''.join(c for c in text if c not in vowels)

The difference between the two above statements is that the first
calculates the entire list of characters, then passes it to ''.join(),
which iterates through the list to create the final string, while the
second creates a generator and passes it to ''.join(), and the
generator calculates and yields the next character each time ''.join()
calls next() on it.

To put everything together, here's my final version, with a docstring,
a punny Easter egg, and a very simplistic test that is not adequate
testing:

   import random

   def remove_vowels(text):
   """Remove all vowels from 'text' and return the result."""
   vowels = 'aeiou' + random.choice(['y', ''])  # "and sometimes y"
   vowels += vowel

Re: [Tutor] How do I (idiomatically) determine when I'm looking at the last entry in a list?

2015-10-28 Thread Peter Otten
Flynn, Stephen (L & P - IT) wrote:

> Afternoon,
> 
> Python 3.
> 
> I'm iterating through a list and I'd like to know when I'm at
> the end of the said list, so I can do something different. For example
> 
> list_of_things = ['some', 'special', 'things']
> for each_entry in list_of_things:
> print(each_entry)
> if each_entry == list_of_things[-1]: # do something special to
> last entry
> ...etc
> 
> 
> Is this the idiomatic way to detect you're at the last entry in a list
> as you iterate through it?

If the list is small you can slice it:

assert items
for item in things[:-1]:
   print(item, ",", sep="")
print(items[-1])

I have written a generator similar to

>>> def g(items):
... items = iter(items)
... try: 
... prev = next(items)
... except StopIteration: 
... return
... for item in items:
... yield False, prev
... prev = item
... yield True, prev
... 
>>> for islast, item in g("abc"):
... print(item, "(done)" if islast else "(to be continued)", sep="")
... 
a(to be continued)
b(to be continued)
c(done)

but only used it once ore twice.

> For context, I'm working my way through a (csv) file which describes
> some database tables. I'm building the Oracle DDL to create that table
> as I go. When I find myself building the last column, I want to finish
> the definition with a ");" rather than the usual "," which occurs at the
> end of all other column definitions...
> 
> e.g.
> CREATE TABLE wibble
> (
> Col1  CHAR(2),
> Col2  NUMBER(5,2),
> );

This particular problem can idiomatically be addressed with str.join():

>>> print(",\n".join(["foo", "bar", "baz"]))
foo,
bar,
baz



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


Re: [Tutor] Messy - Very Messy string manipulation.

2015-10-28 Thread Peter Otten
Vusa Moyo wrote:

> I've written a script to remove vowels from a string/sentence.
> 
> the while loop I'm using below is to take care of duplicate vowels found
> in a sentence, ie
> 
> anti_vowel('The cow moos louder than the frog')
> 
> It works, but obviously its messy and n00by. Any suggestions on how I can
> write this code better?

(I'm assuming Python3)

>>> 'The cow moos louder than the frog'.translate(str.maketrans("", "", 
"aeiouAEIOU"))
'Th cw ms ldr thn th frg'


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


Re: [Tutor] Demystification of Lambda Functions

2015-10-28 Thread Peter Otten
Steven D'Aprano wrote:

> Sometimes callbacks are particularly short and simple. Suppose you are 
> programming a calculator, and you have ten buttons 0...9 which all do 
> precisely the same thing: they add their own name to the calculator 
> display:
> 
> 
> for num in range(0, 10):
> btn = Button(str(num), style="rectangle", 
>  callback = lambda thebtn: display.add(thebtn.name)
>  )
> 
> 
> Much better than having to pre-define ten functions and add them to each 
> of the buttons.

In this case the lambda obscures the fact that those ten functions are 
identical, so I'd prefer

def add_digit(button):
display.add(button.name)

for num in range(10):
button = Button(str(num), style="rectangle", callback=add_digit)

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


Re: [Tutor] Messy - Very Messy string manipulation.

2015-10-28 Thread Alex Kleider

On 2015-10-28 08:09, Vusa Moyo wrote:

Hi Guys,

I've written a script to remove vowels from a string/sentence.

the while loop I'm using below is to take care of duplicate vowels 
found in

a sentence, ie

anti_vowel('The cow moos louder than the frog')

It works, but obviously its messy and n00by. Any suggestions on how I 
can

write this code better?



def anti_vowel(text):
vowel = ['a', 'e', 'i', 'o', 'u']
VOWEL = ['A', 'E', 'I', 'O', 'U']
manip = []

for i in text:
manip.append(i)
fufu = 0
#
while fufu < 16:
for x in vowel:
if x in manip:
manip.remove(x)

for y in VOWEL:
if y in manip:
manip.remove(y)

fufu = fufu + 2

strong = ''.join(manip)
return strong



Thanks - Vusa


This struck me as a good place to utilize list comprehension.


VOWELS = 'aeiouAEIOU'

def remove_chars(s, chars2remove=VOWELS):
"""Returns the string s but without any of
the characters found in chars2remove.
If given only one parameter, defaults to removing vowels.
"""
s_as_list = [char for char in s]
without_chars2remove = [
char for char in s_as_list if char not in chars2remove]
#   print(s_as_list)  # for testing
#   print(without_chars2remove)   #ditto
return "".join(without_chars2remove)

if __name__ == "__main__":
print(remove_chars(
'The cow moos louder than the frog'))



There may be some other constructs (the string join method on the empty 
string)

to which you haven't yet been exposed.
Confession: I'm submitting it probably as much to garner comments from 
the

pundits as to help you.
cheers,
Alex
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Messy - Very Messy string manipulation.

2015-10-28 Thread Alex Kleider

On 2015-10-28 09:37, Peter Otten wrote:

Vusa Moyo wrote:


I've written a script to remove vowels from a string/sentence.

the while loop I'm using below is to take care of duplicate vowels 
found

in a sentence, ie

anti_vowel('The cow moos louder than the frog')

It works, but obviously its messy and n00by. Any suggestions on how I 
can

write this code better?


(I'm assuming Python3)


'The cow moos louder than the frog'.translate(str.maketrans("", "",

"aeiouAEIOU"))
'Th cw ms ldr thn th frg'



I didn't know about the possibility of a third argument.  Thanks, Peter.

from the docs:
"""
static str.maketrans(x[, y[, z]])

This static method returns a translation table usable for 
str.translate().


If there is only one argument, it must be a dictionary mapping 
Unicode ordinals (integers) or characters (strings of length 1) to 
Unicode ordinals, strings (of arbitrary lengths) or None. Character keys 
will then be converted to ordinals.


If there are two arguments, they must be strings of equal length, 
and in the resulting dictionary, each character in x will be mapped to 
the character at the same position in y. If there is a third argument, 
it must be a string, whose characters will be mapped to None in the 
result.

"""

Although not explicitly stated, I assume that if there is a third 
argument, the first 2 will be ignored.

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


Re: [Tutor] Messy - Very Messy string manipulation.

2015-10-28 Thread Alan Gauld

On 28/10/15 16:37, Peter Otten wrote:


'The cow moos louder than the frog'.translate(str.maketrans("", "",

"aeiouAEIOU"))
'Th cw ms ldr thn th frg'


Even easier, forget the maketrans stuff and just use

'The cow moos louder than the frog'.translate(None,'aeiouAEIOU')


--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
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] Messy - Very Messy string manipulation.

2015-10-28 Thread Peter Otten
Alex Kleider wrote:

> On 2015-10-28 09:37, Peter Otten wrote:
>> Vusa Moyo wrote:
>> 
>>> I've written a script to remove vowels from a string/sentence.
>>> 
>>> the while loop I'm using below is to take care of duplicate vowels
>>> found
>>> in a sentence, ie
>>> 
>>> anti_vowel('The cow moos louder than the frog')
>>> 
>>> It works, but obviously its messy and n00by. Any suggestions on how I
>>> can
>>> write this code better?
>> 
>> (I'm assuming Python3)
>> 
> 'The cow moos louder than the frog'.translate(str.maketrans("", "",
>> "aeiouAEIOU"))
>> 'Th cw ms ldr thn th frg'
>> 
> 
> I didn't know about the possibility of a third argument.  Thanks, Peter.
> 
> from the docs:
> """
> static str.maketrans(x[, y[, z]])
> 
>  This static method returns a translation table usable for
> str.translate().
> 
>  If there is only one argument, it must be a dictionary mapping
> Unicode ordinals (integers) or characters (strings of length 1) to
> Unicode ordinals, strings (of arbitrary lengths) or None. Character keys
> will then be converted to ordinals.
> 
>  If there are two arguments, they must be strings of equal length,
> and in the resulting dictionary, each character in x will be mapped to
> the character at the same position in y. If there is a third argument,
> it must be a string, whose characters will be mapped to None in the
> result.
> """
> 
> Although not explicitly stated, I assume that if there is a third
> argument, the first 2 will be ignored.

Don't guess, fire up the interactive interpreter ;)

>>> "abcdef".translate(str.maketrans("acf", "ACF", "bde"))
'ACF'

All argument have an effect. Now have a look at the dict created by 
maketrans:

>>> str.maketrans("acf", "ACF", "bde")
{97: 65, 98: None, 99: 67, 100: None, 101: None, 102: 70}

If the value is an int, str.translate() replaces chr(key) with chr(value), 
if the value is None chr(key) is removed. 

You can also replace one char with multiple chars, but for that you have to 
build the dict yourself:

>>> "ähnlich üblich löblich".translate(
... {ord(a): b for a, b in [
... ("ä", "ae"), ("ö", "oe"), ("ü", "ue")]})
'aehnlich ueblich loeblich'


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


Re: [Tutor] Are there any Python-based GUI builders for tkinter

2015-10-28 Thread Mark Lawrence

On 28/10/2015 08:39, Laura Creighton wrote:

In a message of Tue, 27 Oct 2015 15:20:56 -0500, boB Stepp writes:

I have a friend at work and he is trying to develop GUI applications
in Python, but he does not want to hand-code them.  Are there any
commercial or non-commercial products that would do this for him?  He
tried his own online search but was unsuccessful.

His OS is Mac OS 10.10 and is using Python 3.5.

TIA!

--
boB


check out QtDesigner

http://doc.qt.io/qt-5/qtdesigner-manual.html

or QtCreator
http://www.qt.io/ide/

if you want the whole process to happen inside an IDE.

https://wiki.python.org/moin/PyQt/Creating_GUI_Applications_with_PyQt_and_Qt_Designer
 may be useful as well, though its a little old by now.

Laura



I was't aware that Qt would work with tkinter as given in the subject. 
Could you elaborate please?


--
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] Messy - Very Messy string manipulation.

2015-10-28 Thread Peter Otten
Alan Gauld wrote:

> On 28/10/15 16:37, Peter Otten wrote:
> 
> 'The cow moos louder than the frog'.translate(str.maketrans("", "",
>> "aeiouAEIOU"))
>> 'Th cw ms ldr thn th frg'
> 
> Even easier, forget the maketrans stuff and just use
> 
> 'The cow moos louder than the frog'.translate(None,'aeiouAEIOU')

This only works for byte strings, not unicode.

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


[Tutor] export pandas excel

2015-10-28 Thread Lucas Mascia
Hello,

Attached is my program, I have filtered some data from an extensive table
from excel. I have it running for two names:

ps_sol = ["Mauro Cavalheiro Junior", "Aline Oliveira"]
> for name in ps_sol:
> 


At the end I am trying to export to another .xlsx file. But it is only
saving the info of the last name in the list.

I want it to save for all names that i list in my ps_sol


Help please (:




| VIEW MY | 

"It is not the strongest of the species that survives, nor the most
intelligent that survives. It is the one that is most adaptable to change."
 - Darwin.
import pandas as pd
import sys


#file loc
R1 = input('Data do Relatório desejado  (dd.mm) --->  ')
loc = r'C:\Users\lucas.mascia\Downloads\relatorio-{0}.xlsx'.format(R1)

##

#Solicitantes
ps_sol = ["Mauro Cavalheiro Junior", "Aline Oliveira"]


#Aplicando filtros
for name in ps_sol:

#opening file
df = pd.read_excel(loc)
dfps = df[[2,15,16,17]]

#apply filter
f1 = dfps[(dfps['Cliente']=="POSTAL SAUDE")
& (dfps['Nome do solicitante']==name)]

#print info
print ('''
=
Relatorio do dia:   {}
Cliente:POSTAL SAUDE
Solicitante:{}
=
'''.format(R1, name))

print (f1)

f1.to_excel('C:/Users/lucas.mascia/Downloads/ps_sol.xlsx', 
sheet_name=name)___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Messy - Very Messy string manipulation.

2015-10-28 Thread Alan Gauld

On 28/10/15 17:35, Peter Otten wrote:

Alan Gauld wrote:


On 28/10/15 16:37, Peter Otten wrote:


'The cow moos louder than the frog'.translate(str.maketrans("", "",

"aeiouAEIOU"))
'Th cw ms ldr thn th frg'


Even easier, forget the maketrans stuff and just use

'The cow moos louder than the frog'.translate(None,'aeiouAEIOU')


This only works for byte strings, not unicode.


Aha, I tried it in Python 2.7 which worked, but I didn't
think about v3...

--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
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] Messy - Very Messy string manipulation.

2015-10-28 Thread Zachary Ware
On Wed, Oct 28, 2015 at 11:09 AM, Zachary Ware
 wrote:
>return ''.join(c for c in text if c not in vowels

Looking again, I see I typo'd here too.  There should of course be a
')' at the end.

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


Re: [Tutor] How do I (idiomatically) determine when I'm looking at the last entry in a list?

2015-10-28 Thread Cameron Simpson

On 28Oct2015 14:48, Flynn, Stephen (L & P - IT)  
wrote:

Python 3.

I'm iterating through a list and I'd like to know when I'm at
the end of the said list, so I can do something different. For example

list_of_things = ['some', 'special', 'things']
for each_entry in list_of_things:
print(each_entry)
if each_entry == list_of_things[-1]: # do something special to
last entry
...etc

Is this the idiomatic way to detect you're at the last entry in a list
as you iterate through it?


If it really is a list then enumerate is your friend.

 list_of_things = ['some', 'special', 'things']
 last_index = len(list_of_things) - 1
 for index, each_entry in enumerate(list_of_things):
   print(each_entry)
   if index == last_index:
 ... special stuff for the last index ...


For context, I'm working my way through a (csv) file which describes
some database tables. I'm building the Oracle DDL to create that table
as I go. When I find myself building the last column, I want to finish
the definition with a ");" rather than the usual "," which occurs at the
end of all other column definitions...


This is a bit different, in that you are probably not using a list: you don't 
know how long the sequence is.


I build things like that this way:

 fp.write('CREATE TABLE wibble\n(')
 sep = '\n   '
 for item in items:
   fp.write(sep)
   fp.write(... column definition for item ...)
   sep = ',\n   '
 fp.write('\n);\n')

i.e. instead of printing the separator _after_ each item, print it _before_.  
That way you can special case the first occasion and use a comma for each 
successive occasion.


Cheers,
Cameron Simpson 

Why is it whatever we don't understand is called a 'thing'? - "Bones" McCoy
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Are there any Python-based GUI builders for tkinter

2015-10-28 Thread Laura Creighton
In a message of Wed, 28 Oct 2015 17:31:35 +, Mark Lawrence writes:
>On 28/10/2015 08:39, Laura Creighton wrote:
>> In a message of Tue, 27 Oct 2015 15:20:56 -0500, boB Stepp writes:
>>> I have a friend at work and he is trying to develop GUI applications
>>> in Python, but he does not want to hand-code them.  Are there any
>>> commercial or non-commercial products that would do this for him?  He
>>> tried his own online search but was unsuccessful.
>>>
>>> His OS is Mac OS 10.10 and is using Python 3.5.
>>>
>>> TIA!
>>>
>>> --
>>> boB
>>
>> check out QtDesigner
>>
>> http://doc.qt.io/qt-5/qtdesigner-manual.html
>>
>> or QtCreator
>> http://www.qt.io/ide/
>>
>> if you want the whole process to happen inside an IDE.
>>
>> https://wiki.python.org/moin/PyQt/Creating_GUI_Applications_with_PyQt_and_Qt_Designer
>>  may be useful as well, though its a little old by now.
>>
>> Laura
>>
>
>I was't aware that Qt would work with tkinter as given in the subject. 
>Could you elaborate please?

I actually only read the text of the letter, and not the subject
line.  So I assumed any gui toolkit he did not have to build himself
that would work with python would be fine.  

Laura

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


Re: [Tutor] export pandas excel

2015-10-28 Thread Alan Gauld

On 28/10/15 15:26, Lucas Mascia wrote:

Hello,

Attached is my program,


When its a short program(<100 lines say) just include it in the text.
Attachments often get rejected by email gateways, especially on 
corporate firewalls or for mobile devices.


=
import pandas as pd
import sys


#file loc
R1 = input('Data do Relatório desejado  (dd.mm) --->  ')
loc = r'C:\Users\lucas.mascia\Downloads\relatorio-{0}.xlsx'.format(R1)

##

#Solicitantes
ps_sol = ["Mauro Cavalheiro Junior", "Aline Oliveira"]


#Aplicando filtros
for name in ps_sol:

#opening file
df = pd.read_excel(loc)
dfps = df[[2,15,16,17]]

#apply filter
f1 = dfps[(dfps['Cliente']=="POSTAL SAUDE")
& (dfps['Nome do solicitante']==name)]

#print info
print ('''
=
Relatorio do dia:   {}
Cliente:POSTAL SAUDE
Solicitante:{}
=
'''.format(R1, name))

print (f1)

f1.to_excel('C:/Users/lucas.mascia/Downloads/ps_sol.xlsx', 
sheet_name=name)

===



At the end I am trying to export to another .xlsx file. But it is only
saving the info of the last name in the list.


Pandas is outside the scope of this list so I don't know much about
it. But is it possible that to_excel() creates a new file each time?
Is there an append flag you can pass maybe?

Finally in the line starting f1=dfps...

Is that really supposed to be a bitwise AND (&) operation? It seems 
unlikely given the two operands are both boolean values. It should

work but it looks wrong. I would expect a logical AND (and).

I can't comment on the rest because it is too pandas (and data )
specific to make any sense to me.

--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
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] How do I (idiomatically) determine when I'm looking at the last entry in a list?

2015-10-28 Thread Steven D'Aprano
On Wed, Oct 28, 2015 at 02:48:05PM +, Flynn, Stephen (L & P - IT) wrote:

>   I'm iterating through a list and I'd like to know when I'm at
> the end of the said list, so I can do something different. For example
> 
> list_of_things = ['some', 'special', 'things']
> for each_entry in list_of_things:
>   print(each_entry)
>   if each_entry == list_of_things[-1]: # do something special to
> last entry
>   ...etc
> 
> 
> Is this the idiomatic way to detect you're at the last entry in a list
> as you iterate through it?

But it doesn't detect the last entry. Consider:

list_of_things = ["cheese", "fruit", "cheese", "fish", "cheese"]

Your code will perform the special processing three times.

There's no idiomatic way to do this because it is a fairly unusual thing 
to do. Normally we want to process all the items in a list the same way. 
But here are some solutions:

(1) Avoid the problem altogether by arranging matters so that the "last 
item" isn't in the list at all.

list_of_things = ['some', 'special']
last = 'things'
for each_entry in list_of_things:
print(each_entry)

print(last.upper())


(2) Slicing. Requires a little extra memory, but is probably the closest 
to an idiomatic solution for this sort of thing.

list_of_things = ['some', 'special', 'things']
for each_entry in list_of_things[:-1]:
print(each_entry)

print(list_of_things[-1].upper())


(3) Add a sentinel to the list.

list_of_things = ['some', 'special', None, 'things']
for each_entry in list_of_things:
if each_entry is None: break
print(each_entry)

print(list_of_things[-1].upper())


(4) Count the items.

list_of_things = ['some', 'special', 'things']
for i, each_entry in enumerate(list_of_things):
if i == len(list_of_things) - 1:  # Watch out for off-by-one errors!
each_entry = each_entry.upper()
print(each_entry)


(5) What if you're dealing with an iterable of unknown length that can't 
be sliced? The obvious answer is to convert to a list:

list_of_things = list(things)

but suppose you have some reason for not wanting to do that. (Perhaps 
things is truly huge, billions of items.) Something like this should 
help:

prev = []
for this in things:
if prev:
print(prev[0])
prev = [this]

print(prev[0].upper())


We can make this a little more efficient if things is an actual 
iterator:

things = iter(things)
try:
prev = next(things)
except StopIteration:
# No things at all.
pass
else:
for this in things:
print(prev)
prev = this
print(prev.upper())



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


Re: [Tutor] How do I (idiomatically) determine when I'm looking at the last entry in a list?

2015-10-28 Thread Steven D'Aprano
Wait, I have another comment...

On Wed, Oct 28, 2015 at 02:48:05PM +, Flynn, Stephen (L & P - IT) wrote:

>   I'm iterating through a list and I'd like to know when I'm at
> the end of the said list, so I can do something different. For example
[...]
> For context, I'm working my way through a (csv) file which describes
> some database tables. I'm building the Oracle DDL to create that table
> as I go. When I find myself building the last column, I want to finish
> the definition with a ");" rather than the usual "," which occurs at the
> end of all other column definitions...

Then you don't need to know when you're at the end of the list. See 
below.

But firstly, and MOST IMPORTANTLY, how are you sanitizing your input?

http://bobby-tables.com/

Code injection attacks are now #1 risk factor for code, above buffer 
overflows.

So, assuming you have sanitized your input, or trust it more than you 
trust your own code (you run tests on your own code, right?), let's see 
how to build up a string like:

"FUNCTION(a,b,c,d,e);"

with some variable number of string arguments a, b, c, ... 


args = ["5", "2", "7", "1", "0", "3"]
result = "FUNCTION(%s);" % ','.join(args)


This will do the right thing whether there is one argument or twenty, or 
even no arguments at all.

The "join" method inserts the first string *between* each of the list 
items. It deals correctly with the "no items" and "one item" cases:

py> "--".join([])
''
py> "--".join(["spam"])
'spam'
py> "--".join(["spam", "eggs"])
'spam--eggs'
py> "--".join(["spam", "eggs", "cheese"])
'spam--eggs--cheese'


so you don't have to worry about counting items or determining the last 
item, you just join them. 


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


Re: [Tutor] Are there any Python-based GUI builders for tkinter

2015-10-28 Thread Mark Lawrence

On 28/10/2015 22:32, Laura Creighton wrote:

In a message of Wed, 28 Oct 2015 17:31:35 +, Mark Lawrence writes:

On 28/10/2015 08:39, Laura Creighton wrote:

In a message of Tue, 27 Oct 2015 15:20:56 -0500, boB Stepp writes:

I have a friend at work and he is trying to develop GUI applications
in Python, but he does not want to hand-code them.  Are there any
commercial or non-commercial products that would do this for him?  He
tried his own online search but was unsuccessful.

His OS is Mac OS 10.10 and is using Python 3.5.

TIA!

--
boB


check out QtDesigner

http://doc.qt.io/qt-5/qtdesigner-manual.html

or QtCreator
http://www.qt.io/ide/

if you want the whole process to happen inside an IDE.

https://wiki.python.org/moin/PyQt/Creating_GUI_Applications_with_PyQt_and_Qt_Designer
 may be useful as well, though its a little old by now.

Laura



I was't aware that Qt would work with tkinter as given in the subject.
Could you elaborate please?


I actually only read the text of the letter, and not the subject
line.  So I assumed any gui toolkit he did not have to build himself
that would work with python would be fine.

Laura



How many times do I have to say this, never assume anything, and I 
assume that you're okay with that? :)


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