[Tutor] Shorten Code.

2011-11-18 Thread Mic


From: Wayne Werner 
Sent: Thursday, November 17, 2011 8:30 PM
To: Mic 
Cc: tutor@python.org 
Subject: Re: [Tutor] Clock in tkinter?

  Say that I have a class and I want to make 100 objects. 
  Then it could look like this:
  snip 
  class Chairs(object):
  snip code 

  #Create the objects
  chair1=Chairs(10,20)
  chair2=Chairs(10,20)
  chair3=Chairs(10,20) 

  How do I shorten this? I have thought of using a for sling. I have looked in 
my programming
  book and on the internet, but I don’t know how to make this shorter. The 
arguements (“10”, “20”)
  should be the same for every object, which should make it easier than if they 
were different each time?

If you ever write a line of code more than once, it's a good sign that you have 
what's called a code smell. This example is very smelly code ;)

What you should do instead is have a collection of chairs:

chairs = []
for _ in range(100): # the underscore `_` indicates that you don't care about 
the value
chairs.append(Chairs(10,20))
--

Yes, I got that right now. But now that you talked about shortening code, I 
have a general question.
What if I don’t write the same line of code more than once, but I write 
similiar lines more than once. Is that okay? 

For example:
value=green”
value_1=”green”

click=-1
click1=-1
click2=-1

I know that I can make this shorter, with a for sling for example, but the 
problem is that 
I need to use these variables later in my program, and I don’t know how do to 
then, to be able
to use them later on, in a function for example. Do you have any general tips 
on how to make
your code shorter?

I also hope I have learnt to post better now.


Thanks!

Mic
wlEmoticon-smile[1].png___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Shorten Code.

2011-11-18 Thread Alan Gauld

On 18/11/11 08:16, Mic wrote:


What if I don’t write the same line of code more than once, but I write
similiar lines more than once. Is that okay? Ler
For example:
value=green”
value_1=”green”


If you had a lot of these you could shorten it with a loop (BTW the 
English term in programming terminology is loop not sling ;-)


for var in [value,value_1]:
var = green

But you need to have already created the variables somewhere and unless 
there is a big list its not usually worth while.


One other trick you can use for this specific type of assignment is

value = value_1 = green

But it gets a bit unreadable for long lists of names.


click=-1
click1=-1
click2=-1


Same here, but imagine it had been:

click=-1
click1= 2
click2=-1


And here you are changing both name and value.
The best abbreviation here is probably tuple
expansion:

click, click1, click2 = -1,2,-1

 Do you have any general tips on how to make

your code shorter?


Shorter is not necessarily better. Clarity is far more important and you 
should always consider whether tricks like those above are helping or 
hindering clarity. Only use them if they make your code easier to read. 
(Also they all make debugging slightly harder so you should think about 
that too)


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

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


[Tutor] A recursion question

2011-11-18 Thread Kĩnũthia Mũchane

Hi,

I am trying to do something which is really stupid :-)
I would like to count the number of occurrences of a certain character 
in a list.

This is more of an exercise in recursion rather than the underlying problem.
I could have used a *for* loop or simply the list *count* method.
Here is the code:

class Find_Ex():

count = 0
def slais(self, lst, x):
if len(lst) == 0: #if list is empty just give a -1
return -1
elif lst[0] == x:
Find_Ex.count += 1 # we have found 'x', increment class 
attribute 'count' by 1
Find_Ex.slais(self,lst[1:], x)# slice the list and go to 
the next element

else:
Find_Ex.slais(self,lst[1:], x)#'x' not found so we move to 
the next element

return Find_Ex.count

s = Find_Ex()
lst = [4,4,4,5,6,7,4,7,7,4]
x = 4
print There are %d occurrences of %d%(s.slais(lst, x),x)

It works as advertised but I am convincing myself that it should not! :-)

If the list is empty, which is the base case, s.slais([], 4) returns -1. 
Now using some bush logic, in a non-empty list, in order for the 
recursion to terminate it has to 'hit' the base case and return -1. 
Where does this -1 go ? Further, why do not I get a *TypeError*  when I 
use a simple *return* statement in the *if* clause?


The reason I am asking  that is that I think(wrongly, of course :-)) it 
should be part of the answer and therefore I should be getting an answer 
that is off by one or a *TypeError*!!


And by the way, the reason I used a *class* was that I could not get a 
suitable place in the program to initialise my *count* variable otherwise.


Thanks...

--
Kĩnũthia

S 1º 8' 24”
E 36º 57' 36”
1522m

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


Re: [Tutor] A recursion question

2011-11-18 Thread Christian Witts

On 2011/11/18 03:16 PM, Kĩnũthia Mũchane wrote:

Hi,

I am trying to do something which is really stupid :-)
I would like to count the number of occurrences of a certain character 
in a list.
This is more of an exercise in recursion rather than the underlying 
problem.

I could have used a *for* loop or simply the list *count* method.
Here is the code:

class Find_Ex():

count = 0
def slais(self, lst, x):
if len(lst) == 0: #if list is empty just give a -1
return -1
elif lst[0] == x:
Find_Ex.count += 1 # we have found 'x', increment class 
attribute 'count' by 1
Find_Ex.slais(self,lst[1:], x)# slice the list and go to 
the next element

else:
Find_Ex.slais(self,lst[1:], x)#'x' not found so we move to 
the next element

return Find_Ex.count

s = Find_Ex()
lst = [4,4,4,5,6,7,4,7,7,4]
x = 4
print There are %d occurrences of %d%(s.slais(lst, x),x)

It works as advertised but I am convincing myself that it should not! :-)

If the list is empty, which is the base case, s.slais([], 4) returns 
-1. Now using some bush logic, in a non-empty list, in order for the 
recursion to terminate it has to 'hit' the base case and return -1. 
Where does this -1 go ? Further, why do not I get a *TypeError*  when 
I use a simple *return* statement in the *if* clause?


The reason I am asking  that is that I think(wrongly, of course :-)) 
it should be part of the answer and therefore I should be getting an 
answer that is off by one or a *TypeError*!!


And by the way, the reason I used a *class* was that I could not get a 
suitable place in the program to initialise my *count* variable 
otherwise.


Thanks...

If you pop in some print statements you can see what's happening a bit 
easier.  You are creating a stack of functions which each return their 
values but in a LIFO fashion (Last In, First Out) so you can see the 
first return is -1 as you expected to happen when the list is exhausted, 
and then each subsequent return is the count which is why you get the 
correct return value in the end.  Also, why do you think you should get 
a TypeError when you `return -1` ?


class Find_Ex():
count = 0
def slais(self, lst, x):
print lst
if len(lst) == 0: #if list is empty just give a -1
print 'Returning -1'
return -1
elif lst[0] == x:
print 'Incrementing Count'
Find_Ex.count += 1 # we have found 'x', increment class 
attribute 'count' by 1
Find_Ex.slais(self,lst[1:], x)# slice the list and go to 
the next element

else:
print 'Nothing Found'
Find_Ex.slais(self,lst[1:], x)#'x' not found so we move to 
the next element

print 'Returning the count'
return Find_Ex.count

s = Find_Ex()
lst = [4,4,4,5,6,7,4,7,7,4]
x = 4
print There are %d occurrences of %d%(s.slais(lst, x),x)

[4, 4, 4, 5, 6, 7, 4, 7, 7, 4]
Incrementing Count
[4, 4, 5, 6, 7, 4, 7, 7, 4]
Incrementing Count
[4, 5, 6, 7, 4, 7, 7, 4]
Incrementing Count
[5, 6, 7, 4, 7, 7, 4]
Nothing Found
[6, 7, 4, 7, 7, 4]
Nothing Found
[7, 4, 7, 7, 4]
Nothing Found
[4, 7, 7, 4]
Incrementing Count
[7, 7, 4]
Nothing Found
[7, 4]
Nothing Found
[4]
Incrementing Count
[]
Returning -1
Returning the count
Returning the count
Returning the count
Returning the count
Returning the count
Returning the count
Returning the count
Returning the count
Returning the count
Returning the count
There are 5 occurrences of 4

--

Christian Witts
Python Developer
//
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Encoding

2011-11-18 Thread Max S.
Well, I am assuming that by this you mean converting user input into a
string, and then extracting the numerals (0-9) from it.  Next time, please
tell us your version of Python.  I'll do my best to help with this.  You
might try the following:

the_input = input(Insert string here: ) # change to raw_input in python 2
after = 
for char in the_input:
try:
char = int(char)
except:
after += char

If other symbols might be in the string ($, @, etc.), then you might use

the_input = input('Insert string here: ') # change to raw_input in python 2
after = ''
not_allowed = '1234567890-=!@#$%^**()_+,./?`~[]{}\\|'
for char in the_input:
if char in not_allowed:
pass
else:
after += char

This method requires more typing, but it works with a wider variety of
characters.  Hopefully this helped.

On Thu, Nov 17, 2011 at 8:45 PM, Nidian Job-Smith nidia...@hotmail.comwrote:


 Hi all,

 In my programme I am encoding what the user has in-putted.

 What the user inputs will in a string, which might a mixture of letters
 and numbers.

 However I only want the letters to be encoded.


 Does any-one how I can only allow the characters to be encoded ??

 Big thanks,



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


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


Re: [Tutor] Shorten Code.

2011-11-18 Thread Dave Angel

On 11/18/2011 04:01 AM, Alan Gauld wrote:

On 18/11/11 08:16, Mic wrote:


What if I don’t write the same line of code more than once, but I write
similiar lines more than once. Is that okay? Ler
For example:
value=green”
value_1=”green”


If you had a lot of these you could shorten it with a loop (BTW the 
English term in programming terminology is loop not sling ;-)


for var in [value,value_1]:
var = green


Um, that won't work.   You typed that example too quickly.


Mic, the problem is not shortening code, but making it more readable, 
and easier to maintain.  If you have a series of variables that hold 
similar or identical values, or which are treated in consistent ways, 
then you should probably make a list out of them.  And that will 
naturally shorten code like this.


student0 = 4
student1 = 3
student2 = 12
student3 = 11

Replace with

students = list((4,3,12,11))

Then if you want to deal with a particular student, you might do
   student[2] = 5

But if you want to deal with the ith student, you could do
  student[i] =

and if you want to do something with all of them:
   for index, student in enumerate(students):
 students[indes] += 65

There are plenty of more advanced methods that would make even that 
simpler, but I'm trying to keep it simple.


--

DaveA

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


Re: [Tutor] A recursion question

2011-11-18 Thread Dave Angel

On 11/18/2011 08:16 AM, Kĩnũthia Mũchane wrote:

Hi,

I am trying to do something which is really stupid :-)
I would like to count the number of occurrences of a certain character 
in a list.
This is more of an exercise in recursion rather than the underlying 
problem.

I could have used a *for* loop or simply the list *count* method.
Here is the code:

class Find_Ex():

count = 0
def slais(self, lst, x):
if len(lst) == 0: #if list is empty just give a -1
return -1
elif lst[0] == x:
Find_Ex.count += 1 # we have found 'x', increment class 
attribute 'count' by 1
Find_Ex.slais(self,lst[1:], x)# slice the list and go to 
the next element

else:
Find_Ex.slais(self,lst[1:], x)#'x' not found so we move to 
the next element

return Find_Ex.count

s = Find_Ex()
lst = [4,4,4,5,6,7,4,7,7,4]
x = 4
print There are %d occurrences of %d%(s.slais(lst, x),x)

It works as advertised but I am convincing myself that it should not! :-)

Well, it doesn't count the number of occurrences correctly if the list 
is empty.  It should get zero, and it gets -1.  But for any non-empty 
list, nothing ever looks at the -1 value, so it doesn't matter what you 
put there.   This example diverges from traditional recursion in many 
ways, but the chief reason it's not traditional recursion is that it 
never uses the return value. within the function.
If the list is empty, which is the base case, s.slais([], 4) returns 
-1. Now using some bush logic, in a non-empty list, in order for the 
recursion to terminate it has to 'hit' the base case and return -1. 
Where does this -1 go ? 
Nowhere.  You don't use it, so it gets discarded.  if you were going to 
use it, your internal calls to the method would look something like:

  b = self.slais(lst[1:], x)
 and then you'd do something with b.
Further, why do not I get a *TypeError*  when I use a simple *return* 
statement in the *if* clause?


You would if you actually used the value for arithmetic.  But the return 
itself would be perfectly legal.  it's just a shortcut for 'return None'
The reason I am asking  that is that I think(wrongly, of course :-)) 
it should be part of the answer and therefore I should be getting an 
answer that is off by one or a *TypeError*!!


And by the way, the reason I used a *class* was that I could not get a 
suitable place in the program to initialise my *count* variable 
otherwise.


Using a class is fine.  But you're abusing it.  What happens if you try 
to sum a second list?  (Hint, it gives you a higher number)

Thanks...

If you really want to recursively count, you need a structure which uses 
no objects of global lifetime.  The intermediate values should be stored 
in local variables to that method.


def counter(mylist, val):
  if len(mylist == 0):
 return 0
  prev = counter(mylist[1:], val) #this is actually using the 
recursive return value

  if mylist[0] == val:
return prev + 1
  else:
return prev

Totally untested.  And there are certainly many other variants 
possible.  But the key is you have to do something with the value 
returned to you by the lower level function.






--

DaveA

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


[Tutor] FW: urgent help!! THANKS EVERYONE!

2011-11-18 Thread Prasad, Ramit
Forwarding to the list since I wasn't the only person who helped ;)

Ramit


Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology
712 Main Street | Houston, TX 77002
work phone: 713 - 216 - 5423

--

From: ADRIAN KELLY [mailto:kellyadr...@hotmail.com] 
Sent: Thursday, November 17, 2011 6:08 PM
To: Prasad, Ramit
Subject: RE: [Tutor] urgent help!! THANKS EVERYONE!

Thanks for your help i just got it going my way below - but your way looks 
easier and better!  
thanks for all your help everyone.  feel free to comment on my method - 
its awkward but it works.. 

adrian

def exchange(cash_in):
    euro=1
    dollar=1.35
    base=50
    if cash_inbase:
        totalreturn=cash_in*dollar
    else:
        totalreturn=0
    return totalreturn


def main():
    amount=0
    amount = float(raw_input('how much do you want to change:'))
    while amount50:
        print 'enter an amount over 50'
        amount = float(raw_input('how much do you want to change:'))
    else:
        total=exchange(amount)
        print 'Your exchange comes to: ',total
  
    
main()

 
  
 From: ramit.pra...@jpmorgan.com
 To: kellyadr...@hotmail.com; waynejwer...@gmail.com
 CC: tutor@python.org
 Subject: RE: [Tutor] urgent help!!!
 Date: Thu, 17 Nov 2011 23:43:10 +
 
 def exchange(cash_in):
     euro=1
     dollar=1.35
     base=50
     if cash_inbase:
         totalreturn=cash_in*dollar
     else:
         totalreturn=0
     return totalreturn
 
 amount=0
 # this would be better placed inside the main function.
 def main():
     while amount50:
         amount = raw_input(float('how much do you want to change:'))
 # This should be 
 # amount = float( raw_input('how much do you want to change:' ) )
     if amount50:
         total=0
         print 'enter an amount over 50: '
     else:
         total=exchange(amount)
         print 'Your exchange comes to: ',total
 
 
 Ramit
 
 
 Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology
 712 Main Street | Houston, TX 77002
 work phone: 713 - 216 - 5423
 
 -- 
This email is confidential and subject to important disclaimers and
conditions including on offers for the purchase or sale of
securities, accuracy and completeness of information, viruses,
confidentiality, legal privilege, and legal entity disclaimers,
available at http://www.jpmorgan.com/pages/disclosures/email.  
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] FW: urgent help!! THANKS EVERYONE!

2011-11-18 Thread Wayne Werner
On Fri, Nov 18, 2011 at 9:26 AM, Prasad, Ramit ramit.pra...@jpmorgan.comwrote:

 Forwarding to the list since I wasn't the only person who helped ;)

 From: ADRIAN KELLY [mailto:kellyadr...@hotmail.com]
 Sent: Thursday, November 17, 2011 6:08 PM
 To: Prasad, Ramit
 Subject: RE: [Tutor] urgent help!! THANKS EVERYONE!

 Thanks for your help i just got it going my way below - but your way looks
 easier and better!
 thanks for all your help everyone.  feel free to comment on my method -
 its awkward but it works.. snip
 def main():
 amount=0
 amount = float(raw_input('how much do you want to change:'))
 while amount50:
 print 'enter an amount over 50'
 amount = float(raw_input('how much do you want to change:'))
 else:
 total=exchange(amount)
 print 'Your exchange comes to: ',total


In these sorts of cases I actually prefer the recursive solution. And from
a usability standpoint it's much nicer to warn the user ahead of time:

def amount_over_50():
amount = float(raw_input(How much do you want to change (minimum $50)?
Amount: $))
if amount  50.0:
print 'Please enter an amount greater than $50'
return amount_over_50()
return amount


Then you can just do this:

def main():
print 'Your total comes to', exchange(amount_over_50())

The chances of hitting the maximum recursion depth is pretty slim, unless
your user manages to type in a wrong number about 1000 times ;)

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


[Tutor] In a pickle over pickles….Python 3

2011-11-18 Thread Joe Batt

Hi All,Sorry to trouble you all again with more nooby problems! Only been 
programming a week so still all a haze especially since self taught…..
I am opening a url and saving it to a file on my computer, then I am trying to 
pickle it. I have written the url file to a file on my computer then opened it 
and assigned the contents to a var 'filecontents' and tried to pickle it it is 
giving the error:
Traceback (most recent call last):  File 
/Users/joebatt/Desktop/python/pickling puzzle 5.py, line 39, in module
geturlfile(urlfile)  File /Users/joebatt/Desktop/python/pickling puzzle 5.py, 
line 28, in geturlfilepickle.dump(filecontents,pickledfile)TypeError: must 
be str, not bytes
Yet I tested the variable filecontents using   print (type(file contents))  and 
it is saying that it is a str yet the error seems to indicate it is a byte, can 
anyone point me in the right direction please?
(I know my coding is very untidy and verbose, sorry I am very new and at the 
moment I have to think in baby steps with little knowledge!)
Joe
  Pickle an 
object- ###
import pickleimport urllib
def geturlfile(urlfile):#gets the user URL from main opens it and saves it to 
var fileurlfrom urllib.request import urlopen
fileurl=urlopen(urlfile)#opens the file on computer and writes the var fileurl 
to ithtml_file=open('///Users/joebatt/Desktop/python/puzzle5.txt','w')
for line in fileurl.readlines():linestring=line.decode(utf-8) 
#ensures written in string not bytehtml_file.write(linestring)
html_file.close() #closes the puzzle file#just prints file to check its correct 
   html_file=open('///Users/joebatt/Desktop/python/puzzle5.txt','r')
filecontents=html_file.read()html_file.close()print (filecontents)
print (type(filecontents))
#pickles the file filecontents containing the url file
pickledfile=open('///Users/joebatt/Desktop/python/pickledpuzzle5.txt','w')
pickle.dump(filecontents,pickledfile)pickledfile.close()
return ()

# Main programurlfile=input('Please input the URL ')geturlfile(urlfile) 
  ___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Saving read-only or encoded text files?

2011-11-18 Thread Max S.
Hi.  I've been using a lot of text files recently, and I'm starting to
worry about a user hacking some element by editing the text files.  I know
that I can pickle my data instead, creating less easily editable (try
saying that five times fast) .dat files, but I'd rather store individual
variables rather than lists of objects.  Is there a way to make my text
files either read-only or saved in some way that they can't be opened, or
at least not so easily as double-clicking on them?  I just want some
slightly more secure code, though it's not too important.  I just thought
I'd ask.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Saving read-only or encoded text files?

2011-11-18 Thread Prasad, Ramit
Hi.  I've been using a lot of text files recently, and I'm starting to worry 
about a user hacking some element by editing the text files.  I know that I can 
pickle my data instead, creating less easily editable (try saying that five 
times fast) .dat files, but I'd rather store individual variables rather than 
lists of objects.  Is there a way to make my text files either read-only or 
saved in some way that they can't be opened, or at least not so easily as 
double-clicking on them?  I just want some slightly more secure code, though 
it's not too important.  I just thought I'd ask.
==

Any file will eventually be able to be reverse engineered, but it matters how 
much effort you care to obfuscate it. The way you can do it will vary based on 
your OS. 

For Windows, you can change the file extension to something that is not read by 
most text editors '.zxy'. It will still be able to be read if they try and open 
it with a text editor, but double clicking  will not work by default. You can 
also try setting the file attribute directly: 
http://code.activestate.com/recipes/303343-changing-file-attributes-on-windows/ 

For *nix/OS X, you can prepend the file with . as those files are hidden by 
default on most *nix systems I have used. You can also try to use 
os.chmod(0###, 'filename').


Keep in mind that all of these solutions are probably user reversible since the 
application will have the permissions of the user account it is run as; in most 
cases this is the same as the logged in user.



Ramit


Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology
712 Main Street | Houston, TX 77002
work phone: 713 - 216 - 5423

--
This email is confidential and subject to important disclaimers and
conditions including on offers for the purchase or sale of
securities, accuracy and completeness of information, viruses,
confidentiality, legal privilege, and legal entity disclaimers,
available at http://www.jpmorgan.com/pages/disclosures/email.  
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Saving read-only or encoded text files?

2011-11-18 Thread Max gmail
Thank you.  This will work perfectly.

On Nov 18, 2011, at 11:58 AM, Prasad, Ramit wrote:

 Hi.  I've been using a lot of text files recently, and I'm starting to worry 
 about a user hacking some element by editing the text files.  I know that I 
 can pickle my data instead, creating less easily editable (try saying that 
 five times fast) .dat files, but I'd rather store individual variables rather 
 than lists of objects.  Is there a way to make my text files either read-only 
 or saved in some way that they can't be opened, or at least not so easily as 
 double-clicking on them?  I just want some slightly more secure code, though 
 it's not too important.  I just thought I'd ask.
 ==
 
 Any file will eventually be able to be reverse engineered, but it matters how 
 much effort you care to obfuscate it. The way you can do it will vary based 
 on your OS. 
 
 For Windows, you can change the file extension to something that is not read 
 by most text editors '.zxy'. It will still be able to be read if they try and 
 open it with a text editor, but double clicking  will not work by default. 
 You can also try setting the file attribute directly: 
 http://code.activestate.com/recipes/303343-changing-file-attributes-on-windows/
  
 
 For *nix/OS X, you can prepend the file with . as those files are hidden by 
 default on most *nix systems I have used. You can also try to use 
 os.chmod(0###, 'filename').
 
 
 Keep in mind that all of these solutions are probably user reversible since 
 the application will have the permissions of the user account it is run as; 
 in most cases this is the same as the logged in user.
 
 
 
 Ramit
 
 
 Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology
 712 Main Street | Houston, TX 77002
 work phone: 713 - 216 - 5423
 
 --
 This email is confidential and subject to important disclaimers and
 conditions including on offers for the purchase or sale of
 securities, accuracy and completeness of information, viruses,
 confidentiality, legal privilege, and legal entity disclaimers,
 available at http://www.jpmorgan.com/pages/disclosures/email.  
 ___
 Tutor maillist  -  Tutor@python.org
 To unsubscribe or change subscription options:
 http://mail.python.org/mailman/listinfo/tutor

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


Re: [Tutor] In a pickle over pickles….Python 3

2011-11-18 Thread Dave Angel

On 11/18/2011 11:12 AM, Joe Batt wrote:

Hi All,Sorry to trouble you all again with more nooby problems! Only been 
programming a week so still all a haze especially since self taught…..
I am opening a url and saving it to a file on my computer, then I am trying to 
pickle it. I have written the url file to a file on my computer then opened it 
and assigned the contents to a var 'filecontents' and tried to pickle it it is 
giving the error:
Traceback (most recent call last):  File /Users/joebatt/Desktop/python/pickling puzzle 5.py, 
line 39, inmodule geturlfile(urlfile)  File /Users/joebatt/Desktop/python/pickling 
puzzle 5.py, line 28, in geturlfilepickle.dump(filecontents,pickledfile)TypeError: must be str, 
not bytes
Yet I tested the variable filecontents using   print (type(file contents))  and 
it is saying that it is a str yet the error seems to indicate it is a byte, can 
anyone point me in the right direction please?
(I know my coding is very untidy and verbose, sorry I am very new and at the 
moment I have to think in baby steps with little knowledge!)
Joe
  Pickle an 
object- ###
import pickleimport urllib
def geturlfile(urlfile):#gets the user URL from main opens it and saves it to var fileurl 
   from urllib.request import urlopenfileurl=urlopen(urlfile)#opens the file on 
computer and writes the var fileurl to it
html_file=open('///Users/joebatt/Desktop/python/puzzle5.txt','w')for line in 
fileurl.readlines():linestring=line.decode(utf-8) #ensures written in 
string not bytehtml_file.write(linestring)html_file.close() #closes the 
puzzle file#just prints file to check its correct
html_file=open('///Users/joebatt/Desktop/python/puzzle5.txt','r')
filecontents=html_file.read()html_file.close()print (filecontents)print 
(type(filecontents))
#pickles the file filecontents containing the url file
pickledfile=open('///Users/joebatt/Desktop/python/pickledpuzzle5.txt','w')
pickle.dump(filecontents,pickledfile)pickledfile.close()
 return ()

# Main programurlfile=input('Please input the URL ')geturlfile(urlfile) 



You forgot to post in text mode, so everything ran together.



--

DaveA

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


Re: [Tutor] Saving read-only or encoded text files?

2011-11-18 Thread Wayne Werner
On Fri, Nov 18, 2011 at 11:17 AM, Max gmail maxskywalk...@gmail.com wrote:

 Thank you.  This will work perfectly.

 On Nov 18, 2011, at 11:58 AM, Prasad, Ramit wrote:
 snip
 
  Any file will eventually be able to be reverse engineered, but it
 matters how much effort you care to obfuscate it. The way you can do it
 will vary based on your OS.
 
  For Windows, you can change the file extension to something that is not
 read by most text editors '.zxy'. It will still be able to be read if they
 try and open it with a text editor, but double clicking  will not work by
 default. You can also try setting the file attribute directly:
 http://code.activestate.com/recipes/303343-changing-file-attributes-on-windows/
 
  For *nix/OS X, you can prepend the file with . as those files are
 hidden by default on most *nix systems I have used. You can also try to use
 os.chmod(0###, 'filename').
 
 
  Keep in mind that all of these solutions are probably user reversible
 since the application will have the permissions of the user account it is
 run as; in most cases this is the same as the logged in user.
 snip


As an addition, you can also create the file using the zipfile module (
http://docs.python.org/library/zipfile.html). This adds another layer of
obfuscation and has the added benefit of making your files smaller. Of
course, the savvy user won't have any issue getting past this (Office files
are just archive files). On Ubuntu at least, if you just remove the
extension then it will attempt to discover what the filetype, and can
usually guess archive types.

It's security through obscurity, of course, so it all depends on who you're
worried about accessing this data.

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


Re: [Tutor] Encoding

2011-11-18 Thread Prasad, Ramit
On 11/17/2011 8:45 PM, Nidian Job-Smith wrote: 

Hi all, 

In my programme I am encoding what the user has in-putted. 

What the user inputs will in a string, which might a mixture of letters and 
numbers.

However I only want the letters to be encoded. 


I am assuming that you meant only accept characters and not actual
text encoding. The following example is untested and is limited. It 
will not really work with non-ASCII letters (i.e. Unicode).

import string
input_string = raw_input( 'Enter something' ) #use input in Python3
final_input = [] # append to a list instead of concatenating a string
 # because it is faster to ''.join( list )
for char in input_string:
if char in string.letters:
final_input.append( char )
input_string = ''.join( final_input )



Ramit


Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology
712 Main Street | Houston, TX 77002
work phone: 713 - 216 - 5423

--

This email is confidential and subject to important disclaimers and
conditions including on offers for the purchase or sale of
securities, accuracy and completeness of information, viruses,
confidentiality, legal privilege, and legal entity disclaimers,
available at http://www.jpmorgan.com/pages/disclosures/email.  
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Shorten Code.

2011-11-18 Thread ALAN GAULD


  for var in [value,value_1]:
 var = green

 Um, that won't work.   You typed that example too quickly.


Oops! Yes. You'd need to enumerate and access the variables
via an index. yuk. Don't do it folks! :-)

Excuse: It was early morning and I hadn't had any coffee...

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


Re: [Tutor] In a pickle over pickles….Python 3

2011-11-18 Thread Jerry Hill
On Fri, Nov 18, 2011 at 11:12 AM, Joe Batt joeb...@hotmail.co.uk wrote:


 pickledfile=open('///Users/joebatt/Desktop/python/pickledpuzzle5.txt','w')
 pickle.dump(filecontents,pickledfile)
 pickledfile.close()


A pickle is a binary object, so you'll need to open your picklefile in
binary mode:

pickledfile=open('///Users/joebatt/Desktop/python/pickledpuzzle5.txt','wb')

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


Re: [Tutor] A recursion question

2011-11-18 Thread Kĩnũthia Mũchane

On 11/18/2011 06:04 PM, Dave Angel wrote:

On 11/18/2011 08:16 AM, Kĩnũthia Mũchane wrote:

snip

Well, it doesn't count the number of occurrences correctly if the list 
is empty.  It should get zero, and it gets -1.  But for any non-empty 
list, nothing ever looks at the -1 value, so it doesn't matter what 
you put there.   This example diverges from traditional recursion in 
many ways, but the chief reason it's not traditional recursion is that 
it never uses the return value. within the function.
If the list is empty, which is the base case, s.slais([], 4) returns 
-1. Now using some bush logic, in a non-empty list, in order for the 
recursion to terminate it has to 'hit' the base case and return -1. 
Where does this -1 go ? 
Nowhere.  You don't use it, so it gets discarded.  if you were going 
to use it, your internal calls to the method would look something like:

  b = self.slais(lst[1:], x)
 and then you'd do something with b.
Further, why do not I get a *TypeError*  when I use a simple *return* 
statement in the *if* clause?


You would if you actually used the value for arithmetic.  But the 
return itself would be perfectly legal.  it's just a shortcut for 
'return None'
The reason I am asking  that is that I think(wrongly, of course :-)) 
it should be part of the answer and therefore I should be getting an 
answer that is off by one or a *TypeError*!!


And by the way, the reason I used a *class* was that I could not get 
a suitable place in the program to initialise my *count* variable 
otherwise.


Using a class is fine.  But you're abusing it.  What happens if you 
try to sum a second list?  (Hint, it gives you a higher number)

That is very true, I tried it with a second list and the value was higher.

Thanks...

If you really want to recursively count, you need a structure which 
uses no objects of global lifetime.  The intermediate values should be 
stored in local variables to that method.


def counter(mylist, val):
  if len(mylist == 0):
 return 0
  prev = counter(mylist[1:], val) #this is actually using the 
recursive return value

  if mylist[0] == val:
return prev + 1
  else:
return prev
I was trying to come up with something like this but I was totally 
stumped. Now I understand, perfectly.

My heartfelt thanks to you, Dave, and Christian ! ;-)


Totally untested.  And there are certainly many other variants 
possible.  But the key is you have to do something with the value 
returned to you by the lower level function.









--
Kĩnũthia

S 1º 8' 24”
E 36º 57' 36”
1522m

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


Re: [Tutor] binary file query

2011-11-18 Thread Prasad, Ramit
No *need* but, often convenient, regardless of whether the data was 
written by a C struct or not.(*) It is a way to interpret binary data in 
terms of fundamental data types such as ints, floats, strings etc.

Trying to convert raw bytes representing floats into a floating point 
number without using struct would be an interesting exercise. Using 
struct it's trivial.

Interesting, I will keep it in mind. Thanks!

Ramit


Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology
712 Main Street | Houston, TX 77002
work phone: 713 - 216 - 5423

--
This email is confidential and subject to important disclaimers and
conditions including on offers for the purchase or sale of
securities, accuracy and completeness of information, viruses,
confidentiality, legal privilege, and legal entity disclaimers,
available at http://www.jpmorgan.com/pages/disclosures/email.  
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Shorten Code.

2011-11-18 Thread Alexander Etter
On Nov 18, 2011, at 13:15, ALAN GAULD alan.ga...@btinternet.com wrote:

 
   for var in [value,value_1]:
  var = green
 
  Um, that won't work.  You typed that example too quickly.
 
 Oops! Yes. You'd need to enumerate and access the variables
 via an index. yuk. Don't do it folks! :-)
 
 Excuse: It was early morning and I hadn't had any coffee...
 
 Alan G.
 

In your defense Alan, after you typed that code in your response you mentioned 
the necessity of defining the variables:

But you need to have already created the variables somewhere and unless there 
is a big list its not usually worth while.

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

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


Re: [Tutor] urgent help!!!!!!!!!!!

2011-11-18 Thread Emile van Sebille

On 11/17/2011 3:26 PM ADRIAN KELLY said...

i know i'm stupid but i have tried everything to get one line of text
working, i have written out pseudo and read every website.
now i am getting this error

Traceback (most recent call last):
File F:\VTOS ATHLONE\PYTHON_VTOS\foreign exchange\f_ex4 - Copy.py,
line 24, in module
main()
File F:\VTOS ATHLONE\PYTHON_VTOS\foreign exchange\f_ex4 - Copy.py,
line 14, in main
while amount50:
UnboundLocalError: local variable 'amount' referenced before assignment




You've seen the fixes, but perhaps more explanation helps too.

Python organizes variables into namespaces.  The normal namespace 
resolution sequence is local, global, builtin.  Assigning to a name 
within a function creates a local variable, otherwise accessing a name 
in a function will use the global or builtin namespaces.  Python decides 
these issues in part during initial loading of the module where it sees 
that you assign to the variable amount within the function, thus 
creating a local variable.  Later, during execution, you first test the 
value of amount (in the while statement), but amount isn't assigned to 
until after the test, ergo, UnboundLocalError.


HTH,

Emile



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


Re: [Tutor] python telnet

2011-11-18 Thread Rayon
I installed the telnet client but still the same error. 

Traceback (most recent call last):
  File C:\Users\Rayon\Documents\projects1\super_hia\main.py, line 6, in
module
child = winspawn('telnet 192.168.0.55:210')
  File
C:\Python26\lib\site-packages\winpexpect-1.5-py2.6.egg\winpexpect.py, line
346, in __init__
logfile=logfile, cwd=cwd, env=env)
  File C:\Python26\lib\site-packages\winpexpect-1.5-py2.6.egg\pexpect.py,
line 429, in __init__
self._spawn (command, args)
  File
C:\Python26\lib\site-packages\winpexpect-1.5-py2.6.egg\winpexpect.py, line
369, in _spawn
raise ExceptionPexpect, 'Command not found: %s' % self.command
ExceptionPexpect: Command not found: telnet 

-Original Message-
From: tutor-bounces+evosweet=hotmail@python.org
[mailto:tutor-bounces+evosweet=hotmail@python.org] On Behalf Of Steven
D'Aprano
Sent: 17 November 2011 19:52
To: tutor@python.org
Subject: Re: [Tutor] python telnet

Rayon wrote:

 I am trying to use winpexpect  to connect  a telnet session. 
 I keep getting this  error. 
 
  
 
 raise ExceptionPexpect, 'Command not found: %s' % self.command
 ExceptionPexpect: Command not found: telnet

Please copy and paste the entire traceback, not just the last couple of
lines. But judging by just the small bit you show, it looks like telnet is
not a command that winpexpect understands, so it raises an error command
not found.

Perhaps it is a bug in winpexpect. Are you using the latest version?

Do you actually have telnet available on your system? If not, then you can't
expect winpexpect to use something which isn't there.


-- 
Steven

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

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


Re: [Tutor] python telnet

2011-11-18 Thread Rayon
Thank you I think I understand now, thank you very much.

-Original Message-
From: tutor-bounces+evosweet=hotmail@python.org
[mailto:tutor-bounces+evosweet=hotmail@python.org] On Behalf Of Steven
D'Aprano
Sent: 17 November 2011 19:52
To: tutor@python.org
Subject: Re: [Tutor] python telnet

Rayon wrote:

 I am trying to use winpexpect  to connect  a telnet session. 
 I keep getting this  error. 
 
  
 
 raise ExceptionPexpect, 'Command not found: %s' % self.command
 ExceptionPexpect: Command not found: telnet

Please copy and paste the entire traceback, not just the last couple of
lines. But judging by just the small bit you show, it looks like telnet is
not a command that winpexpect understands, so it raises an error command
not found.

Perhaps it is a bug in winpexpect. Are you using the latest version?

Do you actually have telnet available on your system? If not, then you can't
expect winpexpect to use something which isn't there.


-- 
Steven

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

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


Re: [Tutor] A recursion question

2011-11-18 Thread Asokan Pichai
Another way to do that is to avoid any intermediate variables altogether
That may be easier to understand YMMV

def counter(mylist, val):
 if len(mylist == 0):
return 0
 if mylist[0] == val:
   return  1 + counter(mylist[1:], val)
 else:
   return counter(mylist[1:])


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


Re: [Tutor] FW: urgent help!! THANKS EVERYONE!

2011-11-18 Thread Steven D'Aprano

Wayne Werner wrote:


The chances of hitting the maximum recursion depth is pretty slim, unless
your user manages to type in a wrong number about 1000 times ;)


I've had to provide desktop support to people who have done that.


Only-slightly-exaggerating-ly 'yrs,


--
Steven

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


Re: [Tutor] A recursion question

2011-11-18 Thread Kĩnũthia Mũchane

On 11/19/2011 06:03 AM, Asokan Pichai wrote:

Another way to do that is to avoid any intermediate variables altogether
That may be easier to understand YMMV

def counter(mylist, val):
 if len(mylist == 0):
return 0
 if mylist[0] == val:
   return  1 + counter(mylist[1:], val)
 else:
   return counter(mylist[1:])
The intermediate variable explanation by Dave actually clinched it for 
me. Actually, the one I wrote is suspiciously similar to yours ;-). 
Anyway, thanks Asokan!



Asokan Pichai




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



--
Kĩnũthia

S 1º 8' 24”
E 36º 57' 36”
1522m

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