Re: [Tutor] Test for type(object) == ???

2017-02-11 Thread eryk sun
On Sat, Feb 11, 2017 at 7:35 AM, boB Stepp  wrote:
> Has this PEP been implemented yet?  I am running Python 3.5.2 and it
> appears not to work.  Also, in "What's New In Python 3.6"
> (https://docs.python.org/3/whatsnew/3.6.html) I did not see a mention
> of it.

You can see in the document header that PEP 457 is an Informational
document at the draft stage, as opposed to a Standards Track document
that's finalized. It's the best I could find as provisional
documentation of CPython's usage of '/' to mark positional-only
arguments of built-in functions. FYI, the PEP's author, Larry
Hastings, is also the author of Argument Clinic.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Python-list thread: int vs. float

2017-02-11 Thread Steven D'Aprano
On Fri, Feb 10, 2017 at 07:59:04PM -0600, boB Stepp wrote:

> He cannot figure out how to reliably tell if the user's input is an
> integer, float or neither.  So I thought I would come up with my
> solution, which currently is:
> 
> py3: def ck_input():
> ... value_to_ck = input('Enter a number:')
> ... try:
> ... value = int(value_to_ck)
> ... print('You have entered an integer.')
> ... except ValueError:
> ... try:
> ... value = float(value_to_ck)
> ... print('You have entered a float.')
> ... except ValueError:
> ... print('You have failed to enter a numerical value.')
> ...
[...]
> This is all well and good.  I am not trying to elicit an "Atta boy,
> boB!" here. ~(:>)) 

Nevertheless, atta boy boB! 

The only not-so-good part of this is that you have mixed user-interface 
and internal calculation. Better:


def to_number(string):
"""Convert string to either an int or a float, or raise ValueError."""
try:
return int(string)
except ValueError:
return float(string)


def check_input():
value_to_ck = input('Enter a number: ')
try:
value = to_number(value_to_ck)
except ValueError:
print('You have failed to enter a numerical value.')
return
if isinstance(value, float):
print('You have entered a float.')
else:
print('You have entered an int.')


This gives you nice separation between the function that interacts with 
the user, and the function that does the actual conversion.



> Instead, I am wondering if there is something in
> Python's wonderful cornucopia of programming stuff that can simplify
> this type of check.

The most reliable and foolproof way of checking if something is a valid 
int is to ask int to convert it, and see if it fails.

Likewise for floats, where the format is *very* complex. Any of these, 
and many more, should be accepted:

1.2345
+1.2345
-1.2345e0
123.45e+20
123.45E-20
.123
-.123
+.123e-12
123.
inf
+inf
-inf
NaN

Getting all the gory details right of what is and isn't allowed may be 
tricky, but that's okay, because float() already understands how to do 
it for you.


> As you might guess from my earlier post this
> evening, I have been playing around with "type()" and "isinstance()",
> but if I try something like:
> 
> py3: isinstance(int('5.0'))
> Traceback (most recent call last):
>   File "", line 1, in 
> ValueError: invalid literal for int() with base 10: '5.0'

The problem here is that int('5.0') raises an exception because '.' is 
not a valid digit for integers, so it fails before isinstance() gets a 
chance to run.

Valid digits for integers include 0 through 9 in decimal, plus no more 
than one leading + or - sign, and whitespace (space, tabs, newlines) 
before or after the string. If you specify the base, the set of valid 
digits will change, e.g. int(string, 16) will allow 0 through 9 plus A 
through F in lower and upper case.

But whatever base you choose, '.' is not a valid digit.



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


Re: [Tutor] Python-list thread: int vs. float

2017-02-11 Thread eryk sun
On Sat, Feb 11, 2017 at 8:06 AM, Steven D'Aprano  wrote:
> Valid digits for integers include 0 through 9 in decimal

Note that Python 3 uses the Unicode database to determine the decimal
value of characters, if any. It's not limited to the ASCII decimal
digits 0-9. For example:

>>> s
'௧꘢୩'
>>> int(s)
123
>>> print(*(unicodedata.name(c) for c in s), sep='\n')
TAMIL DIGIT ONE
VAI DIGIT TWO
ORIYA DIGIT THREE
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Test for type(object) == ???

2017-02-11 Thread Steven D'Aprano
On Fri, Feb 10, 2017 at 07:34:35PM -0600, boB Stepp wrote:
> I was playing around with type() tonight.  If I type (pun intended), I get:
> 
> py3: type(5)
> 
> 
> So I naively thought a test for type int should go like:
> 
> py3: type(5) == ""
> False


The interactive intepreter is great, but you have to remember that what 
you see is not necessarily what you've got. What you *see* is the string 
representation of the object:

py> print


but what you've actually got is the object itself; in this case, it is 
the print function, and in your case, it is the int class.

Generally angle brackets < > mean that the text between the brackets is 
just a display form, something intended for the human reader, and not a 
programmable syntax. You then have to know (from experience) how to 
refer to the object in code.

In the case of int, there are three distinct things here:

- the class (or type) itself, a blob of memory somewhere in the 
interpreter containing various methods and attributes used for working 
with integers;

- the name the interpreter knows that class by, namely "int";

- the string representation for the human reader, "".


So long as you remember the difference between the object itself, the 
name we use to talk about the object, and the way we visually display 
the object, you can't go wrong :-)

(The nation Russia is not the same as a map of Russia, which is not the 
same as the word Russia, which is not the same as the letters R u 
s s i a, or even Р о с с и ́я for that matter). 

As they say: the map is not the territory. Or in the words of Steven 
Wright, "I have a map of the United States... Actual size. It says, 
'Scale: 1 mile = 1 mile.' I spent last summer folding it."


> I finally stumbled onto the correct form:
> 
> py3: type(5) == int
> True

type(5) returns the class that we call "int". The name "int" returns 
that same class.


> So my question is why does "type(5)" result in "",

No, that's just the string representation of int.

Inside the interactive interpreter, when you hit ENTER, the interpreter 
evaluates the line of code you have, generates a result, and then does 
the equivalent of:

print(repr(result))

(except that None is suppressed).


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


Re: [Tutor] Test for type(object) == ???

2017-02-11 Thread Steven D'Aprano
On Sat, Feb 11, 2017 at 01:00:11PM +1100, Ben Finney wrote:
> boB Stepp  writes:
> 
> > I was playing around with type() tonight.  If I type (pun intended), I get:
> >
> > py3: type(5)
> > 
> 
> Ceci n'est pas un ‘int’.
[...]
> https://en.wikipedia.org/wiki/The_Treachery_of_Images>


For anyone interested in this concept and how it relates to programming, 
and many other mind-expanding concepts, I cannot recommend enough the 
famous book 

Gödel, Escher, Bach: An Eternal Golden Braid

by Douglas Hofstadter. It is a mighty tome, but don't be put off by the 
size and weight. It covers some *extremely* subtle concepts, but it 
works up to them in baby steps, with the aid of dialogs between 
Archilles and the Tortoise.

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


[Tutor] Accessing an entry value input by the user

2017-02-11 Thread Pooja Bhalode
Hi,

I am trying to create a label and an entry widget. I am not able to
understand as to how to access the value input by the user in the entry
widget.

Label(frame1, text = "Number of species:").grid(row=0, column = 1, sticky=W)
entrynumberspecies = Entry(frame1)
entrynumberspecies.grid(row=0, column = 2, sticky=W)

print entrynumberspecies.get()

How can I make the entrynumberspecies store the value in once the user
inputs it and then use that value for later part of my code? or print it
for that matter.

Thank you

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


Re: [Tutor] Python-list thread: int vs. float

2017-02-11 Thread Alex Kleider

On 2017-02-11 00:36, eryk sun wrote:
On Sat, Feb 11, 2017 at 8:06 AM, Steven D'Aprano  
wrote:

Valid digits for integers include 0 through 9 in decimal


Note that Python 3 uses the Unicode database to determine the decimal
value of characters, if any. It's not limited to the ASCII decimal
digits 0-9. For example:

>>> s
'௧꘢୩'
>>> int(s)
123
>>> print(*(unicodedata.name(c) for c in s), sep='\n')
TAMIL DIGIT ONE
VAI DIGIT TWO
ORIYA DIGIT THREE


???
alex@X301n3:~$ python3
Python 3.4.3 (default, Nov 17 2016, 01:11:57)
[GCC 4.8.4] on linux
Type "help", "copyright", "credits" or "license" for more information.

s

Traceback (most recent call last):
  File "", line 1, in 
NameError: name 's' is not defined




What your 's' represents seems quite different to 'mine.'
There must be something else going on.
???

Also of interest (at least to me) was the 'magic' you demonstrated in 
the print function parameter list; my efforts to figure it out:

word = "Hello"
print((c for c in word))

 at 0xb71d125c>

print(*(c for c in word))

H e l l o

print(*(c for c in word), sep='')

Hello



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


Re: [Tutor] Accessing an entry value input by the user

2017-02-11 Thread Alan Gauld via Tutor
On 11/02/17 15:28, Pooja Bhalode wrote:

> I am trying to create a label and an entry widget. I am not able to
> understand as to how to access the value input by the user in the entry
> widget.
> 
> Label(frame1, text = "Number of species:").grid(row=0, column = 1, sticky=W)
> entrynumberspecies = Entry(frame1)
> entrynumberspecies.grid(row=0, column = 2, sticky=W)
> 
> print entrynumberspecies.get()

You just accessed it, via the get() method. Did that not work?

> How can I make the entrynumberspecies store the value in once the user
> inputs it and then use that value for later part of my code? 

You can do it the way you did above using the get() method.

But you can also do what you did for the checkboxes - use
a StringVar and attach it to the Entry widget textvariable
attribute. That way the variable will reflect whats in
the Entry automatically and if you update the variable
it will update the Entry. (Personally I prefer to use
get() in most cases but many use the StringVar technique.)
See the example at the bottom...

> or print it for that matter.

You can print it as you did above or you can store it in
a variable and then print it or you can print the StringVar:

print myEntry.get()

myVar = MyEntry.get()
print myVar

entryVar = StringVar()
myEntry = Entry(.textvariable=entryVar)
print entryVar.get()

Here is a minimal example:


from Tkinter import *

def show():
print "entry says: " + e.get()
print "Variable holds: " + v.get()

top = Tk()
v = StringVar()
e = Entry(top,textvariable=v)
e.pack()
Button(top,text="Set foobar", command=lambda : v.set("foobar")).pack()
Button(top,text="Show me", command=show).pack()

top.mainloop()
#


-- 
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] Python-list thread: int vs. float

2017-02-11 Thread boB Stepp
On Fri, Feb 10, 2017 at 7:59 PM, boB Stepp  wrote:
> I have been following the thread "int vs. float"
> (https://mail.python.org/pipermail/python-list/2017-February/719287.html)
> on the main list.  A search for the OP on the Tutor archive came up
> negative, so I am hoping he is not following Tutor tonight (Or anytime
> prior to the due date for his homework!).  The central part of
> adam14711993's question is:
>
> "What I cannot figure out is how to write it so that if my user input
> is, for example, 1.5, the program will result with: Sorry, you can
> only order whole packages.
>
> "I understand that because I am starting out by assigning my
> number_purchases_str to be an int, when the user enters a float that
> is a conflict and will crash."
>
> He cannot figure out how to reliably tell if the user's input is an
> integer, float or neither.

Back in the main Python list thread, Marko Rauhamaa suggested
(https://mail.python.org/pipermail/python-list/2017-February/719322.html):

"
...
Haven't been following the discussion, but this should be simply:

   ast.literal_eval("...")
...
"

This looks like it may do the trick quite concisely:

py3: import ast
py3: ast.literal_eval('5')
5
py3: ast.literal_eval('5.0')
5.0
py3: type(ast.literal_eval('5'))

py3: type(ast.literal_eval('5.0'))


It appears to reliably parse string input as to whether it is an
integer or float.  However, if the input is a non-numerical string:

py3: ast.literal_eval('a')
Traceback (most recent call last):
  File "", line 1, in 
  File "C:\Program Files\Python35\lib\ast.py", line 84, in literal_eval
return _convert(node_or_string)
  File "C:\Program Files\Python35\lib\ast.py", line 83, in _convert
raise ValueError('malformed node or string: ' + repr(node))
ValueError: malformed node or string: <_ast.Name object at 0x02C9D860>

But that seems okay, as in the OP's original problem spec, he just
needed a way to determine integer, float or other non-acceptable
input.  This seems to do this quite directly.  I am not familiar with
"abstract syntax trees" (Python has so much very interesting stuff!).
I am concerned about this paragraph at the beginning of the docs on it
(https://docs.python.org/3/library/ast.html?highlight=ast.literal_eval#module-ast):

"The ast module helps Python applications to process trees of the
Python abstract syntax grammar. The abstract syntax itself might
change with each Python release; this module helps to find out
programmatically what the current grammar looks like."

That statement about potentially changing with each Python release
bothers me.  Should I be bothered?  The link to ast.literal_eval():
https://docs.python.org/3/library/ast.html?highlight=ast.literal_eval#ast.literal_eval

What are the gotchas or other negatives from this approach?

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


Re: [Tutor] Python-list thread: int vs. float

2017-02-11 Thread boB Stepp
On Sat, Feb 11, 2017 at 11:10 AM, Alex Kleider  wrote:

> Also of interest (at least to me) was the 'magic' you demonstrated in the
> print function parameter list; my efforts to figure it out:

Isn't this just argument unpacking?  Thus the necessary "*".

 word = "Hello"
 print((c for c in word))

Need print(*(c...)) to unpack the sequence arguments.

>  at 0xb71d125c>

 print(*(c for c in word))
>
> H e l l o

Spaces because of the default setting for sep argument for print() as
you demonstrate next.

 print(*(c for c in word), sep='')
>
> Hello


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


Re: [Tutor] Python-list thread: int vs. float

2017-02-11 Thread boB Stepp
On Sat, Feb 11, 2017 at 11:10 AM, Alex Kleider  wrote:
> On 2017-02-11 00:36, eryk sun wrote:
>>

>> Note that Python 3 uses the Unicode database to determine the decimal
>> value of characters, if any. It's not limited to the ASCII decimal
>> digits 0-9. For example:
>>
>> >>> s
>> '௧꘢୩'
>> >>> int(s)
>> 123
>> >>> print(*(unicodedata.name(c) for c in s), sep='\n')
>> TAMIL DIGIT ONE
>> VAI DIGIT TWO
>> ORIYA DIGIT THREE
>
>
> ???
> alex@X301n3:~$ python3
> Python 3.4.3 (default, Nov 17 2016, 01:11:57)
> [GCC 4.8.4] on linux
> Type "help", "copyright", "credits" or "license" for more information.

 s
>
> Traceback (most recent call last):
>   File "", line 1, in 
> NameError: name 's' is not defined


> What your 's' represents seems quite different to 'mine.'
> There must be something else going on.

I suspect Eryk had set a normal 's' as an identifier for the character
code sequence that produces the non-ASCII output, but forgot to show
us that step.  But I could be mistaken.

Today I am working in Windows 7, not Linux Mint.  Of course when I
attempted to copy and paste the non-ASCII sequence from Gmail into
cmd.exe I got 3 rectangular boxes on the paste line, indicating
cmd.exe could not translate those characters.  However, if I paste
them into IDLE or gvim, things are translated correctly:

Python 3.5.2 (v3.5.2:4def2a2901a5, Jun 25 2016, 22:18:55) [MSC v.1900
64 bit (AMD64)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> s
Traceback (most recent call last):
  File "", line 1, in 
s
NameError: name 's' is not defined
>>> '௧꘢୩'
'௧꘢୩'
>>>

I think that this demonstrates that 's' is just an identifier pointing
to the non-ASCII character sequence, but that the actual characters
can be copied and pasted *if* the editor or environment you paste
those characters into is setup to translate those characters.

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


Re: [Tutor] Python-list thread: int vs. float

2017-02-11 Thread boB Stepp
On Sat, Feb 11, 2017 at 2:06 AM, Steven D'Aprano  wrote:
> On Fri, Feb 10, 2017 at 07:59:04PM -0600, boB Stepp wrote:
>
>> He cannot figure out how to reliably tell if the user's input is an
>> integer, float or neither.  So I thought I would come up with my
>> solution, which currently is:
>>
>> py3: def ck_input():
>> ... value_to_ck = input('Enter a number:')
>> ... try:
>> ... value = int(value_to_ck)
>> ... print('You have entered an integer.')
>> ... except ValueError:
>> ... try:
>> ... value = float(value_to_ck)
>> ... print('You have entered a float.')
>> ... except ValueError:
>> ... print('You have failed to enter a numerical value.')
>> ...

> The only not-so-good part of this is that you have mixed user-interface
> and internal calculation. Better:
>
>
> def to_number(string):
> """Convert string to either an int or a float, or raise ValueError."""
> try:
> return int(string)
> except ValueError:
> return float(string)
>
>
> def check_input():
> value_to_ck = input('Enter a number: ')
> try:
> value = to_number(value_to_ck)
> except ValueError:
> print('You have failed to enter a numerical value.')
> return
> if isinstance(value, float):
> print('You have entered a float.')
> else:
> print('You have entered an int.')
>
>
> This gives you nice separation between the function that interacts with
> the user, and the function that does the actual conversion.

Ah!  I am glad I asked the questions.  There is a difference between
intellectually understanding what I should do and reliably
implementing it in my regular coding practice.  This is one such
instance, probably of many unfortunately.  I knew something was
bothering me about this.  I did not like nesting try...except
two-deep.  Now that you have shown the way, I see what was nagging at
me.  Thanks, Steve!

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


Re: [Tutor] Accessing an entry value input by the user

2017-02-11 Thread Pooja Bhalode
Hi Alan,

I had done what you suggested here, I also tried creating another file for
that snipet of the code to see if that section works. The other file works,
but I am not able to figure out why the original one doesn't work.
The variable here is entrynumberspeciesvar

Code:
from Tkinter import *
import datetime
import tkMessageBox
from tkFileDialog import *
from tkMessageBox import *
root = Tk()
root.title("Design of Experiments with Parameter Estimation")
root.geometry("1000x1000")

statusvar = StringVar()
statusvar = "Status Bar"

var1 = IntVar()
var2 = IntVar()
var3 = IntVar()
var4 = IntVar()

varreac = IntVar()
varint = IntVar()
varpro = IntVar()

varconc = IntVar()
vartemp = IntVar()
entrynumberspeciesvar = IntVar()

def DesignPoint():
print "Inside Design Point"
rootdesign=Tk()
rootdesign.title("Design Point Suggestions")
rootdesign.geometry("700x400")
frame1 = Frame(rootdesign)
frame1.grid(row=0, column=0)

label1 = Label(frame1, text="1. Responses to include: ")
label1.grid(row=0, column=0,sticky=W)


Label(frame1, text = "Number of species:").grid(row=0, column = 1,
sticky=W)
entrynumberspecies = Entry(frame1, textvariable = entrynumberspeciesvar)
entrynumberspecies.grid(row=0, column = 2, sticky=W)

# print entrynumberspeciesvar.get()
checkreac = Checkbutton(frame1, text = "Reactant species", variable =
varreac)
checkreac.grid(row = 1, column = 1, sticky = W)
checkreac.select()
Checkbutton(frame1, text = "Intermediate species", variable =
varint).grid(row = 2, column = 1, sticky = W)
Checkbutton(frame1, text = "Product species", variable =
varpro).grid(row = 3, column = 1, sticky = W)

def Default():
print "Inside default"

var1.set(0)
var2.set(0)
var3.set(0)
var4.set(1)
Checkbutton(frame1, text = "Vertices", variable=var1, onvalue=1,
offvalue=0).grid(row=1, column = 2, sticky=W)
Checkbutton(frame1, text = "Edges", variable=var2).grid(row=2, column =
2, sticky=W)
Checkbutton(frame1, text = "Faces", variable=var3).grid(row=3, column =
2, sticky=W)
check = Checkbutton(frame1, text = "Center", variable=var4)

check.grid(row=4, column = 2, sticky=W)
check.select()

Label(frame1, text="2. Variables to be adjusted:").grid(row=5,
column=0,sticky=W)
Checkbutton(frame1, text = "Concentration", variable=varconc,
onvalue=1, offvalue=0).grid(row=5, column = 1, sticky=W)
Checkbutton(frame1, text = "Temperature", variable=vartemp).grid(row=6,
column = 1, sticky=W)

def InsertRange():
print "Inside InsertRange"
# entrynumberspeciesvar.set(2)
print entrynumberspeciesvar.get()
for i in range(entrynumberspeciesvar.get()):
textvar = StringVar()
print i
textvar = "\t Conc"+str(i)
Label(frame1, text=textvar).grid(row=(9+i), column=0,sticky=W)
conclowerentry = Entry(frame1)
conclowerentry.grid(row= (9+i), column = 1, sticky = W)
concupperentry = Entry(frame1)
concupperentry.grid(row= (9+i), column = 2, sticky = W)


Label(frame1, text="3. Range of formulation:").grid(row=7,
column=0,sticky=W)
Button(frame1, text = "Insert Range", command = InsertRange()).grid(row
= 7, column = 3, sticky=W)
Label(frame1, text="Lower Limit").grid(row=7, column=1,sticky=W)
Label(frame1, text="Upper Limit").grid(row=7, column=2,sticky=W)

Label(frame1, text="\t Temperature").grid(row=8, column=0,sticky=W)
templowerentry = Entry(frame1, text="0.0")
templowerentry.grid(row= 8, column = 1, sticky = W)
tempupperentry = Entry(frame1)
tempupperentry.grid(row= 8, column = 2, sticky = W)

rootdesign.mainloop()


## Secondary menu bar:
menusec = Frame(root, bg="white")
butt1 = Button(menusec, text="Part One", command=DesignPoint)
butt1.pack(side=LEFT, padx=1)
menusec.pack(side=TOP, fill=X)


### --- Status bar  
Status = Label(root, text = statusvar, bd=1, relief=SUNKEN, anchor=W)
Status.pack(side=BOTTOM, fill=X)

text = Text(root, width=1000, height = 400)
text.pack(side=BOTTOM)


root.mainloop()

I have removed other parts of the code and included only the ones related
to the entry box and the work that I need to do.
I also tried doing it in another file as mentioned before. That works the
exact way I want.

Code:
from Tkinter import *

rootdesign=Tk()
rootdesign.title("Design Point Suggestions")
rootdesign.geometry("650x400")
frame1 = Frame(rootdesign)
frame1.grid(row=0, column=0)
entrynumberspeciesvar = IntVar()
## Inserting Checkboxes:
label1 = Label(frame1, text="1. Responses to include: ")
label1.grid(row=0, column=0,sticky=W )
Label(frame1, text = "Number of species:").grid(row=0, column = 1, sticky=W)
entrynumberspecies = Entry(frame1, textvariable = entrynumberspeciesvar)
entrynumberspecies.grid(row=0, column = 2, sticky=W)

def Print():
print entrynumberspeciesvar.get()
for i in range(entrynumberspeciesv

Re: [Tutor] Find (list) strings in large textfile

2017-02-11 Thread Sylwester Graczyk


It is probably better to store your key file in memory
then loop over the large data file and check the
line against each key. Better to check 2000 data
keys in memory for one loop of the data file.
That way you only read the key file and data file
once each - 502,000 reads instead of a billion.

I replace one loop (in file), with searching in a *list*, and it's much 
faster :)


   my_list = open("list_file.txt")
   file_list = [i[:-1] for i in my_list.readlines()]

   file_large = open("large_file.txt")
   save_file = open("output.txt", "w")

   for row in file_large:
split_row = row.split()
   if split_row[0] in file_list:
save_file.write(row)

   file_large.close()
   file_list.close()


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


Re: [Tutor] Find (list) strings in large textfile

2017-02-11 Thread Danny Yoo
Believe it or not, a change in two characters should make this even faster.  :)

Change the line:

file_list = [i[:-1] for i in my_list.readlines()]

to:

file_list = {i[:-1] for i in my_list.readlines()}


The change is to use a "set comprehension" instead of a "list
comprehension".  Sets allow membership checks in expected *constant*
time instead of *linear* time.  Try that, and compare the speed: you
should get a fairly good speedup.


See:

https://docs.python.org/3/tutorial/datastructures.html#sets

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


Re: [Tutor] Accessing an entry value input by the user

2017-02-11 Thread Alan Gauld via Tutor
On 11/02/17 18:59, Pooja Bhalode wrote:
> Hi Alan,
> 
> I had done what you suggested here, I also tried creating another file for
> that snipet of the code to see if that section works. The other file works,
> but I am not able to figure out why the original one doesn't work.

Too late at night for a detailed analysis but your code
should be restructured its ghetting very messy and hard
to see whats going on. More on that another time.
Meanwhile some immediate thoughts...

> from Tkinter import *
> import datetime
> import tkMessageBox
> from tkFileDialog import *
> from tkMessageBox import *

If you do this there's no point in importing tkmessagebox earlier.

> root = Tk()
> root.title("Design of Experiments with Parameter Estimation")
> root.geometry("1000x1000")
> 
> statusvar = StringVar()
> statusvar = "Status Bar"

You create the stringvar but then throw it waay by overwriting it with a
string.

Maybe you meant to do:

statusvar = StringVar()
statusvar.set("Status Bar")

???


> var1 = IntVar()
> var2 = IntVar()
> var3 = IntVar()
> var4 = IntVar()
> 
> varreac = IntVar()
> varint = IntVar()
> varpro = IntVar()
> 
> varconc = IntVar()
> vartemp = IntVar()
> entrynumberspeciesvar = IntVar()

You can only use a stringvar with an Entry because
the Entry only holds text, not integers. You will
need to do the conversions yourself when you set/get
the values.

> def DesignPoint():
> print "Inside Design Point"
> rootdesign=Tk()

You are still creating multiple roots, that is
really bad practice and almost sure to create
problems later. Define the function as:

def DesignPoint(root):...

and call it as

DesignPoint(root)

> rootdesign.title("Design Point Suggestions")
> rootdesign.geometry("700x400")
> frame1 = Frame(rootdesign)
> frame1.grid(row=0, column=0)
> 

If you want a second window you should be
using a Toplevel widget not Frame here.


> label1 = Label(frame1, text="1. Responses to include: ")
> label1.grid(row=0, column=0,sticky=W)
> 
> 
> Label(frame1, text = "Number of species:").grid(row=0, column = 1,
> sticky=W)
> entrynumberspecies = Entry(frame1, textvariable = entrynumberspeciesvar)
> entrynumberspecies.grid(row=0, column = 2, sticky=W)
> 
> # print entrynumberspeciesvar.get()
> checkreac = Checkbutton(frame1, text = "Reactant species", variable =
> varreac)
> checkreac.grid(row = 1, column = 1, sticky = W)
> checkreac.select()
> Checkbutton(frame1, text = "Intermediate species", variable =
> varint).grid(row = 2, column = 1, sticky = W)
> Checkbutton(frame1, text = "Product species", variable =
> varpro).grid(row = 3, column = 1, sticky = W)
> 
> def Default():
> print "Inside default"
> 
> var1.set(0)
> var2.set(0)
> var3.set(0)
> var4.set(1)

This function really should be defined outside
the DesignPoint one. It will be much easier to maintain
if you separate them out.

> Checkbutton(frame1, text = "Vertices", variable=var1, onvalue=1,
> offvalue=0).grid(row=1, column = 2, sticky=W)
> Checkbutton(frame1, text = "Edges", variable=var2).grid(row=2, column =
> 2, sticky=W)
> Checkbutton(frame1, text = "Faces", variable=var3).grid(row=3, column =
> 2, sticky=W)
> check = Checkbutton(frame1, text = "Center", variable=var4)
> 
> check.grid(row=4, column = 2, sticky=W)
> check.select()
> 
> Label(frame1, text="2. Variables to be adjusted:").grid(row=5,
> column=0,sticky=W)
> Checkbutton(frame1, text = "Concentration", variable=varconc,
> onvalue=1, offvalue=0).grid(row=5, column = 1, sticky=W)
> Checkbutton(frame1, text = "Temperature", variable=vartemp).grid(row=6,
> column = 1, sticky=W)
> 
> def InsertRange():
> print "Inside InsertRange"
> # entrynumberspeciesvar.set(2)
> print entrynumberspeciesvar.get()
> for i in range(entrynumberspeciesvar.get()):
> textvar = StringVar()
> print i
> textvar = "\t Conc"+str(i)

Again you have deleted your StringVar object by overwriting it.
You need to set the value with the set() method. OTOH you
never use the StringVar so maybe you just need to delete
that line.

> Label(frame1, text=textvar).grid(row=(9+i), column=0,sticky=W)
> conclowerentry = Entry(frame1)
> conclowerentry.grid(row= (9+i), column = 1, sticky = W)
> concupperentry = Entry(frame1)
> concupperentry.grid(row= (9+i), column = 2, sticky = W)
> 

Same goes here. You should have very good reasons to define event
handlers inside the functions that build your UIs. It usually just makes
the code more complex with no benefit.

> Label(frame1, text="3. Range of formulation:").grid(row=7,
> column=0,sticky=W)
> Button(frame1, text = "Insert Range", command = InsertRange()).grid(row
> = 7, column = 3, sticky=W)
> Label(frame1, text="Lower Limit").grid(row=7, column=1,sticky=W)
> Label(frame1, text="Upper 

Re: [Tutor] Python-list thread: int vs. float

2017-02-11 Thread Steven D'Aprano
On Sat, Feb 11, 2017 at 02:28:42PM -0600, boB Stepp wrote:

> Back in the main Python list thread, Marko Rauhamaa suggested
> (https://mail.python.org/pipermail/python-list/2017-February/719322.html):
> 
> "
> ...
> Haven't been following the discussion, but this should be simply:
> 
>ast.literal_eval("...")
> ...
> "
> 
> This looks like it may do the trick quite concisely:

Nope. Not even close. The problem is that you have to accept ints and 
floats, but reject anything else, and literal_eval does not do that.

py> import ast
py> ast.literal_eval('[1, {}, None, "s", 2.4j, ()]')
[1, {}, None, 's', 2.4j, ()]


literal_eval will parse and evaluate anything that looks like one of:

- int
- float
- string
- bool (True or False)
- None
- complex (e.g. -3.5+4.5j)
- tuple
- list
- dict
- set


so it does *far* more than what the OP requires.

[...]
> That statement about potentially changing with each Python release
> bothers me.  Should I be bothered?

No. In this case, you are parsing a string, and the ast module itself 
parses it to an Abstract Syntax Tree before evaluating literals, so it 
doesn't matter if the AST is different from one version to the next.

You should only care if you generated an AST in (say) Python 3.5, saved 
it in a data file, then read it back in to Python 3.6 and tried to 
evaluate it. That may not succeed.



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


Re: [Tutor] Python-list thread: int vs. float

2017-02-11 Thread Steven D'Aprano
On Sat, Feb 11, 2017 at 09:10:04AM -0800, Alex Kleider wrote:

> What your 's' represents seems quite different to 'mine.'
> There must be something else going on.
> ???

I think there's an easy explanation for that, which is that eryksun 
probably just created a variable "s" but didn't show the code for that.

Unfortunately copying and pasting Unicode characters from email to the 
Python interpreter may not always work, as that depends on how well at 
least four software components deal with Unicode:

- the email program
- the copy/paste clipboard manager
- the console/terminal
- the Python interpreter

The second last one is particularly problematic under Windows.


When clarity is more important than brevity, the best way to insert 
Unicode characters into a string is to use the '\N{name}' form:

s = '\N{TAMIL DIGIT ONE}\N{VAI DIGIT TWO}\N{ORIYA DIGIT THREE}'

Since that's pure ASCII, you can copy and paste it easily even in the 
most poorly-configured system.


> Also of interest (at least to me) was the 'magic' you demonstrated in 
> the print function parameter list; my efforts to figure it out:
> >>>word = "Hello"
> >>>print((c for c in word))
>  at 0xb71d125c>
> >>>print(*(c for c in word))
> H e l l o
> >>>print(*(c for c in word), sep='')
> Hello

Indeed: the leading * is just the systax for argument unpacking. If you 
have a sequence:

seq = [1, 2, 3, 4]

and unpack it:

print(*seq)

then what the print function sees is:

print(1, 2, 3, 4)


It works with any iterable, not just lists or tuples: also strings, 
generator expressions, and more.



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


Re: [Tutor] Python-list thread: int vs. float

2017-02-11 Thread boB Stepp
On Sat, Feb 11, 2017 at 7:08 PM, Steven D'Aprano  wrote:
> On Sat, Feb 11, 2017 at 02:28:42PM -0600, boB Stepp wrote:
>
>> Back in the main Python list thread, Marko Rauhamaa suggested
>> (https://mail.python.org/pipermail/python-list/2017-February/719322.html):
>>
>> "
>> ...
>> Haven't been following the discussion, but this should be simply:
>>
>>ast.literal_eval("...")
>> ...
>> "
>>
>> This looks like it may do the trick quite concisely:
>
> Nope. Not even close. The problem is that you have to accept ints and
> floats, but reject anything else, and literal_eval does not do that.
>
> py> import ast
> py> ast.literal_eval('[1, {}, None, "s", 2.4j, ()]')
> [1, {}, None, 's', 2.4j, ()]

My intent was to follow up with
type(ast.literal_eval(string_input_from_user)) and if that does not
come out 'int' or 'float', then it can be rejected as invalid input
from the user.  In your example type() would return a list, which
would be invalid input for the OP's case.  Of course this seems like
swatting a gnat with a sledge hammer, but it still seems that the
combination of checking the return of
type(ast.literal_eval(user_input)) does the job since everything that
is not float or int can be rejected as invalid input, and the float
case can get its special error message.

Or am I missing something?

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