[Tutor] find pickle and retrieve saved data

2015-08-02 Thread Quiles, Stephanie
 how do i go about being able to add a feature to search for individual entries 
that have been saved into that dictionary or else tell me that the name I 
entered is not found? 

Here is the code that i have so far…

import pickle
def main():
infile = open("emails.dat", "rb")
emails = pickle.load(infile)
infile.close()
name_search = input("Enter a name in the file for info: ")

for name in emails:

if name[0] == name_search:
print("This is the info: ", info)
return emails
else:
print("Entry not Found! Try again.")
main()


thanks for all the help and suggestions this is really helping me in trying to 
figure this out! 

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


Re: [Tutor] infix to postfix eval

2015-08-02 Thread Anish Tambe
On Sun, Aug 2, 2015 at 9:39 AM, Quiles, Stephanie
 wrote:
>
> hello again!
>
> I have to unify these methods so that i can enter an infix, convert it to a 
> postfix and then solve. Here are the methods

At the end of your code I added this -

inFixExpr = raw_input("Enter infix string : ")
postFixExpr = infixToPostfix(inFixExpr)
print("The postfix string is:  " + postFixExpr)
value = postfixEval(postFixExpr)
print("The final result is:  " + str(value))

And this gives me output -
$ python postfix.py
5 3 4 2 - ^ *
A B + C * D E - F G + * -
Enter infix string : ( 8 + 2 ) * ( 2 + 4 )
The postfix string is:  8 2 + 2 4 + *
The final result is:  60


> if token in "ABCDEFGHIJKLMNOPQRSTUVWXYZ" or token in "0123456789":

Instead of the above line, you can do this -
 if token in string.uppercase or token in string.digits:
Import string module first.

>>> import string
>>> string.uppercase
'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
>>> string.digits
'0123456789'
>>>

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


Re: [Tutor] scratching my head

2015-08-02 Thread Válas Péter
2015-08-02 23:44 GMT+02:00 Clayton Kirkwood :

>
>
> for dir_path, directories, files in os.walk(main_dir):
> for file in files:
> #print( " file = ", file)
> #   if( ("(\.jpg|\.png|\.avi|\.mp4)$") not in file.lower() ):
>
>
> I supppose you want to use regular expressions here and you are somehow
familiar with them but you forgot to tell Python to handle your string as
regex. This kind of expression must be matched against filenames instead of
using "in" operator.

In this case, https://docs.python.org/3/library/re.html and
https://docs.python.org/3/howto/regex.html are your friends.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] scratching my head

2015-08-02 Thread Laura Creighton
I think people are giving you sub-optimal advice.

Python has a module in the standard library for doing exactly what
you want to do -- match files with certain extensions.

See: https://docs.python.org/2/library/fnmatch.html

It's unix style file matching, but I am fairly certain this works
on windows also.  I don't have a windows machine to test and make sure.

Laura

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


Re: [Tutor] Windows "feature" I don't understand

2015-08-02 Thread Válas Péter
My "best practice" is to avoid Windows-generated directories and create my
own ones. :-)
They are linked and "pseudo-named" in a really messy way even if you use
English Windows, but the real extended horror begins at different languages
where Windows randomly uses English and translated names. Also, I usually
know better what I need than some of those guys in Redmond. I think
Users\Clayton should be the last point where you use the default structure,
but if it is your own computer, it's even better to leave the whole Users
directory for the playground of Windows and create your own documents
structure. Preferably on another device or partition than location of
operating system. (However, Windows itself allows you to relocate these
directories in the official structure.)

Also, it is wise to define this path at the beginning of your script in
case you want to use it elsewhere.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] Windows "feature" I don't understand

2015-08-02 Thread Clayton Kirkwood
In a former life, I played the part of a system manager in a number of Unix
environments, which I really liked. Now, I am stuck using Windows and don't
get into the innards much. I ran into a problem in my program, which we have
been discussing, which is windows-caused. I originally set my directory in
my code to /users/Clayton/Pictures by memory that that was the name of the
directory in windows. My code worked using the directory. I then noticed
that my "real" directory as listed by windows explorer was /users/Clayton/My
Pictures. I changed it in my code and nothing works. /users/Clayton/Pictures
doesn't show up in explorer even tho I've set to display hidden files,
system files, etc. I dropped down into dos and lo and behold, Picture exists
but there is no My Pictures. That explains why pictures worked, but I don't
understand the discrepancy for the differences, why My Pictures doesn't
work, etc. My Pictures is not a link in explorer.

Any shed light would be greatly appreciated.

TIA,

Clayton

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


Re: [Tutor] scratching my head

2015-08-02 Thread Clayton Kirkwood


> -Original Message-
> From: Tutor [mailto:tutor-bounces+crk=godblessthe...@python.org] On
> Behalf Of Steven D'Aprano
> Sent: Sunday, August 02, 2015 5:49 PM
> To: tutor@python.org
> Subject: Re: [Tutor] scratching my head
> 
> On Sun, Aug 02, 2015 at 02:44:15PM -0700, Clayton Kirkwood wrote:
> 
> > for dir_path, directories, files in os.walk(main_dir):
> > for file in files:
> > #print( " file = ", file)
> > #   if( ("(\.jpg|\.png|\.avi|\.mp4)$") not in file.lower() ):
> > #if(  (".jpg" or ".png" or ".avi" or ".mp4" )  not in
file.lower()
> 
> name, ext = os.path.splitext(filename)
> if ext.lower() in ('.jpg', '.png', '.avi', '.mp4'):
> ...
> 
> 
> > #del files[file]
> > #
> > #I get an error on int expected here. If I'm able to access by string,
> > why wouldn't I be able to #acess in the del?
> 
> What are you attempting to do here? files is a list of file names:
> 
> files = ['this.jpg', 'that.txt', 'other.pdf'] filename = 'that.txt'
> 
> What do you expect files['that.txt'] to do?
> 
> The problem has nothing to do with del, the problem is that you are trying
to
> access the 'that.txt'-th item of a list, and that is meaningless.


Well, I was expecting that the list entry would be deleted. In other parts
of my code I am using filenames as the index of lists: list[filenames] for
for loops and some ifs where it appears to work. I am able to look at
directories and the files in them by doing this. Check the rest of my
original code. I had one if that complained at the bottom of my code that
complained that the index was supposed to be an in not the list element
value. So I get that the index is supposed to be an int, and I think what is
happening in much of the code is the filename somehow becomes an int and
then the list accesses that way. It's very confusing. Basically, I was using
filenames as indexes into the list.


> 
> 
> > print( "looking at file  ", file, "  in
> > top_directory_file_list  ", top_directory_file_list )
> 
> What does this print? In particular, what does the last part,
> top_directory_file_list, print? Because the next error:
> 
> > if file in top_directory_file_list:
> > #error: arg of type int not iterable
> 
> is clear that it is an int.
> 
> > #yet it works for the for loops
> 
> I think you are confusing:
> 
> top_directory_file_list
> 
> directory_file_list


I don't know. If you look at the code that is going thru the directory
filename by filename the prints kick out filename and directories and the
list elements are addressed by "strings", the actual filenames.

What is happening in most of the code looks like what one would expect if
the lists could be indexed by words not ints. As a programmer, I would
expect lists to be addressed via a name or a number. It seems kind of like
dicktionaries. Am I mixing dictionaries and list?


Clayton
> 
> 
> ___
> 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] scratching my head

2015-08-02 Thread Clayton Kirkwood


> -Original Message-
> From: Tutor [mailto:tutor-bounces+crk=godblessthe...@python.org] On
> Behalf Of Cameron Simpson
> Sent: Sunday, August 02, 2015 6:03 PM
> To: tutor@python.org
> Subject: Re: [Tutor] scratching my head
> 
> On 02Aug2015 16:15, Clayton Kirkwood  wrote:
> >> Behalf Of Cameron Simpson
> >> Sent: Sunday, August 02, 2015 3:35 PM
> [...]
> >> Personally I'd be reaching for os.path.splitext. Untested example
below:
> >>
> >>   from os.path import splitext
> >>   
> >>   for dir_path, directories, files in os.walk(main_dir):
> >> for file in files:
> >>   prefix, ext = splitext(file)
> >>   if ext and ext[1:].lower() in ('jpg', 'png', 'avi', 'mp4'):
> >> 
> >>
> >> which I think is much easier to read.
> >>
> >> BTW, I'd be using the variable names "filename" and "filenames"
> >> instead of "file" and "files": in python 2 "file" is a builtin
> >> function (though long deprecated by "open()") and in any case I'd
> >> (personally) expect such a
> >name
> >> to be an _open_ file. As opposed to "filename", which is clearer.
> >
> >Thanks, that should also help a lot. Now time to look at splitext, and
> >the ext and ext[1:.
> 
> The "[1:]" is because "ext" will include the dot.

Yeah, after looking it up, it became clear, but thanks!

> 
> >I appreciate your comments also about the variable names.
> >Any comments on the problems lower in the file?
> 
> Maybe you'd better reraise these problems again explicitly.

Point taken.

> 
> Cheers,
> Cameron Simpson 
> ___
> 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] scratching my head

2015-08-02 Thread Cameron Simpson

On 02Aug2015 16:15, Clayton Kirkwood  wrote:

Behalf Of Cameron Simpson
Sent: Sunday, August 02, 2015 3:35 PM

[...]

Personally I'd be reaching for os.path.splitext. Untested example below:

  from os.path import splitext
  
  for dir_path, directories, files in os.walk(main_dir):
for file in files:
  prefix, ext = splitext(file)
  if ext and ext[1:].lower() in ('jpg', 'png', 'avi', 'mp4'):


which I think is much easier to read.

BTW, I'd be using the variable names "filename" and "filenames" instead of
"file" and "files": in python 2 "file" is a builtin function (though long
deprecated by "open()") and in any case I'd (personally) expect such a

name

to be an _open_ file. As opposed to "filename", which is clearer.


Thanks, that should also help a lot. Now time to look at splitext, and the
ext and ext[1:.


The "[1:]" is because "ext" will include the dot.


I appreciate your comments also about the variable names.
Any comments on the problems lower in the file?


Maybe you'd better reraise these problems again explicitly.

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


Re: [Tutor] scratching my head

2015-08-02 Thread Steven D'Aprano
On Sun, Aug 02, 2015 at 11:46:31PM +0100, Alan Gauld wrote:
> On 02/08/15 23:01, Alan Gauld wrote:
> 
> >found = False
> >for s in (".jpg",".png",".avi",".mp4"):
> > found = test or (s in file.lower())
> 
> Oops, that should be:
> 
> found = found or (s in file.lower())

extensions = (".jpg",".png",".avi",".mp4")
found = any(s in filename.lower() for s in extensions)

but that's still wrong, because it will find files like

History.of.Avis.PA.pdf

as if it were an AVI file. Instead, use os.path.splitext.



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


Re: [Tutor] scratching my head

2015-08-02 Thread Steven D'Aprano
On Sun, Aug 02, 2015 at 02:44:15PM -0700, Clayton Kirkwood wrote:

> for dir_path, directories, files in os.walk(main_dir):
> for file in files:
> #print( " file = ", file)
> #   if( ("(\.jpg|\.png|\.avi|\.mp4)$") not in file.lower() ):
> #if(  (".jpg" or ".png" or ".avi" or ".mp4" )  not in file.lower()

name, ext = os.path.splitext(filename)
if ext.lower() in ('.jpg', '.png', '.avi', '.mp4'):
...


> #del files[file]
> #
> #I get an error on int expected here. If I'm able to access by string, why
> wouldn't I be able to
> #acess in the del?

What are you attempting to do here? files is a list of file names:

files = ['this.jpg', 'that.txt', 'other.pdf']
filename = 'that.txt'

What do you expect files['that.txt'] to do?

The problem has nothing to do with del, the problem is that you are 
trying to access the 'that.txt'-th item of a list, and that is 
meaningless.


> print( "looking at file  ", file, "  in top_directory_file_list  ",
> top_directory_file_list )

What does this print? In particular, what does the last part, 
top_directory_file_list, print? Because the next error:

> if file in top_directory_file_list:
> #error: arg of type int not iterable

is clear that it is an int.

> #yet it works for the for loops

I think you are confusing:

top_directory_file_list

directory_file_list


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


Re: [Tutor] email validation

2015-08-02 Thread Quiles, Stephanie
So i took your advice and i am much closer. however, when i type in an invalid 
address it loops back to the first prompt and asks you to enter your name: I 
want it to ask you to re-enter your email address instead how would i go about 
this?

Here is the corrected code : 

import pickle


def main():
cont = True
emails = open_existing_file()
print(emails)

# Get data...
while cont:
name = input("Enter your name: ")
email1 = input("Enter your email address: ")
if not is_good_address(email1): continue
email2 = input("Enter an alternate email address: ")
if not is_good_address(email2): continue
phone = input("Enter your phone number: ")
contactlist = [email1, email2, phone]
emails[name] = contactlist
c = input("Enter another? [y]/n: ")
if c == 'n' or c == 'N':
cont = False

# Save data...
outfile = open("emails.dat", "wb")
pickle.dump(emails, outfile)
outfile.close
print("Your data has been saved to emails.dat")


def is_good_address(addr):
if '@' not in addr or '.' not in addr:
print('email needs @ and . at the same time')
return False
else:
return True


def open_existing_file():
# returns an empty dictionary or one that has data from a file
emails = {}
# Load the dictionary
try:
infile = open("emails.dat", "rb")
emails = pickle.load(infile)
infile.close()
except:
print("No file to open. Starting with no data.")
return emails


main()


Thanks 

Stephanie 


> On Aug 2, 2015, at 10:12 AM, Alan Gauld  wrote:
> 
> On 02/08/15 09:31, Alan Gauld wrote:
> 
>> them outside the main block and use them in your tests. In that case you
>> only need one function which I'd call something like test_email()
> 
> Ahem. Or you could call it is_good_address() of course! Oops!
> 
>> def is_good_address(addr):
>>  if '@' not in addr or '.' not in addr:
>>  print('email needs @ and . at the same time')
>>  return False
>>  else: return True
> 
> -- 
> 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

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


[Tutor] Writing back to same CSV in the next column

2015-08-02 Thread Nym City via Tutor
Hello,
Below is my program where I am reading a list of IPs from a CSV file and 
running it through the socket module. The result of the computation is stored 
in a variable named ResolvedAddresses. However, there are some that are not 
resolved and for those there is an exception.
The task that I am trying to complete now is taking the output of the 
ResolvedAddresses and the content of the exception and write is back out to the 
same CSV file where the data is originally imported from. Ideally, I would like 
this new information to be in the column B and match with column A.
Thank you in advance. And please let me know if what I am trying to accomplish 
is not clear and I'll try to explain it better.

Here is the code: https://bpaste.net/show/01a412f72fa1

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


Re: [Tutor] email validation

2015-08-02 Thread Alan Gauld

On 02/08/15 23:54, Quiles, Stephanie wrote:

So i took your advice and i am much closer. however, when i type in an invalid 
address it loops back to the first prompt and asks you to enter your name: I 
want it to ask you to re-enter your email address instead how would i go about 
this?


Just move the line that asks for the name above the while loop.
Then it will only ask for the name once.

If you want to cater for multiple users each with multiple addresses then
you will need two nested loops.

while True
user = input(...name...):
collect other user data here
while True:
   get/check addresses here


 while cont:
 name = input("Enter your name: ")
 email1 = input("Enter your email address: ")
 if not is_good_address(email1): continue
 email2 = input("Enter an alternate email address: ")
 if not is_good_address(email2): continue
 phone = input("Enter your phone number: ")
 contactlist = [email1, email2, phone]
 emails[name] = contactlist
 c = input("Enter another? [y]/n: ")
 if c == 'n' or c == 'N':
 cont = False

 # Save data...
 outfile = open("emails.dat", "wb")
 pickle.dump(emails, outfile)
 outfile.close
 print("Your data has been saved to emails.dat")

def is_good_address(addr):
 if '@' not in addr or '.' not in addr:
 print('email needs @ and . at the same time')
 return False
 else:
 return True

def open_existing_file():
 # returns an empty dictionary or one that has data from a file
 emails = {}
 # Load the dictionary
 try:
 infile = open("emails.dat", "rb")
 emails = pickle.load(infile)
 infile.close()
 except:
 print("No file to open. Starting with no data.")
 return emails


--
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] scratching my head

2015-08-02 Thread Clayton Kirkwood


> -Original Message-
> From: Tutor [mailto:tutor-bounces+crk=godblessthe...@python.org] On
> Behalf Of Cameron Simpson
> Sent: Sunday, August 02, 2015 3:35 PM
> To: tutor@python.org
> Subject: Re: [Tutor] scratching my head
> 
> On 02Aug2015 23:01, ALAN GAULD  wrote:
> >On 02/08/15 22:44, Clayton Kirkwood wrote:
> >>for dir_path, directories, files in os.walk(main_dir):
> >> for file in files:
> >>#print( " file = ", file)
> >>#   if( ("(\.jpg|\.png|\.avi|\.mp4)$") not in file.lower() ):
> >
> >Python sees that as a single string. That string is not in your filename.
> >
> >>#if(  (".jpg" or ".png" or ".avi" or ".mp4" )  not in
file.lower()
> [...]
> >But you could use a loop:
> >
> >found = False
> >for s in (".jpg",".png",".avi",".mp4"):
> >found = test or (s in file.lower()) if not found: ...
> >
> >> if(  ".jpg" not in file.lower() and
> >>  ".png" not in file.lower() and
> >>  ".avi" not in file.lower() and
> >>  ".mp4" not in file.lower() ):
> >
> >Whether that's any better than your combined test is a moot point.
> 
> Alan has commented extensively on the logic/implementation errors. I have
> a suggestion.
> 
> Personally I'd be reaching for os.path.splitext. Untested example below:
> 
>   from os.path import splitext
>   
>   for dir_path, directories, files in os.walk(main_dir):
> for file in files:
>   prefix, ext = splitext(file)
>   if ext and ext[1:].lower() in ('jpg', 'png', 'avi', 'mp4'):
> 
> 
> which I think is much easier to read.
> 
> BTW, I'd be using the variable names "filename" and "filenames" instead of
> "file" and "files": in python 2 "file" is a builtin function (though long
> deprecated by "open()") and in any case I'd (personally) expect such a
name
> to be an _open_ file. As opposed to "filename", which is clearer.


Thanks, that should also help a lot. Now time to look at splitext, and the
ext and ext[1:. I appreciate your comments also about the variable names.
Any comments on the problems lower in the file?

Clayton


> 
> Cheers,
> Cameron Simpson 
> 
> Rudin's Law:
>   If there is a wrong way to do something, most people will do it every
time.
> Rudin's Second Law:
>   In a crisis that forces a choice to be made among alternative courses of
>   action, people tend to choose the worst possible  course.
> ___
> 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] scratching my head

2015-08-02 Thread Alan Gauld

On 02/08/15 23:01, Alan Gauld wrote:


found = False
for s in (".jpg",".png",".avi",".mp4"):
 found = test or (s in file.lower())


Oops, that should be:

found = found or (s in file.lower())

Sorry, 'test' was my first  choice of name
but I changed it to found later.
But not everywhere :-(


--
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] scratching my head

2015-08-02 Thread Cameron Simpson

On 02Aug2015 23:01, ALAN GAULD  wrote:

On 02/08/15 22:44, Clayton Kirkwood wrote:

for dir_path, directories, files in os.walk(main_dir):
for file in files:
#print( " file = ", file)
#   if( ("(\.jpg|\.png|\.avi|\.mp4)$") not in file.lower() ):


Python sees that as a single string. That string is not in your filename.


#if(  (".jpg" or ".png" or ".avi" or ".mp4" )  not in file.lower()

[...]

But you could use a loop:

found = False
for s in (".jpg",".png",".avi",".mp4"):
   found = test or (s in file.lower())
if not found: ...


if(  ".jpg" not in file.lower() and
 ".png" not in file.lower() and
 ".avi" not in file.lower() and
 ".mp4" not in file.lower() ):


Whether that's any better than your combined test is a moot point.


Alan has commented extensively on the logic/implementation errors. I have a 
suggestion.


Personally I'd be reaching for os.path.splitext. Untested example below:

 from os.path import splitext
 
 for dir_path, directories, files in os.walk(main_dir):
   for file in files:
 prefix, ext = splitext(file)
 if ext and ext[1:].lower() in ('jpg', 'png', 'avi', 'mp4'):
   

which I think is much easier to read.

BTW, I'd be using the variable names "filename" and "filenames" instead of 
"file" and "files": in python 2 "file" is a builtin function (though long 
deprecated by "open()") and in any case I'd (personally) expect such a name to 
be an _open_ file. As opposed to "filename", which is clearer.


Cheers,
Cameron Simpson 

Rudin's Law:
 If there is a wrong way to do something, most people will do it every time.
Rudin's Second Law:
 In a crisis that forces a choice to be made among alternative courses of
 action, people tend to choose the worst possible  course.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] scratching my head

2015-08-02 Thread Clayton Kirkwood


> -Original Message-
> From: Tutor [mailto:tutor-bounces+crk=godblessthe...@python.org] On
> Behalf Of Alan Gauld
> Sent: Sunday, August 02, 2015 3:01 PM
> To: tutor@python.org
> Subject: Re: [Tutor] scratching my head
> 
> On 02/08/15 22:44, Clayton Kirkwood wrote:
> 
> > for dir_path, directories, files in os.walk(main_dir):
> >  for file in files:
> > #print( " file = ", file)
> > #   if( ("(\.jpg|\.png|\.avi|\.mp4)$") not in file.lower() ):
> 
> Python sees that as a single string. That string is not in your filename.
> 
> > #if(  (".jpg" or ".png" or ".avi" or ".mp4" )  not in
file.lower()
> 
> Python sees that as a boolean expression so will try to work it out as a
> True/False value. Since a non empty string is considered True and the
first
> True expression makes an OR opeation True overall it returns ".jpg" and
tests
> if it is not in the filename.
> 
> > #except by the drudgery below. I should be able to just have a list,
> > maybe from a file, that lists all
> 
> You might think so but that's not how 'in' works.
> 
> But you could use a loop:
> 
> found = False
> for s in (".jpg",".png",".avi",".mp4"):
>  found = test or (s in file.lower()) if not found: ...


The for is much better and it's able to get input from a file. I would think
Python more sensible if something like my commented one would work. That
would make more sense to me.

Thanks


> 
> >  if(  ".jpg" not in file.lower() and
> >   ".png" not in file.lower() and
> >   ".avi" not in file.lower() and
> >   ".mp4" not in file.lower() ):
> 
> Whether that's any better than your combined test is a moot point.
> 
> 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

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


Re: [Tutor] scratching my head

2015-08-02 Thread Alan Gauld

On 02/08/15 22:44, Clayton Kirkwood wrote:


for dir_path, directories, files in os.walk(main_dir):
 for file in files:
#print( " file = ", file)
#   if( ("(\.jpg|\.png|\.avi|\.mp4)$") not in file.lower() ):


Python sees that as a single string. That string is not in your filename.


#if(  (".jpg" or ".png" or ".avi" or ".mp4" )  not in file.lower()


Python sees that as a boolean expression so will try to
work it out as a True/False value. Since a non empty
string is considered True and the first True expression
makes an OR opeation True overall it returns ".jpg" and
tests if it is not in the filename.


#except by the drudgery below. I should be able to just have a list, maybe
from a file, that lists all


You might think so but that's not how 'in' works.

But you could use a loop:

found = False
for s in (".jpg",".png",".avi",".mp4"):
found = test or (s in file.lower())
if not found: ...


 if(  ".jpg" not in file.lower() and
  ".png" not in file.lower() and
  ".avi" not in file.lower() and
  ".mp4" not in file.lower() ):


Whether that's any better than your combined test is a moot point.

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


[Tutor] scratching my head

2015-08-02 Thread Clayton Kirkwood
Hey, been awhile, but I ran into os.walk and it fit what I needed to do for
an issue I've had for a long time: I have tons of pictures in my top
directory of pictures which are duplicated into properly named
subdirectories. Please see issues above my questions with large gaps below. 
TIA,
Clayton


#Program to find duplicated pictures in my picture directory tree
#Presumably, if the file exists in a subdirectory I can remove if from the
parent picture directory
#
#Clayton Kirkwood
#01Aug15

import os
from os.path import join,  getsize

main_dir = "/users/Clayton/Pictures"
directory_file_list = {}
duplicate_files = 0
top_directory_file_list = 0

for dir_path, directories, files in os.walk(main_dir):
for file in files:
#print( " file = ", file)
#   if( ("(\.jpg|\.png|\.avi|\.mp4)$") not in file.lower() ):
#if(  (".jpg" or ".png" or ".avi" or ".mp4" )  not in file.lower()
):
#
#why don't these work?, especially the last one. How am I to capture all
camera and video types
#except by the drudgery below. I should be able to just have a list, maybe
from a file, that lists all
#off the types and do something like if master_list not in file.lower()





if(  ".jpg" not in file.lower() and
 ".png" not in file.lower() and
 ".avi" not in file.lower() and
 ".mp4" not in file.lower() ):

print( "file ", file, "doesn't contain .jpg or .png or .avi or
.mp4" )
#del files[file]
#
#I get an error on int expected here. If I'm able to access by string, why
wouldn't I be able to
#acess in the del?





directory_file_list[dir_path] = files   #this is a list
#print(dir_path, directory_file_list[dir_path])
#print( main_dir )
for directory_path in directory_file_list.keys():
if( directory_path == main_dir ):
top_directory_file_list = directory_file_list[directory_path]
continue
#print( directory_path, ":", directory_file_list[directory_path])
file_list = directory_file_list[directory_path]
#print(file_list)
for file in file_list:
#pass
print( "looking at file  ", file, "  in top_directory_file_list  ",
top_directory_file_list )
if file in top_directory_file_list:
#error: arg of type int not iterable
#yet it works for the for loops





print( "file ", file, " found in both directory_path ",
directory_path, " and ", main_dir)
duplicate_files =+ 1
pass
break


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


Re: [Tutor] OT: Test to see if ibisMail app is truly sending in plain text

2015-08-02 Thread boB Stepp


On 2 Aug 2015 Oscar Benjamin wrote:

> Have you tried using the Gmail app?

Yes.  That is my normal mail app.

> I'm using the Gmail app here on my phone. I've just looked at your message,
> hit reply-all and then "respond inline". Then I can see/edit the
> attribution line and your message. I've not had complaints with using the
> list this way (perhaps I'm inviting them now though!)

That is how it works on my Nexus 5 phone, though I have not attempted to send 
an email to this list yet from it.  However, on my iPad, this functionality is 
not present in the Gmail App.  Why it would not be beats me, but unless there 
is a hidden setting or gesture I have missed, both by futzing around my actual 
iPad as well as searching the 'Net, then it is not available.
--
boB
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] email validation

2015-08-02 Thread Alan Gauld

On 02/08/15 09:31, Alan Gauld wrote:


them outside the main block and use them in your tests. In that case you
only need one function which I'd call something like test_email()


Ahem. Or you could call it is_good_address() of course! Oops!


def is_good_address(addr):
  if '@' not in addr or '.' not in addr:
  print('email needs @ and . at the same time')
  return False
  else: return True


--
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] String Attribute

2015-08-02 Thread Alan Gauld

On 02/08/15 10:15, Ltc Hotspot wrote:

Question1: Why did the following strip function fail: line2 =
line.strip (',')


What makes you think it failed?
I see no error messages below.


Question2: How do I code a vertical column output


See below.


Revised code:
fname = raw_input("Enter file name: ")
if len(fname) < 1 : fname = "mbox-short.txt"
fh = open(fname)
count = 0
addresses =[]
for line in fh:
 if line.startswith('From'):


You are still not checking for 'From ' - with a space. Thats why you still
get 54 instead of 27.


 line2 = line.strip ()
 line3 = line2.split()
 line4 = line3[1]
 addresses.append(line4)
 count = count + 1
print addresses


To get a vertical printout try this:

print '\n'.join(addresses)

Which converts the list into a string with a newline between each element.

Alternatively do it the manual way:

for addr in addresses: print addr


--
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] String Attribute

2015-08-02 Thread Ltc Hotspot
Hi Alan,

Question1: Why did the following strip function fail: line2 =
line.strip (',')
View instructions for 'str.strip([*chars*])¶
'
which is available at
https://docs.pythonorg/2.7/library/stdtypes.html?highlight=strip#str.strip

Question2: How do I code a vertical column output

Revised code:
fname = raw_input("Enter file name: ")
if len(fname) < 1 : fname = "mbox-short.txt"
fh = open(fname)
count = 0
addresses =[]
for line in fh:
if line.startswith('From'):
line2 = line.strip ()
line3 = line2.split()
line4 = line3[1]
addresses.append(line4)
count = count + 1
print addresses
print "There were", count, "lines in the file with From as the first word"



Produced output:
['stephen.marqu...@uct.ac.za', 'stephen.marqu...@uct.ac.za', '
lo...@media.berkeley.edu', 'lo...@media.berkeley.edu', 'zq...@umich.edu', '
zq...@umich.edu', 'rjl...@iupui.edu', 'rjl...@iupui.edu', 'zq...@umich.edu',
'zq...@umich.edu', 'rjl...@iupui.edu', 'rjl...@iupui.edu', 'c...@iupui.edu',
'c...@iupui.edu', 'c...@iupui.edu', 'c...@iupui.edu', 'gsil...@umich.edu', '
gsil...@umich.edu', 'gsil...@umich.edu', 'gsil...@umich.edu', '
zq...@umich.edu', 'zq...@umich.edu', 'gsil...@umich.edu', 'gsil...@umich.edu',
'wagne...@iupui.edu', 'wagne...@iupui.edu', 'zq...@umich.edu', '
zq...@umich.edu', 'antra...@caret.cam.ac.uk', 'antra...@caret.cam.ac.uk', '
gopal.ramasammyc...@gmail.com', 'gopal.ramasammyc...@gmail.com', '
david.horw...@uct.ac.za', 'david.horw...@uct.ac.za', '
david.horw...@uct.ac.za', 'david.horw...@uct.ac.za', '
david.horw...@uct.ac.za', 'david.horw...@uct.ac.za', '
david.horw...@uct.ac.za', 'david.horw...@uct.ac.za', '
stephen.marqu...@uct.ac.za', 'stephen.marqu...@uct.ac.za', '
lo...@media.berkeley.edu', 'lo...@media.berkeley.edu', '
lo...@media.berkeley.edu', 'lo...@media.berkeley.edu', '
r...@media.berkeley.edu', 'r...@media.berkeley.edu', 'c...@iupui.edu', '
c...@iupui.edu', 'c...@iupui.edu', 'c...@iupui.edu', 'c...@iupui.edu', '
c...@iupui.edu'] ← Mismatch
There were 54 lines in the file with From as the first word


Desired output:
stephen.marqu...@uct.ac.za
lo...@media.berkeley.edu
zq...@umich.edu
rjl...@iupui.edu
zq...@umich.edu
rjl...@iupui.edu
c...@iupui.edu
c...@iupui.edu
gsil...@umich.edu
gsil...@umich.edu
zq...@umich.edu
gsil...@umich.edu
wagne...@iupui.edu
zq...@umich.edu
antra...@caret.cam.ac.uk
gopal.ramasammyc...@gmail.com
david.horw...@uct.ac.za
david.horw...@uct.ac.za
david.horw...@uct.ac.za
david.horw...@uct.ac.za
stephen.marqu...@uct.ac.za
lo...@media.berkeley.edu
lo...@media.berkeley.edu
r...@media.berkeley.edu
c...@iupui.edu
c...@iupui.edu
c...@iupui.edu
There were 27 lines in the file with From as the first word

Regards,
Hal







On Sun, Aug 2, 2015 at 1:18 AM, Alan Gauld 
wrote:

> On 02/08/15 02:20, Ltc Hotspot wrote:
>
>> Hi Alan,
>>
>> I made a mistake and incorrectly assumed that differences between 54 lines
>> of output and 27 lines of output is the result of removing duplicate email
>> addresses,
>>
>> Apparently, this is not the case and I was wrong :(
>> The solution to the problem is in the  desired line output:
>>
>> stephen.marqu...@uct.ac.za
>> lo...@media.berkeley.edu
>> zq...@umich.edu
>> rjl...@iupui.edu
>> zq...@umich.edu
>> rjl...@iupui.edu
>>
> ...
>
> OK, Only a couple of changes should see to that.
>
> Latest revised code:
>> fname = raw_input("Enter file name: ")
>> if len(fname) < 1 : fname = "mbox-short.txt"
>> fh = open(fname)
>> count = 0
>> addresses = set()
>>
>
> change this to use a list
>
> addresses = []
>
> for line in fh:
>>  if line.startswith('From'):
>>  line2 = line.strip()
>>  line3 = line2.split()
>>  line4 = line3[1]
>>  addresses.add(line4)
>>
>
> and change this to use the list append() method
>
> addresses.append(line4)
>
>  count = count + 1
>> print addresses
>> print "There were", count, "lines in the file with From as the first word"
>>
>
> I'm not quite sure where the 54/27 divergence comes from except that
> I noticed Emille mention that there were lines beginning 'From:'
> too. If that's the case then follow his advice and change the if
> test to only check for 'From ' (with the space).
>
> That should be all you need.
>
>
> --
> 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
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] OT: Test to see if ibisMail app is truly sending in plain text

2015-08-02 Thread Oscar Benjamin
On 1 Aug 2015 16:28, "boB Stepp"  wrote:
>
> I apologize for the noise, but I felt it better to get this question
answered definitively prior to posting questions from my iPad.
>
> I am on a brief vacation and only brought my iPad.  I have been having a
devil of a time searching the Internet for an iPad app that will truly send
and display in plain text emails.  If someone would tell me if I have been
successful or not, I would be very appreciative!  If successful, Python
questions will soon follow.
>

Have you tried using the Gmail app?

I'm using the Gmail app here on my phone. I've just looked at your message,
hit reply-all and then "respond inline". Then I can see/edit the
attribution line and your message. I've not had complaints with using the
list this way (perhaps I'm inviting them now though!)
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] email validation

2015-08-02 Thread Alan Gauld

On 02/08/15 02:55, Quiles, Stephanie wrote:

On Aug 1, 2015, at 5:17 PM, Danny Yoo  wrote:
Thank you, the program is now working but when the email is not entered

>> correctly it doesn’t make me go back and re-enter,
>> it spits out an error code but then moves on to the next field .


Here is the code:

import pickle


def main():
 cont = True
 emails = open_existing_file()
 print(emails)

 # Get data...
 while cont:
 name = input("Enter your name :")
 email1 = input("Enter your email address :")
 if '@' not in email1 or '.' not in email1:
 print('email needs @ and . at the same time')
 cont = False


Instead of setting cont here - which will not stop the loop
from continuing (the while only checks the condition at the
start of each iteration) you should use continue. continue
jumps straight back to the top of the loop for another
iteration. I thnk that is what you want.

...

 c = input("Enter another? [y]/n :")
 if c == 'n' or c == 'N':
 cont = False

 def email1():
 if '@' not in email1 or '.' not in email1:
 print('email needs @ and . at the same time')

 def email2():
 if '@' not in email2 or '.' not in email2:
 print('email needs @ and . at the same time')
 # Save data...


These are no longer being used. instead you create variables of the same 
name which these then replace with functions. That is a recipe for 
confusion. You should remove these functions. Either that or move
them outside the main block and use them in your tests. In that case you 
only need one function which I'd call something like test_email()


def is_good_address(addr):
 if '@' not in addr or '.' not in addr:
 print('email needs @ and . at the same time')
 return False
 else: return True

You can then use it like

if not is_good_address(email2): continue

--
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] String Attribute

2015-08-02 Thread Alan Gauld

On 02/08/15 02:20, Ltc Hotspot wrote:

Hi Alan,

I made a mistake and incorrectly assumed that differences between 54 lines
of output and 27 lines of output is the result of removing duplicate email
addresses,

Apparently, this is not the case and I was wrong :(
The solution to the problem is in the  desired line output:

stephen.marqu...@uct.ac.za
lo...@media.berkeley.edu
zq...@umich.edu
rjl...@iupui.edu
zq...@umich.edu
rjl...@iupui.edu

...

OK, Only a couple of changes should see to that.


Latest revised code:
fname = raw_input("Enter file name: ")
if len(fname) < 1 : fname = "mbox-short.txt"
fh = open(fname)
count = 0
addresses = set()


change this to use a list

addresses = []


for line in fh:
 if line.startswith('From'):
 line2 = line.strip()
 line3 = line2.split()
 line4 = line3[1]
 addresses.add(line4)


and change this to use the list append() method

addresses.append(line4)


 count = count + 1
print addresses
print "There were", count, "lines in the file with From as the first word"


I'm not quite sure where the 54/27 divergence comes from except that
I noticed Emille mention that there were lines beginning 'From:'
too. If that's the case then follow his advice and change the if
test to only check for 'From ' (with the space).

That should be all you need.

--
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] FETCH URLs FROM WEBSITE

2015-08-02 Thread Alan Gauld

On 02/08/15 08:30, Gaurav Lathwal wrote:


& Both of you know a lot about all this, how do I go about doing that ? I
mean, how do I learn that much ?


I'm no expert but I've been using the web and creating web pages
since 1994 and you just learn stuff as you go. So sadly I can't
direct you to any definitive place where you can learn all you
need.

Having said that, I'm sure there are books and web sites that
will help, its just that I don't know them because I've
learned about the web incrementally as it grew. The only
paper book I use is the, now quite old, "Dynamic HTML - The
Definitive Guide" by Danny Goodman.

If I do need reference material I tend to go to the W3 master
web site since that's where the standards are kept and a lot
of tutorial material exists there. But much of modern web
application design (MEAN stack, JQuery, Ajax, Restful APIs etc)
is not about creating new standards as much as using the old
standards in clever ways.

Those new technologies (especially JQuery and Angular) make
web scraping much more difficult than it was previously
because the HTML is changing dynamically as you use the page.
Whole  sections may appear or disappear as you watch.

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


[Tutor] infix to postfix eval

2015-08-02 Thread Quiles, Stephanie
hello again!

I have to unify these methods so that i can enter an infix, convert it to a 
postfix and then solve. Here are the methods

method #1 is :


class Stack:
def __init__(self):
self.items = []

def isEmpty(self):
return self.items == []

def push(self, item):
self.items.insert(0,item)

def pop(self):
return self.items.pop(0)

def peek(self):
return self.items[0]

def size(self):
return len(self.items)


def infixToPostfix(infixexpr):
prec = {}
prec["^"] = 4
prec["*"] = 3
prec["/"] = 3
prec["+"] = 2
prec["-"] = 2
prec["("] = 1
opStack = Stack()
postfixList = []
tokenList = infixexpr.split()

for token in tokenList:
if token in "ABCDEFGHIJKLMNOPQRSTUVWXYZ" or token in "0123456789":
postfixList.append(token)
elif token == '(':
opStack.push(token)
elif token == ')':
topToken = opStack.pop()
while topToken != '(':
postfixList.append(topToken)
topToken = opStack.pop()
else:
while (not opStack.isEmpty()) and \
   (prec[opStack.peek()] >= prec[token]):
  postfixList.append(opStack.pop())
opStack.push(token)

while not opStack.isEmpty():
postfixList.append(opStack.pop())
return " ".join(postfixList)

print(infixToPostfix("5 * 3 ^ ( 4 - 2 )"))
print(infixToPostfix("( A + B ) * C - ( D - E ) * ( F + G )”))


method #2 is :

def postfixEval(postfixExpr):
operandStack = Stack()

tokenList = postfixExpr.split()

for token in tokenList:
if token in "0123456789":
operandStack.push(int(token))
else:
operand2 = operandStack.pop()
operand1 = operandStack.pop()
result = doMath(token,operand1,operand2)
operandStack.push(result)

return operandStack.pop()

def doMath(op, op1, op2):
if op == "^":
return op1 ** op2
if op == "*":
return op1 * op2
elif op == "/":
return op1 / op2
elif op == "+":
return op1 + op2
else:
return op1 - op2

basically i have to make a main function and somehow unify these two so that 
user can input an infix, then convert and print the postfix and then solve and 
print the final calculation. Here is the assignment as written by the 
instructor:

Try to do program #3 from P.144. We began this in class. Here’s what you need 
to do. We will be using Listings 3.7 and 3.8. First make sure that you can get 
Listing 3.7 to work. Just test some strings. Note that the code in the text 
expects the input to be “strings” of letters, each character separated by a 
space, and uses the “uppercase” statement in its definition. Second make sure 
that you can get Listing 3.8 to work. Just test some strings. This one you will 
test with digits. Third, now what you’ll need to do to answer program #3 is to 
get Listing 3.7 to handle digits rather than letters. This should not require a 
great deal of change to the code. Look at how Listing 3.8 handles the digits 
and see if you can duplicate that. Test some simple examples (limit the values 
from 0 – 9) with each character (token) separated by a space. For example, if 
we received the input of “3 + 4 * 2”, we would output 3 4 2 * +. (NOTE THE 
SPACES.) Fourth, once you have this working, you will simply feed this result 
to Listing 3.8 and the evaluated result should be printed. For example, if we 
received the input of “3 + 4 * 2”, we would output 3 4 2 * + and also output 
the value of 11.

Below is a sample of what you could show. Keep it simple.


print ("This program will accept an infix expression,")
print ("convert to postfix, and evaluate the result.")
print ("No input validation will be performed.")
print ("Please enter the infix expression correctly, as follows:")
print ("Enter only numbers 0-9")
print ("Separate each character with a space")
print ("You can use the following operators: ( ) + - * / ")
print ("For example: ( 8 + 2 ) * ( 2 + 4 )")

Here’s how a sample run would look.

This program will accept an infix expression,
convert to postfix, and evaluate the result.
No input validation will be performed.
Please enter the infix expression correctly, as follows:
Enter only numbers 0-9
Separate each character with a space
You can use the following operators: ( ) + - * /
For example: ( 8 + 2 ) * ( 2 + 4 )

Enter infix string: ( 8 + 2 ) * ( 2 + 4 )
The postfix string is:  8 2 + 2 4 + *
The final result is:  60

Thanks!

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


Re: [Tutor] email validation

2015-08-02 Thread Quiles, Stephanie

> On Aug 1, 2015, at 5:17 PM, Danny Yoo  wrote:
> Thank you, the program is now working but when the email is not entered 
> correctly it doesn’t make me go back and re-enter, it spits out an error code 
> but then moves on to the next field . 

Here is the code: 

import pickle


def main():
cont = True
emails = open_existing_file()
print(emails)

# Get data...
while cont:
name = input("Enter your name :")
email1 = input("Enter your email address :")
if '@' not in email1 or '.' not in email1:
print('email needs @ and . at the same time')
cont = False
email2 = input("Enter alternate email address :")
if '@' not in email2 or '.' not in email2:
print('email needs @ and . at the same time')
cont = False
phone = input("Enter your phone number :")
contactlist = [email1, email2, phone]
emails[name] = contactlist
c = input("Enter another? [y]/n :")
if c == 'n' or c == 'N':
cont = False

def email1():
if '@' not in email1 or '.' not in email1:
print('email needs @ and . at the same time')

def email2():
if '@' not in email2 or '.' not in email2:
print('email needs @ and . at the same time')
# Save data...
outfile = open("emails.dat", "wb")
pickle.dump(emails, outfile)
outfile.close
print("Your data has been saved to emails.dat")


def open_existing_file():
# returns an empty dictionary or one that has data from a file
emails = {}
# Load the dictionary
try:
infile = open("emails.dat", "rb")
emails = pickle.load(infile)
infile.close()
except:
print("No file to open. Starting with no data.")
return emails


main()


This is the output: 

/Library/Frameworks/Python.framework/Versions/3.4/bin/python3.4 
/Users/stephaniequiles/Downloads/emailsupdate.py
{'maria': ['steph', 'sst', '33ed'], 'Jim': 'ththth@ththt', 'Ton': 
'tomtomtomt@tomtom', 'Bob': 'b...@bob.com'}
Enter your name :sfdgh
Enter your email address :sdfkj...@syesgd.com
Enter alternate email address :sdfghfds@Asfdgfdcod
email needs @ and . at the same time
Enter your phone number :

I must have something missing but can’t remember what it is. Thanks for your 
help! 

Stephanie 


> On Sat, Aug 1, 2015 at 2:03 PM, Válas Péter  wrote:
>> Hi Stephanie,
>> 
>> the function should be defined first, and used after. So put it before
>> main().
> 
> 
> 
> It's perfectly legal and ok to say:
> 
> ###
> def main():
> callHelper()
> 
> def callHelper():
> print("I am the helper")
> 
> main()
> ###
> 
> 
> 
> Rather, the problem is due to putting the helper function accidentally
> nested *within* main:
> 
> 
> def main():
> callHelper()
> 
>def callHelper():
> print("I am the helper but can't be called until after the 
> definition")
> 
> main()
> #
> 
> 
> 
> One technical way to "fix" this is to move it up a bit:
> 
> #
> def main():
>def callHelper():
> print("I am the helper but can't be called until after the 
> definition")
> 
>callHelper()
> 
> main()
> #
> 
> 
> 
> But this is usually unsatisfactory because we can't then access
> callHelper from outside.  There can be valid reasons to hide function
> definitions at times, but this isn't one of those situations.
> 
> 
> Válas's suggestion, to move the helper's definition above, does make sense:
> 
> #
> def callHelper():
> print("I am the helper but can't be called until after the definition")
> 
> def main():
>callHelper()
> 
> main()
> #
> 
> but a key point needs to be made: don't just move it *up*, but move it *out*.

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


Re: [Tutor] String Attribute

2015-08-02 Thread Ltc Hotspot
Hi Emile,

I made a mistake and incorrectly assumed that differences between 54 lines
of output and 27 lines of output is the result of removing duplicate email
addresses, i.e., gsil...@umich.edu
gsil...@umich.edu, c...@iupui.edu, c...@iupui.edu


Apparently, this is not the case and I was wrong :(
The solution to the problem is in the  desired line output:

stephen.marqu...@uct.ac.za
lo...@media.berkeley.edu
zq...@umich.edu
rjl...@iupui.edu
zq...@umich.edu
rjl...@iupui.edu
c...@iupui.edu
c...@iupui.edu
gsil...@umich.edu
gsil...@umich.edu
zq...@umich.edu
gsil...@umich.edu
wagne...@iupui.edu
zq...@umich.edu
antra...@caret.cam.ac.uk
gopal.ramasammyc...@gmail.com
david.horw...@uct.ac.za
david.horw...@uct.ac.za
david.horw...@uct.ac.za
david.horw...@uct.ac.za
stephen.marqu...@uct.ac.za
lo...@media.berkeley.edu
lo...@media.berkeley.edu
r...@media.berkeley.edu
c...@iupui.edu
c...@iupui.edu
c...@iupui.edu
There were 27 lines in the file with From as the first word
Not in the output of a subset.

Latest output:
set(['stephen.marqu...@uct.ac.za', 'lo...@media.berkeley.edu', '
zq...@umich.edu', 'rjl...@iupui.edu', 'c...@iupui.edu', 'gsil...@umich.edu',
'wagne...@iupui.edu', 'antra...@caret.cam.ac.uk', '
gopal.ramasammyc...@gmail.com', 'david.horw...@uct.ac.za', '
r...@media.berkeley.edu']) ← Mismatch
There were 54 lines in the file with From as the first word

Latest revised code:
fname = raw_input("Enter file name: ")
if len(fname) < 1 : fname = "mbox-short.txt"
fh = open(fname)
count = 0
addresses = set()
for line in fh:
if line.startswith('From'):
line2 = line.strip()
line3 = line2.split()
line4 = line3[1]
addresses.add(line4)
count = count + 1
print addresses
print "There were", count, "lines in the file with From as the first word"

Regards,
Hal

On Sat, Aug 1, 2015 at 5:45 PM, Emile van Sebille  wrote:

> On 8/1/2015 4:07 PM, Ltc Hotspot wrote:
>
>> Hi Alan,
>>
>> Question1: The output result is an address or line?
>>
>
> It's a set actually.  Ready to be further processed I imagine.  Or to
> print out line by line if desired.
>
> Question2: Why are there 54 lines as compared to 27 line in the desired
>> output?
>>
>
> Because there are 54 lines that start with 'From'.
>
> As I noted in looking at your source data, for each email there's a 'From
> ' and a 'From:' -- you'd get the right answer checking only for
> startswith('From ')
>
> Emile
>
>
>
>
>> Here is the latest revised code:
>> fname = raw_input("Enter file name: ")
>> if len(fname) < 1 : fname = "mbox-short.txt"
>> fh = open(fname)
>> count = 0
>> addresses = set()
>> for line in fh:
>>  if line.startswith('From'):
>>  line2 = line.strip()
>>  line3 = line2.split()
>>  line4 = line3[1]
>>  addresses.add(line4)
>>  count = count + 1
>> print addresses
>> print "There were", count, "lines in the file with From as the first word"
>>
>> The output result:
>> set(['stephen.marqu...@uct.ac.za', 'lo...@media.berkeley.edu', '
>> zq...@umich.edu', 'rjl...@iupui.edu', 'c...@iupui.edu', '
>> gsil...@umich.edu',
>> 'wagne...@iupui.edu', 'antra...@caret.cam.ac.uk','
>> gopal.ramasammyc...@gmail.com', 'david.horw...@uct.ac.za', '
>> r...@media.berkeley.edu']) ← Mismatch
>> There were 54 lines in the file with From as the first word
>>
>>
>> The desired output result:
>> stephen.marqu...@uct.ac.za
>> lo...@media.berkeley.edu
>> zq...@umich.edu
>> rjl...@iupui.edu
>> zq...@umich.edu
>> rjl...@iupui.edu
>> c...@iupui.edu
>> c...@iupui.edu
>> gsil...@umich.edu
>> gsil...@umich.edu
>> zq...@umich.edu
>> gsil...@umich.edu
>> wagne...@iupui.edu
>> zq...@umich.edu
>> antra...@caret.cam.ac.uk
>> gopal.ramasammyc...@gmail.com
>> david.horw...@uct.ac.za
>> david.horw...@uct.ac.za
>> david.horw...@uct.ac.za
>> david.horw...@uct.ac.za
>> stephen.marqu...@uct.ac.za
>> lo...@media.berkeley.edu
>> lo...@media.berkeley.edu
>> r...@media.berkeley.edu
>> c...@iupui.edu
>> c...@iupui.edu
>> c...@iupui.edu
>> There were 27 lines in the file with From as the first word
>>
>> Regards,
>> Hal
>>
>>
>>
>>
>>
>>
>>
>>
>>
>> On Sat, Aug 1, 2015 at 1:40 PM, Alan Gauld 
>> wrote:
>>
>> On 01/08/15 19:48, Ltc Hotspot wrote:
>>>
>>> There is an indent message in the revised code.
 Question: Where should I indent the code line for the loop?


>>> Do you understand the role of indentation in Python?
>>> Everything in the indented block is part of the structure,
>>> so you need to indent everything that should be executed
>>> as part of the logical block.
>>>
>>> fname = raw_input("Enter file name: ")
>>>
 if len(fname) < 1 : fname = "mbox-short.txt"
 fh = open(fname)
 count = 0
 addresses = set()
 for line in fh:
   if line.startswith('From'):
   line2 = line.strip()
   line3 = line2.split()
   line4 = line3[1]
   addresses.add(line)
   count = count + 1


>>> Everything after the if line should be indented an extra level
>

Re: [Tutor] String Attribute

2015-08-02 Thread Ltc Hotspot
Hi Alan,

I made a mistake and incorrectly assumed that differences between 54 lines
of output and 27 lines of output is the result of removing duplicate email
addresses, i.e., gsil...@umich.edu
gsil...@umich.edu, c...@iupui.edu, c...@iupui.edu


Apparently, this is not the case and I was wrong :(
The solution to the problem is in the  desired line output:

stephen.marqu...@uct.ac.za
lo...@media.berkeley.edu
zq...@umich.edu
rjl...@iupui.edu
zq...@umich.edu
rjl...@iupui.edu
c...@iupui.edu
c...@iupui.edu
gsil...@umich.edu
gsil...@umich.edu
zq...@umich.edu
gsil...@umich.edu
wagne...@iupui.edu
zq...@umich.edu
antra...@caret.cam.ac.uk
gopal.ramasammyc...@gmail.com
david.horw...@uct.ac.za
david.horw...@uct.ac.za
david.horw...@uct.ac.za
david.horw...@uct.ac.za
stephen.marqu...@uct.ac.za
lo...@media.berkeley.edu
lo...@media.berkeley.edu
r...@media.berkeley.edu
c...@iupui.edu
c...@iupui.edu
c...@iupui.edu
There were 27 lines in the file with From as the first word
Not in the output of a subset.

Latest output:
set(['stephen.marqu...@uct.ac.za', 'lo...@media.berkeley.edu', '
zq...@umich.edu', 'rjl...@iupui.edu', 'c...@iupui.edu', 'gsil...@umich.edu',
'wagne...@iupui.edu', 'antra...@caret.cam.ac.uk', '
gopal.ramasammyc...@gmail.com', 'david.horw...@uct.ac.za', '
r...@media.berkeley.edu']) ← Mismatch
There were 54 lines in the file with From as the first word

Latest revised code:
fname = raw_input("Enter file name: ")
if len(fname) < 1 : fname = "mbox-short.txt"
fh = open(fname)
count = 0
addresses = set()
for line in fh:
if line.startswith('From'):
line2 = line.strip()
line3 = line2.split()
line4 = line3[1]
addresses.add(line4)
count = count + 1
print addresses
print "There were", count, "lines in the file with From as the first word"

Regards,
Hal

On Sat, Aug 1, 2015 at 5:44 PM, Alan Gauld 
wrote:

> On 02/08/15 00:07, Ltc Hotspot wrote:
>
>> Question1: The output result is an address or line?
>>
>
> Its your assignment,. you tell me.
> But from your previous mails I'm assuming you want addresses?
>
> Question2: Why are there 54 lines as compared to 27 line in the desired
>> output?
>>
>
> Because the set removes duplicates? So presumably there were 27
> duplicates? (Which is a suspicious coincidence!)
>
> fname = raw_input("Enter file name: ")
>> if len(fname) < 1 : fname = "mbox-short.txt"
>> fh = open(fname)
>> count = 0
>> addresses = set()
>> for line in fh:
>>  if line.startswith('From'):
>>  line2 = line.strip()
>>  line3 = line2.split()
>>  line4 = line3[1]
>>  addresses.add(line4)
>>  count = count + 1
>> print addresses
>> print "There were", count, "lines in the file with From as the first word"
>>
>
> That looks right in that it does what I think you want it to do.
>
> The output result:
>> set(['stephen.marqu...@uct.ac.za', 'lo...@media.berkeley.edu', '
>> zq...@umich.edu', 'rjl...@iupui.edu', 'c...@iupui.edu', '
>> gsil...@umich.edu',
>> 'wagne...@iupui.edu', 'antra...@caret.cam.ac.uk','
>> gopal.ramasammyc...@gmail.com', 'david.horw...@uct.ac.za', '
>> r...@media.berkeley.edu']) ← Mismatch
>>
>
> That is the set of unique addresses, correct?
>
> There were 54 lines in the file with From as the first word
>>
>
> And that seems to be the number of lines in the original file
> starting with From. Can you check manually if that is correct?
>
> The desired output result:
>> stephen.marqu...@uct.ac.za
>> lo...@media.berkeley.edu
>> zq...@umich.edu
>> rjl...@iupui.edu
>> zq...@umich.edu
>> rjl...@iupui.edu
>>
> ...
>
> Now I'm confused again. This has duplicates but you said you
> did not want duplicates? Which is it?
>
> ...
>
>> c...@iupui.edu
>> c...@iupui.edu
>> There were 27 lines in the file with From as the first word
>>
>
> And this is reporting the number of lines in the output
> rather than the file (I think). Which do you want?
>
> Its easy enough to change the code to govre the output
> you demonstrate, but that's not what you originally asked
> for. So just make up your mind exactly what it is you want
> out and we can make it work for you.
>
> --
> 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
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] FETCH URLs FROM WEBSITE

2015-08-02 Thread Gaurav Lathwal
Thank you very much for your input. :)
I did not that there was a such thing as websites raising flags on people
downloading stuff this way. I will take care about it from next time
onwards.

& Both of you know a lot about all this, how do I go about doing that ? I
mean, how do I learn that much ? Please don't take this question in any
wrong way, I just want to learn. Because in all the Python books, they all
stop after the usual stuff, nobody tells you how to write scripts to do
awesome stuff. :\

Please help.

On 1 August 2015 at 23:18, Válas Péter  wrote:

> 2015-08-01 19:42 GMT+02:00 Alan Gauld :
>
>
> > c) The separate page is not static HTML (or even server
> >generated HTML) it is created in part by the Javascript
> >code when the page loads. That means it is very likely to
> >change on each load (possibly deliberately so to foil robots!)
> >
>
> I didn't go far enough to notice this. :-( So my previous script is just an
> outline, how to approach such tasks, but not a whole solution.
> ___
> 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