Re: [Tutor] another better way to do this ?

2014-01-13 Thread Roelof Wobben
I have read all comments and im a little bit confused.
About which script are we talkimng about. I have seen a lot.
 
Roelof
 
 From: keithw...@gmail.com
 Date: Sun, 12 Jan 2014 16:43:40 -0500
 CC: tutor@python.org
 Subject: Re: [Tutor] another better way to do this ?
 
 On Sun, Jan 12, 2014 at 2:22 PM, Keith Winston keithw...@gmail.com wrote:
  There's another approach, I think, that's quite easy if order IS important.
 
 Alas, there's one further problem with my script, relating to testing
 multiple sequential letters in product... but I'm not going to say
 more, I'll leave it as a problem for the OP. It's an easy fix once you
 understand the issue.
 
 -- 
 Keith
 ___
 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] another better way to do this ?

2014-01-13 Thread Roelof Wobben


 From: keithw...@gmail.com
 Date: Mon, 13 Jan 2014 12:56:45 -0500
 Subject: Re: [Tutor] another better way to do this ?
 To: rwob...@hotmail.com
 CC: tutor@python.org
 
 On Mon, Jan 13, 2014 at 1:14 AM, Roelof Wobben rwob...@hotmail.com wrote:
  I have read all comments and im a little bit confused.
  About which script are we talkimng about. I have seen a lot.
 
 
 I am talking about the script/approach I posted. Others have posted
 other scripts. Hopefully you have the capacity, with whatever approach
 to reading email you have, to go back and look over messages?
 
 There is some confusion because your original message specified that
 order was important, though the examples you gave did not indicate
 that (in fact, contradicted it). Also, there was never anything
 specified about repeated letters: what would be the result of
 fix_machine(letr, letter) (not to be confused with
 fix_machine(letter, letr), which would definitely be letr).
 
 -- 
 Keith

Oke, 

I think you mean this script :

def fix_machine(debris, product):
index = 0
for letter in product:
test = debris.find(letter, index)
if test!= -1:
index = test
else:   # Failure
return Give me something that's not useless next time.
return product   # Success
  ___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] another better way to do this ?

2014-01-12 Thread Roelof Wobben
Hello, 
 
Here is the whole exercise with examples. 
 
# By Sam the Great from forums
# That freaking superhero has been frequenting Udacity
# as his favorite boss battle fight stage. The 'Udacity'
# banner keeps breaking, and money is being wasted on
# repairs. This time, we need you to proceduralize the
# fixing process by building a machine to automatically
# search through debris and return the 'Udacity' banner
# to the company, and be able to similarly fix other goods.
# Write a Python procedure fix_machine to take 2 string inputs
# and returns the 2nd input string as the output if all of its
# characters can be found in the 1st input string and Give me
# something that's not useless next time. if it's impossible.
# NOTE: # If you are experiencing difficulties taking
# this problem seriously, please refer back to
# Superhero flyby, the prequel, in Problem Set 11.
# TOOLS: # if statement
 # while loop
 # string operations
 # Unit 1 Basics
# BONUS: # 
# 5* #  If you've graduated from CS101,
#  Gold  #  try solving this in one line.
# Stars! #
def fix_machine(debris, product):
### WRITE YOUR CODE HERE ###
### TEST CASES ###
print Test case 1: , fix_machine('UdaciousUdacitee', 'Udacity') == Give me 
something that's not useless next time.
print Test case 2: , fix_machine('buy me dat Unicorn', 'Udacity') == 'Udacity'
print Test case 3: , fix_machine('AEIOU and sometimes y... c', 'Udacity') == 
'Udacity'
print Test case 4: , fix_machine('wsx0-=mttrhix', 't-shirt') == 't-shirt'
 
Roelof

 
 To: tutor@python.org
 From: alan.ga...@btinternet.com
 Date: Sun, 12 Jan 2014 00:45:11 +
 Subject: Re: [Tutor] another better way to do this ?
 
 On 11/01/14 21:24, Roelof Wobben wrote:
 
  I have two strings a and b
 
  Now I have to check if the characters of b are all in a.
  But they do have to be in the same order.
 
 I'm not sure exactly what you mean? Can you give some examples of
 data that pass and that fail the criteria?
 
 Your algorithm below might meet one definition of the spec but
 its not valid code since it uses return but is not a function.
 
  length = len(b)
  start = 1
  while start  length :
 check = a.find (b[start])
 if check == -1 :
   return False
 start = start + 1
  return True
 
 Problems I see are:
 1) you start testing at b[1] not b[0]
 2) you don't check if the letters are in the same sequence in a as in b
 3) you probably could tidy it up using a for loop over b rather than 
 indexing
 
  But according to the site this can be solved in a one-liner.
 
 That depends on the spec.
 And have you covered regular expressions? That is probably one
 way to do a one-liner...
 
 But just because you can do it in one line doesn't mean you
 should. It's better for code to be readable than short.
 
 
 HTH
 -- 
 Alan G
 Author of the Learn to Program web site
 http://www.alan-g.me.uk/
 http://www.flickr.com/photos/alangauldphotos
 
 ___
 Tutor maillist  -  Tutor@python.org
 To unsubscribe or change subscription options:
 https://mail.python.org/mailman/listinfo/tutor
  ___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] another better way to do this ?

2014-01-11 Thread Roelof Wobben
Hello, 
 
I try to learn python by following the audicity page.
 
Now I have the following problem.
 
I have two strings a and b 
 
Now I have to check if the characters of b are all in a.
But they do have to be in the same order. 
 
So I thought about this solution.
 
length = len(b)
start = 1 
while start  length :
  check = a.find (b[start])
  if check == -1 : 
return False 
  start = start + 1 
return True 
 
But according to the site this can be solved in a one-liner. 
 
So can someone give me pointers how this can be done and if my solution can 
work. 
 
Roelof
 
  ___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] why does this not work

2013-04-24 Thread Roelof Wobben

Thanks for all the remarks.

The problem was indeed a missing . at the end.

Roelof

 To: tutor@python.org
 From: alan.ga...@btinternet.com
 Date: Wed, 24 Apr 2013 09:00:36 +0100
 Subject: Re: [Tutor] why does this not work
 
 On 24/04/13 04:27, frederico Batista wrote:
  Dave, you clearly don't know codecademy.
  Please be nice to him.
 
 To be fair to Dave he was very polite and showed the OP all the things 
 that were needed to enable the users of this forum to help him. Very few 
 of us are familiar with codeacademy - indeed until this thread I don't 
 think I've come across it before. I certainly didn't know it
 had its own runtime environment.
 
  Also, I recommend the codecademy forums. They have a lot of material
  about every exercise.
 
 Posting in the most specific forum is always best so if the issue is 
 with codeacademy that would be the best place. But I guess it would be 
 hard for the OP to figure out if his problem is with Python or with 
 Codeacademy...
 
  Wrong?
  1) your message is in html, not text.  So the formatting is messy.
It could have been worse, so please learn how to make your email
  program behave.
  2) You didn't show your whole program.  If this is all you have in
  the file, then nothing will print because nothing calls your function.
  3) You didn't describe your environment, including python version 
  OS.  And if Oscar's conjecture is correct, all bets are off because
  most of us won't be familiar with the strange environment.
  4) I can't see how you could possibly get the message:
  'It looks like output other than yes/no does not return Sorry, I
  didn\'t understand you.'  And in fact the last part of the message
  is different than the literal in the program, so you've got a typo
  besides.  Please use cutpaste to show your actual code, your actual
  output.
 
  After reading oscar's comment, my guess is that codeacademy (not
  Python) is complaining about the period at the end of your last
  literal string.
 
  --
  DaveA
 
 -- 
 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 maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] why does this not work

2013-04-23 Thread Roelof Wobben
Im trying to learn python by a course at codeacademy. Now I have this code : 
def shut_down(s):
s = s.lower()
if s == yes:
return Shutting down...
elif s == no :
return Shutdown aborted!
else:
return Sorry, I didn't understand you
But when I run it  I see this message: It looks like output other than 
yes/no does not return 
Sorry, I didn't understand you. So can anyone explain to me what I did wrong. 
Roelof___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] join question

2010-10-15 Thread Roelof Wobben

Hello, 
 
Solved it.
 
Problem was that I used fileinfo instead of getinfo.
 
Thanks for the help.
 
Roelof
 
 
 
 
 Date: Thu, 14 Oct 2010 18:55:50 -0400
 From: joel.goldst...@gmail.com
 To: tutor@python.org
 Subject: Re: [Tutor] join question



 On Thu, Oct 14, 2010 at 6:43 PM, Alan Gauld
  wrote:

 Roelof Wobben  wrote



 print ''.join([zf.getinfo('%s.txt' % p).comment for p in zpp])

 So I thought that this would be the same :

 for p in zpp:
 test = zf.getinfo(p).comment
 print ''.join(test)

 But it seems not to work

 Can anyone explain why not ?

 Because it's not the same. test in your version is only a single item.
 In the original its a list of items. So to write similar code
 explicitly you need:

 lst = []

 for p in zpp:
 test = zf.getinfo(p).comment
 lst.append(test)
 print ''.join(lst)

 HTH,

 Alan G.


 There are two problems. Alan shows the solution to the joining of each
 element of the list, but also you need to have the correct argument for
 getinfo. In your first example you append .txt to p, but in the loop
 example you fail to append it. See my earlier post

 --
 Joel Goldstick


 ___ 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


[Tutor] urllib problem

2010-10-12 Thread Roelof Wobben


Hoi, 
 
I have this programm :
 
import urllib
import re
f = 
urllib.urlopen(http://www.pythonchallenge.com/pc/def/linkedlist.php?nothing=6;)
inhoud = f.read()
f.close()
nummer = re.search('[0-9]', inhoud)
volgende = int(nummer.group())
teller = 1 
while teller = 3 :
  url = http://www.pythonchallenge.com/pc/def/linkedlist.php?nothing=; + 
str(volgende)
  f = urllib.urlopen(url)
  inhoud = f.read()
  f.close()
  nummer = re.search('[0-9]', inhoud)
  print nummer is, nummer.group()
  volgende = int(nummer.group())
  print volgende
  teller = teller + 1
 
but now the url changes but volgende not.
 
What do I have done wrong ?
 
Roelof 
  
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] urllib problem

2010-10-12 Thread Roelof Wobben




 From: st...@pearwood.info
 To: tutor@python.org
 Date: Tue, 12 Oct 2010 23:58:03 +1100
 Subject: Re: [Tutor] urllib problem

 On Tue, 12 Oct 2010 11:40:17 pm Roelof Wobben wrote:
 Hoi,

 I have this programm :

 import urllib
 import re
 f =
 urllib.urlopen(http://www.pythonchallenge.com/pc/def/linkedlist.php?
nothing=6) inhoud = f.read()
 f.close()
 nummer = re.search('[0-9]', inhoud)
 volgende = int(nummer.group())
 teller = 1
 while teller = 3 :
 url =
 http://www.pythonchallenge.com/pc/def/linkedlist.php?nothing=; +
 str(volgende) f = urllib.urlopen(url)
 inhoud = f.read()
 f.close()
 nummer = re.search('[0-9]', inhoud)
 print nummer is, nummer.group()
 volgende = int(nummer.group())
 print volgende
 teller = teller + 1

 but now the url changes but volgende not.
 What do I have done wrong ?

 Each time through the loop, you set volgende to the same result:

 nummer = re.search('[0-9]', inhoud)
 volgende = int(nummer.group())

 Since inhoud never changes, and the search never changes, the search
 result never changes, and volgende never changes.



 --
 Steven D'Aprano
 ___
 Tutor maillist - Tutor@python.org
 To unsubscribe or change subscription options:
 http://mail.python.org/mailman/listinfo/tutor
 
 
Hello, 
 
Here is the output when I print every step in the beginning :
 
inhoud : and the next nothing is 87599
nummer is 8
volgende is  8
 
and here is the output in the loop :
 
 
url is: http://www.pythonchallenge.com/pc/def/linkedlist.php?nothing=8
inhoud is and the next nothing is 59212
nummer is 5

 
2ste run:
url is: http://www.pythonchallenge.com/pc/def/linkedlist.php?nothing=5
inhoud is and the next nothing is 51716
nummer is 5

3ste run:
url is: http://www.pythonchallenge.com/pc/def/linkedlist.php?nothing=5
inhoud is and the next nothing is 51716
nummer is 5

4ste run:

I see the problem. It only takes the first number of the nothing.
So I have to look how to solve that.
 
Roelof

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


Re: [Tutor] urllib problem

2010-10-12 Thread Roelof Wobben




 From: st...@pearwood.info
 To: tutor@python.org
 Date: Wed, 13 Oct 2010 01:51:16 +1100
 Subject: Re: [Tutor] urllib problem

 On Tue, 12 Oct 2010 11:58:03 pm Steven D'Aprano wrote:
  On Tue, 12 Oct 2010 11:40:17 pm Roelof Wobben wrote:
   Hoi,
  
   I have this programm :
  
   import urllib
   import re
   f =
   urllib.urlopen(http://www.pythonchallenge.com/pc/def/linkedlist.ph
  p? nothing=6) inhoud = f.read()
   f.close()
   nummer = re.search('[0-9]', inhoud)
   volgende = int(nummer.group())
   teller = 1
   while teller = 3 :
   url =
   http://www.pythonchallenge.com/pc/def/linkedlist.php?nothing=; +
   str(volgende) f = urllib.urlopen(url)
   inhoud = f.read()
   f.close()
   nummer = re.search('[0-9]', inhoud)
   print nummer is, nummer.group()
   volgende = int(nummer.group())
   print volgende
   teller = teller + 1
  
   but now the url changes but volgende not.
   What do I have done wrong ?
 
  Each time through the loop, you set volgende to the same result:
 
  nummer = re.search('[0-9]', inhoud)
  volgende = int(nummer.group())
 
  Since inhoud never changes, and the search never changes, the search
  result never changes, and volgende never changes.

 Wait, sorry, inhoud should change... I missed the line inhoud = f.read()

 My mistake, sorry about that. However, I can now see what is going
 wrong. Your regular expression only looks for a single digit:

 re.search('[0-9]', inhoud)

 If you want any number of digits, you need '[0-9]+' instead.


 Starting from the first URL:

  f = urllib.urlopen(
 ... http://www.pythonchallenge.com/pc/def/linkedlist.php?nothing=6;)
  inhoud = f.read()
  f.close()
  print inhoud
 and the next nothing is 87599


 but:

  nummer = re.search('[0-9]', inhoud)
  nummer.group()
 '8'

 See, you only get the first digit. Then looking up the page with
 nothing=8 gives a first digit starting with 5, and then you get stuck
 on 5 forever:

  urllib.urlopen(
 ... http://www.pythonchallenge.com/pc/def/linkedlist.php?nothing=8;).read()
 'and the next nothing is 59212'
  urllib.urlopen(
 ... http://www.pythonchallenge.com/pc/def/linkedlist.php?nothing=5;).read()
 'and the next nothing is 51716'


 You need to add a + to the regular expression, which means one or more
 digits instead of a single digit.



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

 
Hoi Steven, 
 
Finally solved this puzzle.
Now the next one of the 33 puzzles.
 
Roelof
  
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] pickle problem

2010-10-12 Thread Roelof Wobben


Hello, 
 
I have this code : 
 
import urllib
import pickle
 
image = urllib.URLopener()
image.retrieve(http://www.pythonchallenge.com/pc/def/peak.html,banner.p; )
plaatje = open(banner.p, rb)
plaatje2 = pickle.load(plaatje)
 
But it gives this output :
 
Traceback (most recent call last):
  File C:\Users\wobben\workspace\oefeningen\src\test2.py, line 7, in module
plaatje2 = pickle.load(plaatje)
  File C:\Python27\lib\pickle.py, line 1378, in load
return Unpickler(file).load()
  File C:\Python27\lib\pickle.py, line 858, in load
dispatch[key](self)
KeyError: ''

 
What does this mean ?
 
Roelof
  
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] list of dict question

2010-10-08 Thread Roelof Wobben


Hello, 
 
I have this programm :
 
tournooi = [{'thuis': 'A','uit': B,'thuisscore': 20, 'uitscore': 
15},{'thuis': 'C','uit': D,'thuisscore': 80, 'uitscore': 40}]
stand = []
tussen_thuis = {}
tussen_uit = {}
for wedstrijd in tournooi :
if wedstrijd['thuis'] in stand :
print True
else :
tussen_thuis['ploeg']  = wedstrijd['thuis']
tussen_thuis['wedstrijden'] = 1
if wedstrijd['thuisscore'] wedstrijd['uitscore']:
tussen_thuis['punten'] = 2
else:
tussen_thuis['punten'] = 0 

tussen_thuis['voor'] = wedstrijd['thuisscore']
tussen_thuis ['tegen'] = wedstrijd['uitscore']
stand.append(tussen_thuis)
if wedstrijd['uit'] in stand :
print True
else :
tussen_uit['ploeg']  = wedstrijd['uit']
tussen_uit['wedstrijden'] = 1
if wedstrijd['thuisscore']  wedstrijd['uitscore']:
tussen_uit['punten'] = 2
else:
tussen_uit['punten'] = 0 
tussen_uit['tegen'] = wedstrijd['thuisscore']
tussen_uit ['voor'] = wedstrijd['uitscore']
stand.append(tussen_uit)
 
It gives this output :
 
[{'punten': 2, 'tegen': 40, 'wedstrijden': 1, 'voor': 80, 'ploeg': 'C'}, 
{'punten': 0, 'tegen': 80, 'wedstrijden': 1, 'voor': 40, 'ploeg': 'D'}, 
{'punten': 2, 'tegen': 40, 'wedstrijden': 1, 'voor': 80, 'ploeg': 'C'}, 
{'punten': 0, 'tegen': 80, 'wedstrijden': 1, 'voor': 40, 'ploeg': 'D'}]

 
So the data of A and B are overwriting by C and D.
How can I prevent this ?
 
Roelof
 
 
  
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] list of dict question

2010-10-08 Thread Roelof Wobben




 To: tutor@python.org
 From: alan.ga...@btinternet.com
 Date: Fri, 8 Oct 2010 09:02:05 +0100
 Subject: Re: [Tutor] list of dict question


 Roelof Wobben wrote

 I have this programm :

 tournooi = [{'thuis': 'A','uit': B,'thuisscore': 20, 'uitscore':
 15},{'thuis': 'C','uit': D,'thuisscore': 80, 'uitscore': 40}]
 stand = []
 tussen_thuis = {}
 tussen_uit = {}

 Here you create your dictionary objects.
 You never create any more dictionary objects so these are the only
 ones you have.

 for wedstrijd in tournooi :
 if wedstrijd['thuis'] in stand :
 print True

 stand is a list of dictionaries so this will never be True.

 else :
 tussen_thuis['ploeg'] = wedstrijd['thuis']
 tussen_thuis['wedstrijden'] = 1
 if wedstrijd['thuisscore'] wedstrijd['uitscore']:
 tussen_thuis['punten'] = 2
 else:
 tussen_thuis['punten'] = 0

 tussen_thuis['voor'] = wedstrijd['thuisscore']
 tussen_thuis ['tegen'] = wedstrijd['uitscore']
 stand.append(tussen_thuis)

 Here you append the dictionary into stand

 if wedstrijd['uit'] in stand :
 print True

 But stand is a list with a dictionary inside so this test
 cannot be true since wedstrijg['uit'] is not a dictionary.

 else :
 tussen_uit['ploeg'] = wedstrijd['uit']
 tussen_uit['wedstrijden'] = 1
 if wedstrijd['thuisscore']  wedstrijd['uitscore']:
 tussen_uit['punten'] = 2
 else:
 tussen_uit['punten'] = 0
 tussen_uit['tegen'] = wedstrijd['thuisscore']
 tussen_uit ['voor'] = wedstrijd['uitscore']
 stand.append(tussen_uit)

 Now you append a second dictionary to stand.

 On the next iteration you overwrite those two dictionaries
 with new values then append them to the list again.
 So you wind up with 2 copies of the updated dictionaries.

 So the data of A and B are overwriting by C and D.
 How can I prevent this ?

 You need to create new dictionaries for each iteration of the loop.
 Move the dictionary creation lines inside the loop.

 HTH,


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

 
Hello Alan, 
 
Thank you.
Now i can work on a script which can check if a team exist in standen.
 
Roelof
  
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] FW: list of dict question

2010-10-08 Thread Roelof Wobben




 From: rwob...@hotmail.com
 To: f...@libero.it
 Subject: RE: [Tutor] list of dict question
 Date: Fri, 8 Oct 2010 14:53:53 +




 
 Date: Fri, 8 Oct 2010 13:40:04 +0200
 From: f...@libero.it
 To: tutor@python.org
 Subject: Re: [Tutor] list of dict question


 Il 08/10/2010 10.02, Alan Gauld ha scritto:

 Roelof Wobben wrote

 I have this programm :

 tournooi = [{'thuis': 'A','uit': B,'thuisscore': 20, 'uitscore':
 ...
 for wedstrijd in tournooi :
 if wedstrijd['thuis'] in stand :
 print True

 stand is a list of dictionaries so this will never be True.
...
 if wedstrijd['uit'] in stand :
 print True

 But stand is a list with a dictionary inside so this test
 cannot be true since wedstrijg['uit'] is not a dictionary.

 I'll say the same another way: you are searching an apple in a container
 of baskets, one of which MAY CONTAIN an apple. But you only see baskets,
 and none of those can BE an apple!
 My two cents: the following might be still new for you, but this is a
 way to check if wedstrijd['thuis'] is in stand:

 if wedstrijd['thuis'] in [u['ploeg'] for u in stand]

 where you build a temporary list of 'ploeg's in stand and check whether
 wedstrijd['thuis'] is found there.

...
 On the next iteration you overwrite those two dictionaries
 with new values then append them to the list again.
 So you wind up with 2 copies of the updated dictionaries.
 ...
 This is difficult for me too: why does this happen? Or, more correctly,
 why should this happen? How can you save the current contents of a
 dictionary in a list, making sure that the saved values won't change if
 you update the dict?
 You tell Roelof that the dictionary must be created at every loop, but
 if so, where goes the elegance of
 myDictList.append(UpdateIt(myDict))
 ???

 Francesco (puzzled)

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


Hello Franceso,

Thank you for the answer.

Now find ot how i can find the dict which contains a team.
I thinking now of something like this.

teller = 1
  For wedstrijd in tournooi :
if wedstrijd['thuis'] != stand ['ploeg'] :
teller = teller + 1
stand[teller]['wedstrijd'] += 1

Could this work ?

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


[Tutor] data question

2010-10-02 Thread Roelof Wobben


Hello, 
 
As a test I would write a programm where a user can input game-data like 
home-team, away-team, home-score, away-score) and makes a ranking of it. And 
I'm not looking of a OOP solution because im not comfertle with OOP.
 
Now my question is :
 
In which datatype can I put this data in.
 
I thought myself of a dictonary of tuples.
 
Regards,
 
Roelof
  
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] data question

2010-10-02 Thread Roelof Wobben




 From: rwob...@hotmail.com
 To: berma...@cfl.rr.com
 Subject: RE: [Tutor] data question
 Date: Sat, 2 Oct 2010 13:09:23 +




 
 From: berma...@cfl.rr.com
 To: rwob...@hotmail.com; tutor@python.org
 Subject: RE: [Tutor] data question
 Date: Sat, 2 Oct 2010 09:02:41 -0400



 -Original Message-
 From: tutor-bounces+bermanrl=cfl.rr@python.org [mailto:tutor-
 bounces+bermanrl=cfl.rr@python.org] On Behalf Of Roelof Wobben
 Sent: Saturday, October 02, 2010 4:35 AM
 To: tutor@python.org
 Subject: [Tutor] data question



 Hello,

 Now my question is :

 In which datatype can I put this data in.

 Perhaps a simple SQLlite database?
 http://zetcode.com/databases/sqlitetutorial/

 Hope this helps,

 Robert



 Regards,

 Roelof

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


Oke,

Oke, there I can save the input data.
But I have also need a data model for team, played_games, game_points, 
made_points and againts_points.
So I think it cannot be done without using a class for games and one for 
ranking.
And figuring out how I can store the game-data in a text or database file.

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


Re: [Tutor] data question

2010-10-02 Thread Roelof Wobben




 To: tutor@python.org
 From: alan.ga...@btinternet.com
 Date: Sat, 2 Oct 2010 14:10:25 +0100
 Subject: Re: [Tutor] data question


 Roelof Wobben wrote

 As a test I would write a programm where a user can input game-data
 like home-team, away-team, home-score, away-score) and makes a
 ranking of it.

 In which datatype can I put this data in.

 I thought myself of a dictonary of tuples.

 A dictionary would be good for the basic data but I assume there
 are more than one of these data items? If so what do they represent?
 How would they be used?

 We need a bit more information, even some sample datya might help.

 It could be a list of dictionaries or even a dictionary of
 dictionaries.

 Alan G.


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

Hello Alan, 

What I meant was this:
 
Let's say we have a tournament of 4 teams A,B,C,D
 
They played this games.
 
A - B  20 - 30 
C - D  23 - 67 
 
These data must be stored so I can make a module which make a ranking like this 
:
 
1) C   1 - 2  76 - 23 
2) B   1 - 2   30 - 20
 
I hope you know what I wan
 
 
Roelof
  
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] data question

2010-10-02 Thread Roelof Wobben

hello, 
 
Still one question.
 
Every game is a dictonary/tuple ?
 
Regards,
 
Roelof


 Date: Sat, 2 Oct 2010 06:24:16 -0700
 From: alan.ga...@btinternet.com
 Subject: Re: [Tutor] data question
 To: rwob...@hotmail.com

 OK, So you want a list of games (possibly one per tournament
 if you need to compare across tournies) where for each game
 you store: homeTeam, awayTeam and scores.

 Each game could be represented as either a tuple or a dictionary
 depending on how you want to extract the data:

 game['home'] or game[0]

 The list should probably be a list... :-)

 Try defining a short sample database in Python then try
 extracting some values to get a feel for what suits you
 best. Create the data in a module(easier to edit mistakes/changes)
 Then use the prompt to import the data module and play
 around with it.

 That way it's easy to change from lists to tuples to dictionaries
 and see what works.

 Ultimately this may even be best done using a database but
 that's probably a step too far for you just now.

 Alan Gauld
 Author of the Learn To Program website
 http://www.alan-g.me.uk/




 - Original Message 
 From: Roelof Wobben 
 To: alan.ga...@btinternet.com; tutor@python.org
 Sent: Saturday, 2 October, 2010 14:15:33
 Subject: RE: [Tutor] data question




 
 To: tutor@python.org
 From: alan.ga...@btinternet.com
 Date: Sat, 2 Oct 2010 14:10:25 +0100
 Subject: Re: [Tutor] data question


 Roelof Wobben wrote

 As a test I would write a programm where a user can input game-data
 like home-team, away-team, home-score, away-score) and makes a
 ranking of it.

 In which datatype can I put this data in.

 I thought myself of a dictonary of tuples.

 A dictionary would be good for the basic data but I assume there
 are more than one of these data items? If so what do they represent?
 How would they be used?

 We need a bit more information, even some sample datya might help.

 It could be a list of dictionaries or even a dictionary of
 dictionaries.

 Alan G.


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

 Hello Alan,

 What I meant was this:

 Let's say we have a tournament of 4 teams A,B,C,D

 They played this games.

 A - B 20 - 30
 C - D 23 - 67

 These data must be stored so I can make a module which make a ranking like
this :

 1) C 1 - 2 76 - 23
 2) B 1 - 2 30 - 20

 I hope you know what I wan


 Roelof

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


Re: [Tutor] data question

2010-10-02 Thread Roelof Wobben


Hello Alan, 
 
I think this is what can work : http://www.daniweb.com/code/snippet216750.html
 
I will try it.
 
 
Roelof


 From: rwob...@hotmail.com
 To: alan.ga...@btinternet.com; tutor@python.org
 Subject: RE: [Tutor] data question
 Date: Sat, 2 Oct 2010 13:40:21 +


 hello,

 Still one question.

 Every game is a dictonary/tuple ?

 Regards,

 Roelof

 
 Date: Sat, 2 Oct 2010 06:24:16 -0700
 From: alan.ga...@btinternet.com
 Subject: Re: [Tutor] data question
 To: rwob...@hotmail.com

 OK, So you want a list of games (possibly one per tournament
 if you need to compare across tournies) where for each game
 you store: homeTeam, awayTeam and scores.

 Each game could be represented as either a tuple or a dictionary
 depending on how you want to extract the data:

 game['home'] or game[0]

 The list should probably be a list... :-)

 Try defining a short sample database in Python then try
 extracting some values to get a feel for what suits you
 best. Create the data in a module(easier to edit mistakes/changes)
 Then use the prompt to import the data module and play
 around with it.

 That way it's easy to change from lists to tuples to dictionaries
 and see what works.

 Ultimately this may even be best done using a database but
 that's probably a step too far for you just now.

 Alan Gauld
 Author of the Learn To Program website
 http://www.alan-g.me.uk/




 - Original Message 
 From: Roelof Wobben
 To: alan.ga...@btinternet.com; tutor@python.org
 Sent: Saturday, 2 October, 2010 14:15:33
 Subject: RE: [Tutor] data question




 
 To: tutor@python.org
 From: alan.ga...@btinternet.com
 Date: Sat, 2 Oct 2010 14:10:25 +0100
 Subject: Re: [Tutor] data question


 Roelof Wobben wrote

 As a test I would write a programm where a user can input game-data
 like home-team, away-team, home-score, away-score) and makes a
 ranking of it.

 In which datatype can I put this data in.

 I thought myself of a dictonary of tuples.

 A dictionary would be good for the basic data but I assume there
 are more than one of these data items? If so what do they represent?
 How would they be used?

 We need a bit more information, even some sample datya might help.

 It could be a list of dictionaries or even a dictionary of
 dictionaries.

 Alan G.


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

 Hello Alan,

 What I meant was this:

 Let's say we have a tournament of 4 teams A,B,C,D

 They played this games.

 A - B 20 - 30
 C - D 23 - 67

 These data must be stored so I can make a module which make a ranking like
this :

 1) C 1 - 2 76 - 23
 2) B 1 - 2 30 - 20

 I hope you know what I wan


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


Re: [Tutor] inheritance problem

2010-10-01 Thread Roelof Wobben




 To: tutor@python.org
 From: alan.ga...@btinternet.com
 Date: Fri, 1 Oct 2010 00:59:06 +0100
 Subject: Re: [Tutor] inheritance problem

 Roelof Wobben wrote

 So i have this programm now :

 class Deck:
 def __init__(self):
 self.cards = []
 for suit in range(4):
 for rank in range(1, 14):
 self.cards.append(Card(suit, rank))

 def deal(self, hands, num_cards=999):
 num_hands = len(hands)
 for i in range(num_cards):
 if self.is_empty(): break # break if out of cards
 card = self.pop() # take the top card
 hand = hands[i % num_hands] # whose turn is next?
 hand.add(card) # add the card to the hand

 def shuffle(self):
 import random
 num_cards = len(self.cards)
 for i in range(num_cards):
 j = random.randrange(i, num_cards)
 self.cards[i], self.cards[j] = self.cards[j],
 self.cards[i]

 def remove(self, card):
 if card in self.cards:
 self.cards.remove(card)
 return True
 else:
 return False
 def is_empty(self):
 return (len(self.cards) == 0)

 But now Im getting this error message:

 Traceback (most recent call last):
 File C:\Users\wobben\workspace\oefeningen\src\test.py, line 126,
 in 
 game.deck.deal([hand], 13)
 File C:\Users\wobben\workspace\oefeningen\src\test.py, line 24,
 in deal
 card = self.pop() # take the top card
 AttributeError: Deck instance has no attribute 'pop'


 What went wrong here.

 The error tells you what is wrong, the Deck has no attribute called
 pop.
 Can you see a pop anywhere?
 
I only see a pop here : card = self.pop() # take the top card
but no function called pop.
 

 So if the code you copied has an error how should it assign a card?

 
I assigned a card by this code :
 
def deal(self, hands, num_cards=999):
  num_hands = len(hands)
  for i in range(num_cards):
   if self.is_empty(): break # break if out of cards
   card = self.pop() # take the top card
   hand = hands[i % num_hands] # whose turn is next?
   hand.add(card) # add the card to the hand

 
 
 Where are the cards stored? How would you get the first card from
 the collection? Does that work?

The cards are stored in a directory named cards.
The hands are stored in a directory named hands
 

 Think about what the error is telling you and think about how you
 would fix it. If you don't understand what the error is saying then
 tell
 us and we can explain it, but in this case its pretty clearly stated
 and is one you have seen before.

 
The error is telling me that the function pop does not exist for a directory,
So solution is to find out which object contains pop and then change the code.
  
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] inheritance problem

2010-10-01 Thread Roelof Wobben




 From: rwob...@hotmail.com
 To: alan.ga...@btinternet.com; tutor@python.org
 Date: Fri, 1 Oct 2010 06:19:29 +
 Subject: Re: [Tutor] inheritance problem




 
 To: tutor@python.org
 From: alan.ga...@btinternet.com
 Date: Fri, 1 Oct 2010 00:59:06 +0100
 Subject: Re: [Tutor] inheritance problem

 Roelof Wobben wrote

 So i have this programm now :

 class Deck:
 def __init__(self):
 self.cards = []
 for suit in range(4):
 for rank in range(1, 14):
 self.cards.append(Card(suit, rank))

 def deal(self, hands, num_cards=999):
 num_hands = len(hands)
 for i in range(num_cards):
 if self.is_empty(): break # break if out of cards
 card = self.pop() # take the top card
 hand = hands[i % num_hands] # whose turn is next?
 hand.add(card) # add the card to the hand

 def shuffle(self):
 import random
 num_cards = len(self.cards)
 for i in range(num_cards):
 j = random.randrange(i, num_cards)
 self.cards[i], self.cards[j] = self.cards[j],
 self.cards[i]

 def remove(self, card):
 if card in self.cards:
 self.cards.remove(card)
 return True
 else:
 return False
 def is_empty(self):
 return (len(self.cards) == 0)

 But now Im getting this error message:

 Traceback (most recent call last):
 File C:\Users\wobben\workspace\oefeningen\src\test.py, line 126,
 in
 game.deck.deal([hand], 13)
 File C:\Users\wobben\workspace\oefeningen\src\test.py, line 24,
 in deal
 card = self.pop() # take the top card
 AttributeError: Deck instance has no attribute 'pop'


 What went wrong here.

 The error tells you what is wrong, the Deck has no attribute called
 pop.
 Can you see a pop anywhere?

 I only see a pop here : card = self.pop() # take the top card
 but no function called pop.


 So if the code you copied has an error how should it assign a card?


 I assigned a card by this code :

 def deal(self, hands, num_cards=999):
 num_hands = len(hands)
 for i in range(num_cards):
 if self.is_empty(): break # break if out of cards
 card = self.pop() # take the top card
 hand = hands[i % num_hands] # whose turn is next?
 hand.add(card) # add the card to the hand



 Where are the cards stored? How would you get the first card from
 the collection? Does that work?

 The cards are stored in a directory named cards.
 The hands are stored in a directory named hands


 Think about what the error is telling you and think about how you
 would fix it. If you don't understand what the error is saying then
 tell
 us and we can explain it, but in this case its pretty clearly stated
 and is one you have seen before.


 The error is telling me that the function pop does not exist for a directory,
 So solution is to find out which object contains pop and then change the code.

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

 
Hello, 
 
I make a big mistake.
Both card and hands are lists and pop can be used on a list.
So as Joel said in this rule card = self.pop() there is no list named so I 
think it must be self.hands.pop()
 
Roelof
  
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] inheritance problem

2010-10-01 Thread Roelof Wobben




 I assigned a card by this code :

 def deal(self, hands, num_cards=999):
 num_hands = len(hands)
 for i in range(num_cards):
 if self.is_empty(): break # break if out of cards
 card = self.pop() # take the top card
 hand = hands[i % num_hands] # whose turn is next?
 hand.add(card) # add the card to the hand


 No this code assigns several HANDS not just cards.
 The code that assigns a card is inside this function, but
 you need to narrow it down to the specific lines assigning the card.

 
Oke, 
 
The lines that assign card is :
 
hand = hands[i % num_hands] # whose turn is next?
hand.add(card) # add the card to the hand
 
The first one takes care to who a card is assigned and the second one assigned 
it to that person.
 

 Where are the cards stored? How would you get the first card from
 the collection? Does that work?

 The cards are stored in a directory named cards.

 Correct. So how do you get a card from the collection stored
 in self.cards?
 
 
This is not correct. Card is a list and not a directory. See this : self.cards 
= []
 

 I make a big mistake.
 Both card and hands are lists and pop can be used on a list.

 That's not a mistake, lists are objects too.

oke, but I confused two objects and that is a mistake.
 
 
 

 So as Joel said in this rule card = self.pop() there is no list
 named so I think it must be self.hands.pop()

 If you want to assign a card and cards are stored in self.cards
 why would you use self.hands.pop()?
 Surely it should be self.cards.pop()?

 
It is.
I know that because self.hands is not working.
 
 
Now Im busy to make this difficult exercise of writing print_hands()
But thanks for the time and explantion.
OOP is difficult to understand I find.
 
 
Roelof
  
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] inheritance problem

2010-09-30 Thread Roelof Wobben

hello, 

Im following this page : 
http://openbookproject.net/thinkcs/python/english2e/ch17.html

So i have this programm now : 
class Card:
suits = [Clubs, Diamonds, Hearts, Spades]
ranks = [narf, Ace, 2, 3, 4, 5, 6, 7,
 8, 9, 10, Jack, Queen, King]
def __init__(self, suit=0, rank=0):
self.suit = suit
self.rank = rank
def __str__(self):
return (self.ranks[self.rank] +  of  + self.suits[self.suit])
class Deck:
def __init__(self):
self.cards = []
for suit in range(4):
for rank in range(1, 14):
self.cards.append(Card(suit, rank))

def deal(self, hands, num_cards=999):
num_hands = len(hands)
for i in range(num_cards):
if self.is_empty(): break   # break if out of cards
card = self.pop()   # take the top card
hand = hands[i % num_hands] # whose turn is next?
hand.add(card)  # add the card to the hand

def shuffle(self):
import random
num_cards = len(self.cards)
for i in range(num_cards):
j = random.randrange(i, num_cards)
self.cards[i], self.cards[j] = self.cards[j], self.cards[i]

def remove(self, card):
if card in self.cards:
self.cards.remove(card)
return True
else:
return False
def is_empty(self):
return (len(self.cards) == 0)
class Hand(Deck):
def __init__(self, name=):
   self.cards = []
   self.name = name
def add(self,card):
self.cards.append(card)
def deal(self, hands, num_cards=999):
num_hands = len(hands)
for i in range(num_cards):
if self.is_empty(): break   # break if out of cards
card = self.pop()   # take the top card
hand = hands[i % num_hands] # whose turn is next?
hand.add(card)  # add the card to the hand
class CardGame:
def __init__(self):
self.deck = Deck()
self.deck.shuffle()

class OldMaidHand(Hand):
def remove_matches(self):
count = 0
original_cards = self.cards[:]
for card in original_cards:
match = Card(3 - card.suit, card.rank)
if match in self.cards:
self.cards.remove(card)
self.cards.remove(match)
print Hand %s: %s matches %s % (self.name, card, match)
count = count + 1
return count
class OldMaidGame(CardGame):
def play(self, names):
# remove Queen of Clubs
self.deck.remove(Card(0,12))
# make a hand for each player
self.hands = []
for name in names:
self.hands.append(OldMaidHand(name))
# deal the cards
self.deck.deal(self.hands)
print -- Cards have been dealt
self.printHands()
# remove initial matches
matches = self.removeAllMatches()
print -- Matches discarded, play begins
self.printHands()
# play until all 50 cards are matched
turn = 0
numHands = len(self.hands)
while matches  25:
matches = matches + self.playOneTurn(turn)
turn = (turn + 1) % numHands
print -- Game is Over
self.printHands()
def remove_all_matches(self):
count = 0
for hand in self.hands:
count = count + hand.remove_matches()
return count
def find_neighbor(self, i):
numHands = len(self.hands)
for next in range(1,numHands):
neighbor = (i + next) % numHands
if not self.hands[neighbor].is_empty():
return neighbor

game = CardGame()
hand = OldMaidHand(frank)
deck = Deck()
game.deck.deal([hand], 13)
OldMaidHand.print_hands() 
 
But now Im getting this error message:
 
Traceback (most recent call last):
  File C:\Users\wobben\workspace\oefeningen\src\test.py, line 126, in module
game.deck.deal([hand], 13)
  File C:\Users\wobben\workspace\oefeningen\src\test.py, line 24, in deal
card = self.pop()   # take the top card
AttributeError: Deck instance has no attribute 'pop'

 
What went wrong here.
 
Roelof
 
 
 
 

 
 

 

 



 
 
 



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


[Tutor] question

2010-09-28 Thread Roelof Wobben

Hello,


Im now studying this page :
http://openbookproject.net/thinkcs/python/english2e/ch16.html

But I don't get it why aces are now lower then deuces in the  cmp function.


Roelof

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


Re: [Tutor] question

2010-09-28 Thread Roelof Wobben


 


From: rwob...@hotmail.com
To: da...@ieee.org
Subject: RE: [Tutor] question
Date: Tue, 28 Sep 2010 14:22:17 +





 
 Date: Tue, 28 Sep 2010 10:02:27 -0400
 From: da...@ieee.org
 To: rwob...@hotmail.com
 CC: tutor@python.org
 Subject: Re: [Tutor] question
 
 
 
 On 2:59 PM, Roelof Wobben wrote:
  Hello,
 
 
  Im now studying this page :
  http://openbookproject.net/thinkcs/python/english2e/ch16.html
 
  But I don't get it why aces are now lower then deuces in the cmp function.
 
 
  Roelof
 
  
 Why would you be surprised that aces are lower than deuces? If aces are 
 represented by 1, and deuces by 2, then 1 is less than 2.
 
 Notice that because self.suit is compared first, an ace of spades is 
 higher than a deuce of hearts. It's only within the same suit that an 
 ace is less than a deuce.
 
 DaveA
 
 
 
 

Hello Dave, 
 
In some games in the Netherlands Aces can have a value of 11 or 1 .
So if Aces are 11 then Deuces is lesser then Aces.
 
Can I say that the position of the list is a representation of the value.
 
Roelof
 
  ___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] question

2010-09-28 Thread Roelof Wobben


 


From: rwob...@hotmail.com
To: da...@ieee.org
Subject: RE: [Tutor] question
Date: Tue, 28 Sep 2010 19:14:29 +





 
 Date: Tue, 28 Sep 2010 10:49:28 -0400
 From: da...@ieee.org
 To: rwob...@hotmail.com; tutor@python.org
 Subject: Re: [Tutor] question
 
 On 9/28/2010 10:22 AM, Roelof Wobben wrote:
 
 
 
  Date: Tue, 28 Sep 2010 10:02:27 -0400
  From: da...@ieee.org
  To: rwob...@hotmail.com
  CC: tutor@python.org
  Subject: Re: [Tutor] question
 
 
 
  On 2:59 PM, Roelof Wobben wrote:
  Hello,
 
 
  Im now studying this page :
  http://openbookproject.net/thinkcs/python/english2e/ch16.html
 
  But I don't get it why aces are now lower then deuces in the cmp function.
 
 
  Roelof
 
 
  Why would you be surprised that aces are lower than deuces? If aces are
  represented by 1, and deuces by 2, then 1 is less than 2.
 
  Notice that because self.suit is compared first, an ace of spades is
  higher than a deuce of hearts. It's only within the same suit that an
  ace is less than a deuce.
 
  DaveA
 
 
 
 
 
  Hello Dave,
 
 
 
  In some games in the Netherlands Aces can have a value of 11 or 1 .
 
  So if Aces are 11 then Deuces is lesser then Aces.
 
 
 
  Can I say that the position of the list is a representation of the value.
 
 
 
  Roelof
 
 
  
 The class attribute was assigned as follows:
 
 ranks = [narf, Ace, 2, 3, 4, 5, 6, 7,
 8, 9, 10, Jack, Queen, King]
 
 
 So Ace is at position 1. And if you want an Ace, you'd have to supply a 1 
 to the constructor.
 
 I would certainly agree that in many games this wouldn't be the desired case. 
 Some games specify aces higher than kings, some have no ordering among face 
 cards, some let the player choose.
 
 If the Card class needed to cover all cases, then one might need to make the 
 __cmp__() method parameterizable, so that at different times, the cards might 
 sort differently.
 
 But this is one implementation of the Card class, and hopefully it's 
 self-consistent in the course.
 
 
 
 DaveA
 
 
 
  
 
 
Oke,
 
Thanks.
Then now figuring out how to solve this problem :
 
Modify __cmp__ so that Aces are ranked higher than Kings
 
So aces with value 1 must be higher then Kings with 11 
 
I think I have to make another rule in the rank part like this 
 
If self.rank = Aces and self.rank = Kings then return -1 or 1
 
Tomorrrow I will investigate this. 
 
Roelof

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


Re: [Tutor] class method problem

2010-09-27 Thread Roelof Wobben


Hello, 
 
Fine that you are in a arque
But can we come back to my problem.
 
How can I take care that test2 can be initialized.
 
Roelof

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


[Tutor] class method problem

2010-09-25 Thread Roelof Wobben


Hello, 
 
I have this code:
 
class zoeken() :
pass
def __len__(self):
return 0 
def __str__(self):
return test2
def find(self, strng, ch, start, stop):
index = start
while index  len(strng) and index  stop:
if strng[index] == ch:
return index
index += 1
return -1


test = zoeken()
test.woord = tamara
test2 = zoeken.find(test, a, 1,5)
print test(test2)
 
But now I get this message :
 
Traceback (most recent call last):
  File C:\Users\wobben\workspace\oefeningen\src\test.py, line 20, in module
test2 = zoeken.find(test, a, 1,5)
TypeError: find() takes exactly 5 arguments (4 given)
 
I can do zoeken.find (test2,test, a, 1,5) but then I get this message:
 
Traceback (most recent call last):
  File C:\Users\wobben\workspace\oefeningen\src\test.py, line 20, in module
zoeken.find( test2, test, a, 1,5)
NameError: name 'test2' is not defined
 
 
Roelof
  
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] class method problem

2010-09-25 Thread Roelof Wobben


Hello,

Still the same errors

Roelof


 
 Date: Sat, 25 Sep 2010 19:33:52 +0100
 Subject: Re: [Tutor] class method problem
 From: andre...@gmail.com
 To: rwob...@hotmail.com

 Your method receives 4 arguments and you didn't define one default.
 Try to do something like this:

 def find(self, strng=None, ch=None, start=None, stop=None):

 Or any other default values that matches your needs.



 On 25 September 2010 19:15, Roelof Wobben wrote:


 Hello,

 I have this code:

 class zoeken() :
 á ápass
 á ádef __len__(self):
 á á á áreturn 0
 á ádef __str__(self):
 á á á áreturn test2
 á ádef find(self, strng, ch, start, stop):
 á á á áindex = start
 á á á áwhile index  len(strng) and index  stop:
 á á á á á áif strng[index] == ch:
 á á á á á á á áreturn index
 á á á á á áindex += 1
 á á á á á áreturn -1


 test = zoeken()
 test.woord = tamara
 test2 = zoeken.find(test, a, 1,5)
 print test(test2)

 But now I get this message :

 Traceback (most recent call last):
 áFile C:\Users\wobben\workspace\oefeningen\src\test.py, line 20, in
 á átest2 = zoeken.find(test, a, 1,5)
 TypeError: find() takes exactly 5 arguments (4 given)

 I can do zoeken.find (test2,test, a, 1,5) but then I get this message:

 Traceback (most recent call last):
 áFile C:\Users\wobben\workspace\oefeningen\src\test.py, line 20, in
 á ázoeken.find( test2, test, a, 1,5)
 NameError: name 'test2' is not defined


 Roelof

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




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


Re: [Tutor] pure function problem

2010-09-24 Thread Roelof Wobben




 Date: Fri, 24 Sep 2010 06:29:03 -0400
 From: da...@ieee.org
 To: rwob...@hotmail.com
 CC: tutor@python.org
 Subject: Re: [Tutor] pure function problem

 On 2:59 PM, Roelof Wobben wrote:


 
 From: st...@pearwood.info
 
 On Fri, 24 Sep 2010 06:20:25 am Roelof Wobben wrote:

 time =ijd()
 [...]
 print time(uitkomst)
 Why are you calling time as a function, when it is a tijd instance?

 

 Hello Steve,

 I found this in my tutorial.

 13.8. Instances as return values¶
 Functions can return instances. For example, find_center takes a Rectangle 
 as an argument and returns a Point that contains the coordinates of the 
 center of the Rectangle:
 def find_center(box):
 p =oint()
 p.x =ox.corner.x + box.width/2.0
 p.y =ox.corner.y - box.height/2.0
 return p
 To call this function, pass box as an argument and assign the result to a 
 variable:
 center =ind_center(box)
 print_point(center)
 (50.0, 100.0)


 So i followed it but appearently not the good way.

 Roelof
 There's a big difference between print_point() and print time().

 print_point() in your tutorial is a function, presumably defined
 someplace else.

 You used print time(), (no underscore), which uses the print statement,
 and tries to call a function called time().

 Since you defined time as an instance of your class, and didn't do
 anything special, it's not callable.

 DaveA

 
Oke, 
 
I see it now.
I have to us a function that i had to write a few questions before.
 
Thanks everybody 

Roelof

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


[Tutor] pure function problem

2010-09-23 Thread Roelof Wobben


Hello, 
 
I have to rewrite a function to a pure function.
So i have this :
 

class tijd :
pass
def increment(time, seconds):
sum = tijd()
sum.seconds = time.seconds + seconds 

if sum.seconds 60 :
minutes, seconds = divmod(sum.seconds, 60)
sum.seconds = seconds 
sum.minutes = time.minutes + minutes
return sum
time = tijd()
time.hour = 20 
time.minutes = 20
time.seconds = 20 
seconds = 20
uitkomst = tijd()
uitkomst = increment(time, seconds)
print uitkomst.minutes, uitkomst.seconds
 
But now I get this error message :
 
Traceback (most recent call last):
  File C:\Users\wobben\workspace\oefeningen\src\test.py, line 22, in module
print uitkomst.minutes, uitkomst.seconds
AttributeError: tijd instance has no attribute 'minutes'
 
So it looks like uitkomst has no attribute minutes but uitkomst is a instance 
of tijd which has a attribute minutes.
 
Roelof
  
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] pure function problem

2010-09-23 Thread Roelof Wobben



 Date: Thu, 23 Sep 2010 05:36:58 -0400
 Subject: Re: [Tutor] pure function problem
 From: jemejo...@gmail.com
 To: tutor@python.org
 CC: rwob...@hotmail.com
 
 The problem is that your class definition doesn't do anything to
 explicitly set those attributes.
 
 On Thu, Sep 23, 2010 at 4:58 AM, Roelof Wobben rwob...@hotmail.com wrote:
 snip
  class tijd :
 pass
 
 You're not doing any explicit setting of attributes at the class level.
 
 snip
  time = tijd()
  time.hour = 20
  time.minutes = 20
  time.seconds = 20
 
 You set them on this instance.
 
  seconds = 20
  uitkomst = tijd()
 
 But not on this one.
 
 What you probably want to do is something like this:
 
 class tijd(object):
 def __init__(self):
 self.hour = 20
 self.minutes = 20
 self.seconds = 20
 
 Or if you prefer to set these when you create the instance, you can
 pass in values like this:
 
 class tijd(object):
 def __init__(self, hour=20, minutes=20, seconds=20):
 self.hour = hour
 self.minutes = minutes
 self.seconds = seconds
 
 I noticed something odd just a sec ago.  You have this:
  uitkomst = tijd()
  uitkomst = increment(time, seconds)
  print uitkomst.minutes, uitkomst.seconds
 
 You're creating a tijd instance, binding uitkomst to it, then
 overwriting that instance with what you return from increment().
 
 Anyway, hth.
 
 - jmj


Correct, 

I try to find a way to solve this error message.

Roelof

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


Re: [Tutor] pure function problem

2010-09-23 Thread Roelof Wobben




 From: rwob...@hotmail.com
 To: tutor@python.org
 Subject: RE: [Tutor] pure function problem
 Date: Thu, 23 Sep 2010 10:15:07 +



 Date: Thu, 23 Sep 2010 05:36:58 -0400
 Subject: Re: [Tutor] pure function problem
 From: jemejo...@gmail.com
 To: tutor@python.org
 CC: rwob...@hotmail.com

 The problem is that your class definition doesn't do anything to
 explicitly set those attributes.

 On Thu, Sep 23, 2010 at 4:58 AM, Roelof Wobben wrote:

 class tijd :
 pass

 You're not doing any explicit setting of attributes at the class level.


 time = tijd()
 time.hour = 20
 time.minutes = 20
 time.seconds = 20

 You set them on this instance.

 seconds = 20
 uitkomst = tijd()

 But not on this one.

 What you probably want to do is something like this:

 class tijd(object):
 def __init__(self):
 self.hour = 20
 self.minutes = 20
 self.seconds = 20

 Or if you prefer to set these when you create the instance, you can
 pass in values like this:

 class tijd(object):
 def __init__(self, hour=20, minutes=20, seconds=20):
 self.hour = hour
 self.minutes = minutes
 self.seconds = seconds

 I noticed something odd just a sec ago. You have this:
 uitkomst = tijd()
 uitkomst = increment(time, seconds)
 print uitkomst.minutes, uitkomst.seconds

 You're creating a tijd instance, binding uitkomst to it, then
 overwriting that instance with what you return from increment().

 Anyway, hth.

 - jmj


 Correct,

 I try to find a way to solve this error message.

 Roelof


 
Oke, 
 
I changed everything to this : 
 
class tijd :
pass
 
def increment(time, seconds):
sum = tijd()
sum.seconds = time.seconds + seconds 

if sum.seconds 60 :
minutes, seconds = divmod(sum.seconds, 60)
sum.seconds = seconds 
sum.minutes = time.minutes + minutes
return sum
 
time = tijd()
time.hour = 20 
time.minutes = 20
time.seconds = 20 
seconds = 20
uitkomst = increment(time, seconds)
print time(uitkomst)
 
But now Im getting this error message :
 
Traceback (most recent call last):
  File C:\Users\wobben\workspace\oefeningen\src\test.py, line 21, in module
print time(uitkomst)
AttributeError: tijd instance has no __call__ method
 
 
 
Roelof
  
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] pure function problem

2010-09-23 Thread Roelof Wobben




 From: st...@pearwood.info
 To: tutor@python.org
 Date: Fri, 24 Sep 2010 13:00:40 +1000
 Subject: Re: [Tutor] pure function problem

 Roelof, please learn to delete unnecessarily quoted text. There's no
 need to quoted the entire discussion every time you answer.

 On Fri, 24 Sep 2010 06:20:25 am Roelof Wobben wrote:

 time = tijd()
 [...]
 print time(uitkomst)

 Why are you calling time as a function, when it is a tijd instance?




 --
 Steven D'Aprano
 ___
 Tutor maillist - Tutor@python.org
 To unsubscribe or change subscription options:
 http://mail.python.org/mailman/listinfo/tutor
 
 
Hello Steve,
 
I found this in my tutorial.
 
13.8. Instances as return values¶
Functions can return instances. For example, find_center takes a Rectangle as 
an argument and returns a Point that contains the coordinates of the center of 
the Rectangle:
def find_center(box):
p = Point()
p.x = box.corner.x + box.width/2.0
p.y = box.corner.y - box.height/2.0
return p
To call this function, pass box as an argument and assign the result to a 
variable:
 center = find_center(box)
 print_point(center)
(50.0, 100.0)

 
So i followed it but appearently not the good way.
 
Roelof
  
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] class function problem

2010-09-22 Thread Roelof Wobben


HEllo, 
 
I have this exercise :
 
3.Rewrite the increment function so that it doesn’t contain any loops.
 
The increment function looks like this :
 
def increment(time, seconds):
time.seconds = time.seconds + seconds
while time.seconds= 60:
time.seconds = time.seconds - 60
time.minutes = time.minutes + 1
while time.minutes= 60:
time.minutes = time.minutes - 60
time.hours = time.hours + 1

 
So I thought that recursion can do the job.
 
So I wrote this :
 
class tijd :
pass
 
def incrememt_seconds(time): 
   time.seconds = time.seconds - 60 
   time.minutes =  time.minutes + 1 
   if time.seconds= 60 :
   increment_seconds(time,seconds, minutes)
   return  time 
   
def increment_minutes(time):
time.minutes = time.minutes - 60
time.hours = time.hours + 1
if time.minutes= 60 :
increment_minutes(time, minutes,hours)
return time
 
def increment(time, seconds):
time.seconds = time.seconds + seconds 
if time.seconds= 60 :
increment_seconds(time)
if time.minutes= 60 :
increment_minutes(time)
return time
 
time = tijd()
time.hour = 20 
time.minutes = 20
time.seconds = 20 
seconds = 20
uitkomst = increment(time, seconds)
 
But how can i Check the outcome.
print uitkomst gives the object and print time(uitkomst) gives this error 
message :
 
Traceback (most recent call last):
  File C:\Users\wobben\workspace\oefeningen\src\test.py, line 34, in module
print time(uitkomst)
AttributeError: tijd instance has no __call__ method
 
Roelof
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] class function problem

2010-09-22 Thread Roelof Wobben




 From: hugo.yo...@gmail.com
 Date: Wed, 22 Sep 2010 16:16:45 +0200
 Subject: Re: [Tutor] class function problem
 To: rwob...@hotmail.com
 CC: tutor@python.org

 On Wed, Sep 22, 2010 at 9:10 AM, Roelof Wobben wrote:


 HEllo,

 I have this exercise :

 3.Rewrite the increment function so that it doesn’t contain any loops.

 The increment function looks like this :

 def increment(time, seconds):
 time.seconds = time.seconds + seconds
 while time.seconds= 60:
 time.seconds = time.seconds - 60
 time.minutes = time.minutes + 1
 while time.minutes= 60:
 time.minutes = time.minutes - 60
 time.hours = time.hours + 1


 So I thought that recursion can do the job.


 That's very clever. But you might argue that recursion is technically
 still a loop, albeit an implicit one. There is a simpler way to do
 this, without loops entirely.

 Hint: repeated subtraction while your number is greater than some
 constant, what you are doing, is essentially the same as doing one
 division operation.

 
Sorry. I don't get it.
When I have 62 seconds that's 1 minutes and 2 seconds.
I have no clue how I can this with a division.
 
 


 But how can i Check the outcome.
 print uitkomst gives the object and print time(uitkomst) gives this error 
 message :

 Traceback (most recent call last):
 File C:\Users\wobben\workspace\oefeningen\src\test.py, line 34, in 
 print time(uitkomst)
 AttributeError: tijd instance has no __call__ method


 You can do print uitkomst.seconds, uitkomst.minutes, uitkomst.hours.

 Alternatively, write a suitable __str__ method for your tijd class.
 Then you can just do print uitkomst

 Roelof

 
Oke, thanks for the tip. Stupid I could thought that myself.
 
 
Roelof
  
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Can this be done easly

2010-09-19 Thread Roelof Wobben


Hello, 
 
I have this programm :
 
class Point:
 def __init__(self, x=0, y=0): 
 self.x = x
 self.y = y
 
class Rectangle(Point):
def _init_(self, width=0, length=0):
self.width = width
self.length = length

punt = Point(3,4)
rechthoek = Rectangle (punt,20,30)
 
Now I wonder how I can change this to rechthoek = rectangle (punt,20,20)
This one gives as error message  : 
 
Traceback (most recent call last):
  File C:\Users\wobben\workspace\oefeningen\src\test.py, line 12, in module
rechthoek = Rectangle (punt,20,30)
TypeError: __init__() takes at most 3 arguments (4 given)
 
Roelof
  
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Can this be done easly

2010-09-19 Thread Roelof Wobben




 Date: Sun, 19 Sep 2010 14:19:46 +0200
 From: knack...@googlemail.com
 To: tutor@python.org
 Subject: Re: [Tutor] Can this be done easly

 Am 19.09.2010 10:49, schrieb Roelof Wobben:


 Hello,

 I have this programm :

 class Point:
 def __init__(self, x=0, y=0):
 self.x = x
 self.y = y

 class Rectangle(Point):
 def _init_(self, width=0, length=0):
 self.width = width
 self.length = length
 You're inheriting the Point Class, but you don't initialise it.
 For some detailled description of inheritance in Python I rather suggest
 to check out some tutorials instead of trying to explain it. Also,
 others on this list can do this probably better. Here's one reference:
 http://diveintopython.org/object_oriented_framework/index.html

 But now some remarks regarding your problem:

 First, I would not consider a Rectangle as a special Point. It's not a
 relation like a Sportscar is a Car (is-a-relationship). It's more a
 relation a Rectangle has 4 Points (has-a-relationship), or 1 Point and a
 width and length. So, it's probably better to express your Rectangle
 class like this:

 class Rectangle(object):
 def __init__(self, base_point, width=0, length=0):
 self.base_point = base_point
 self.width = width
 self.length = length

 then you go (with German names ;-)):

 punkt = Point(3,4)
 rechteck = Rectangle(punkt,20,30)

 In your Rectangle class, the __init__ method takes only two arguments
 (not counting the instance: self), but you're passing three arguments.

 At the beginning, the error messages are a bit confusing, because they
 count the instance as one of the arguments. So it tells you, that you
 have given 4 arguments, but you might wonder Hey, I gave you 3.

 HTH,

 Jan


 punt = Point(3,4)
 rechthoek = Rectangle (punt,20,30)

 Now I wonder how I can change this to rechthoek = rectangle (punt,20,20)
 This one gives as error message :

 Traceback (most recent call last):
 File C:\Users\wobben\workspace\oefeningen\src\test.py, line 12, in
 rechthoek = Rectangle (punt,20,30)
 TypeError: __init__() takes at most 3 arguments (4 given)

 Roelof

 ___
 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

Hello, 
 
When I change everything to this :
 
class Point:
 def __init__(self, x=0, y=0): 
 self.x = x
 self.y = y
 
class Rectangle(object):
def _init_(self, base_point, width=0, length=0):
self.base_point = base_point
self.width = width
self.length = length

punt = Point(3,4)
rechthoek = Rectangle (punt,20,30)
 
I get this message :
 
Traceback (most recent call last):
  File C:\Users\wobben\workspace\oefeningen\src\test.py, line 13, in module
rechthoek = Rectangle (punt,20,30)
TypeError: object.__new__() takes no parameters
 
Roelof
  
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Can this be done easly

2010-09-19 Thread Roelof Wobben




 To: tutor@python.org
 From: __pete...@web.de
 Date: Sun, 19 Sep 2010 18:04:25 +0200
 Subject: Re: [Tutor] Can this be done easly

 Roelof Wobben wrote:

 When I change everything to this :

 I get this message :

 Traceback (most recent call last):
 File C:\Users\wobben\workspace\oefeningen\src\test.py, line 13, in
 
 rechthoek = Rectangle (punt,20,30)
 TypeError: object.__new__() takes no parameters

 Hint: why does this work:

 def __init__(self, x=0, y=0):

 ...while this doesnt:

 def _init_(self, base_point, width=0, length=0):

 Peter

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

Hoi, 
 
Maybe because base_point has no value ?

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


[Tutor] FW: Can this be done easly

2010-09-19 Thread Roelof Wobben




 From: rwob...@hotmail.com
 To: __pete...@web.de
 Subject: RE: [Tutor] Can this be done easly
 Date: Sun, 19 Sep 2010 17:01:22 +




 
 To: tutor@python.org
 From: __pete...@web.de
 Date: Sun, 19 Sep 2010 18:27:54 +0200
 Subject: Re: [Tutor] Can this be done easly

 Roelof Wobben wrote:

 Hint: why does this work:

 def __init__(self, x=0, y=0):

 ...while this doesnt:

 def _init_(self, base_point, width=0, length=0):

 Peter

 Maybe because base_point has no value ?

 No. One __init__ has two underscores (correct) on each side, the other
 _init_ only one (wrong).

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



Hello,

Everybody thanks.

For this exercise :

3.Write a function named move_rect that takes a Rectangle and two parameters 
named dx and dy. It should change the location of the rectangle by adding dx to 
the x coordinate of corner and adding dy to the y coordinate of corner.

Is this one of the possible solutions :


class Point:
def __init__(self, x=0, y=0): 
self.x = x
self.y = y
 
class Rectangle(object):
def __init__(self, base_point, width=0, length=0):
self.base_point = base_point
self.width = width
self.length = length

def moverect(rectangle, dx, dy):
rechthoek.base_point.y += dy
rechthoek.base_point.x +=dx
return rechthoek

punt = Point(3,4)
rechthoek = Rectangle (punt,20,30)
test = moverect (Rectangle, 4,3) 
print rechthoek.base_point.x

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


Re: [Tutor] FW: Can this be done easly

2010-09-19 Thread Roelof Wobben




 To: tutor@python.org
 From: __pete...@web.de
 Date: Sun, 19 Sep 2010 20:07:05 +0200
 Subject: Re: [Tutor] FW: Can this be done easly

 Roelof Wobben wrote:

 For this exercise :

 3.Write a function named move_rect that takes a Rectangle and two
 parameters named dx and dy. It should change the location of the rectangle
 by adding dx to the x coordinate of corner and adding dy to the y
 coordinate of corner.

 Is this one of the possible solutions :

 class Point:
 def __init__(self, x=0, y=0):
 self.x = x
 self.y = y

 class Rectangle(object):
 def __init__(self, base_point, width=0, length=0):
 self.base_point = base_point
 self.width = width
 self.length = length

 def moverect(rectangle, dx, dy):
 rechthoek.base_point.y += dy
 rechthoek.base_point.x +=dx
 return rechthoek

 punt = Point(3,4)
 rechthoek = Rectangle (punt,20,30)
 test = moverect (Rectangle, 4,3)
 print rechthoek.base_point.x

 At first glance I'd say so. At second glance I see that you pass the class
 and not an instance to the moverect() routine. Your program only seems to
 work because you are not using the parameter rectangle but the global
 rechthoek variable and as soon as you are trying to move rectangles with a
 different variable name everything will break.
 If I were to run your program I might even find more errors or problematic
 behaviours.

 In the long run it's not a sustainable model to verify the correctness of
 your programs by asking someone on the internet who is just as likely to be
 wrong as you or might even fool you.

 Instead add some tests. For example, you could precalculate the expected
 position and then check if the new position meets your expectation:

 r = Rectangle(Point(3, 4), 20, 30)

 moverect(r, 10, 11)

 if r.base_point.x == 13 and r.base_point.y == 15:
 print looks good
 else:
 print needs work

 Because tests are needed very often there are libraries accompanying the
 interpreter (unittest, doctest) to formalize them and for simple runtime
 checks there is the assert statement. Instead of the if...else you could
 write

 assert r.base_point.x == 13, wrong x position %d % r.base_point.x
 assert r.base_point.y == 15, wrong y position %d % r.base_point.y

 Peter

 ___
 Tutor maillist - Tutor@python.org
 To unsubscribe or change subscription options:
 http://mail.python.org/mailman/listinfo/tutor
 
Hello, 
 
I changed the programm to this :
 
import unittest
class Point:
def __init__(self, x=0, y=0): 
self.x = x
self.y = y
 
class Rectangle(object):
def __init__(self, base_point, width=0, length=0):
self.base_point = base_point
self.width = width
self.length = length

def moverect(roelof, dx, dy):
roelof.base_point.y += dy
roelof.base_point.x +=dx
return roelof

r = Rectangle(Point(3, 4), 20, 30) 
moverect(r, 10, 11)
assert r.base_point.x == 13, wrong x position %d % r.base_point.x
assert r.base_point.y == 15, wrong y position %d % r.base_point.y
 
But no output at all
 
Roelof

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


Re: [Tutor] FW: Can this be done easly

2010-09-19 Thread Roelof Wobben




 From: andreeng...@gmail.com
 Date: Sun, 19 Sep 2010 20:54:01 +0200
 Subject: Re: [Tutor] FW: Can this be done easly
 To: rwob...@hotmail.com
 CC: tutor@python.org

 On Sun, Sep 19, 2010 at 8:33 PM, Roelof Wobben wrote:

 Hello,

 I changed the programm to this :

 import unittest
 class Point:
 def __init__(self, x=0, y=0):
 self.x = x
 self.y = y

 class Rectangle(object):
 def __init__(self, base_point, width=0, length=0):
 self.base_point = base_point
 self.width = width
 self.length = length

 def moverect(roelof, dx, dy):
 roelof.base_point.y += dy
 roelof.base_point.x +=dx
 return roelof

 r = Rectangle(Point(3, 4), 20, 30)
 moverect(r, 10, 11)
 assert r.base_point.x == 13, wrong x position %d % r.base_point.x
 assert r.base_point.y == 15, wrong y position %d % r.base_point.y

 But no output at all

 Which output had you expected, and why?


 --
 André Engels, andreeng...@gmail.com
 
Hello, 
 
Oke, I see it now. There is only output when it's not right.
 
Roelof

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


[Tutor] class problem

2010-09-18 Thread Roelof Wobben

Hello, 

I have this exercise :

Create and print a Point object, and then use id to print the
object’s unique identifier. Translate the hexadecimal form into decimal and
confirm that they match.

So I thought that this would solve it:

class Point:
def __init__(self, x=0, y=0):
self.x = x
self.y = y


P=(Point)
a=0 
b=0
a=id(P)
print a 
print b
print P

But now id is a decimal so I don't can't translate it.
Did I something wrong ?

Roelof

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


[Tutor] FW: class problem

2010-09-18 Thread Roelof Wobben



Hello ,

Thanks everyone.

I solved it by this :


class Point:
   def __init__(self, x=0, y=0):
  self.x = x
  self.y = y


P=Point()
print P
print id(P)

and a calculator which can convert hex to decimal.

Roelof


 
 From: st...@pearwood.info
 To: tutor@python.org
 Date: Sun, 19 Sep 2010 01:54:11 +1000
 Subject: Re: [Tutor] class problem

 On Sat, 18 Sep 2010 07:14:03 pm Roelof Wobben wrote:

 P=(Point)

 This line does not do what you think it does. Brackets in Python are
 used for two things, grouping and calling functions.

 To call a function, or a class, you need to have the brackets *after*
 the function:

 P = Point() # what about arguments to the function?

 If you surround it with brackets, as you do above, it does nothing. It's
 like this:

 x = (1+1) # exactly the same as x = 1+1 without brackets


 a=0
 b=0
 a=id(P)

 It is a waste of time to initialise variables immediately before
 initialising them again.



 print a
 print b
 print P

 But now id is a decimal so I don't can't translate it.

 id(x) returns an integer. By default, integers always print in decimal,
 if you want to print them in hex you can do this:

 hex(id(P))



 --
 Steven D'Aprano
 ___
 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


[Tutor] next class problem

2010-09-18 Thread Roelof Wobben


Hello, 
 
I have this exercise :
 
Rewrite the distance function from chapter 5 so that it takes two Points as 
parameters instead of four numbers.
 
I have this solution :
 
class Point:
 def __init__(self, x=0, y=0): 
 self.x = x
 self.y = y
 
def distance(p1,p2):
dx = p2.x - p1.x
dy = p2.y - p1.y
dsquared = dx**2 + dy**2
result = dsquared**0.5
return result
P1 = Point()
P1.x = 3
P1.y = 3
P2 = Point()
P2.x = 6
P2.y = 7 
result = distance (P1,P2)
print result
 
 
Is this the correct solution ?
 
Roelof
  
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] next class problem

2010-09-18 Thread Roelof Wobben




 Date: Sat, 18 Sep 2010 13:40:55 -0400
 From: bgai...@gmail.com
 To: rwob...@hotmail.com
 CC: tutor@python.org
 Subject: Re: [Tutor] next class problem

 On 9/18/2010 1:20 PM, Roelof Wobben wrote:

 Hello,

 I have this exercise :

 Rewrite the distance function from chapter 5 so that it takes two Points as 
 parameters instead of four numbers.

 I have this solution :

 class Point:
 def __init__(self, x=0, y=0):
 self.x = x
 self.y = y

 def distance(p1,p2):
 dx = p2.x - p1.x
 dy = p2.y - p1.y
 dsquared = dx**2 + dy**2
 result = dsquared**0.5
 return result
 P1 = Point()
 P1.x = 3
 P1.y = 3
 P2 = Point()
 P2.x = 6
 P2.y = 7
 result = distance (P1,P2)
 print result


 Is this the correct solution ?

 What is your criteria for correct?

 There is no one correct solution!

 You seem to be passing 2 points, as requested.

 Do you get the correct answer?

 Then it mus be correct.

 FWIW Python convention recommends names starting with lower case except
 for classes and constants.

 Therefore p1 and p2 are preferred to P1 and P2.

 Also why not initialize x and y thus:
 p1 = Point(3,3)
 That is what the __init__ is for.

 --
 Bob Gailer
 919-636-4239
 Chapel Hill NC

 
Hello, 
 
Thank you.
Learned another thing.
 
Roelof

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


Re: [Tutor] robots question

2010-09-17 Thread Roelof Wobben

Hello, 

I changed a lot because of your suggestions.

But one thing is still a puzzle.

The robots don't move anymore.

What I have is this :

#
# robots.py
#
from gasp import *

SCREEN_WIDTH = 640
SCREEN_HEIGHT = 480
GRID_WIDTH = SCREEN_WIDTH/10 - 1
GRID_HEIGHT = SCREEN_HEIGHT/10 - 1


def place_player():
# x = random.randint(0, GRID_WIDTH)
# y = random.randint(0, GRID_HEIGHT)
x, y = GRID_WIDTH/2 + 3, GRID_HEIGHT/2
return {'shape': Circle((10*x+5, 10*y+5), 5, filled=True), 'x': x, 'y': y}

def place_robot(x, y, junk=False):
return {'shape': Box((10*x, 10*y), 10, 10, filled = junk), 'x': x, 'y': y}


def place_robots(numbots):
robots=[]
# for i in range(numbots):
#x = random.randint(0, GRID_WIDTH)
#y = random.randint(0, GRID_HEIGHT)
#robots.append(place_robot(x, y))
robots.append(place_robot(GRID_WIDTH/2 - 4, GRID_HEIGHT/2 + 2, junk = 
False))
robots.append(place_robot(GRID_WIDTH/2 - 4, GRID_HEIGHT/2 - 2, junk = 
False))
return robots

def move_player(player):
update_when('key_pressed')
if key_pressed('escape'):
return True
elif key_pressed('4'):
if player['x']  0: player['x'] -= 1
elif key_pressed('7'):
if player['x']  0: player['x'] -= 1
if player['y']  GRID_HEIGHT: player['y'] += 1
elif key_pressed('8'):
if player['y']  GRID_HEIGHT: player['y'] += 1
elif key_pressed('9'):
if player['x']  GRID_WIDTH: player['x'] += 1
if player['y']  GRID_HEIGHT: player['y'] += 1
elif key_pressed('6'):
if player['x']  GRID_WIDTH: player['x'] += 1
elif key_pressed('3'):
if player['x']  GRID_WIDTH: player['x'] += 1
if player['y']  0: player['y'] -= 1
elif key_pressed('2'):
if player['y']  0: player['y'] -= 1
elif key_pressed('1'):
if player['x']  0: player['x'] -= 1
if player['y']  0: player['y'] -= 1
elif key_pressed('0'):
   player['x'] = random.randint(0, GRID_WIDTH)
   player['y'] = random.randint(0, GRID_HEIGHT)
else:
return False

move_to(player['shape'], (10*player['x']+5, 10*player['y']+5))

return False

def collided(thing1, thing2):
return thing1['x'] == thing2['x'] and thing1['y'] == thing2['y']

def check_collisions(robots, junk, player):
# check whether player has collided with anything
for thing in robots + junk:
if collided(thing, player):
return True
return False



def move_robot(robot, player):
if robot['x']  player['x']: robot['x'] += 1
elif robot['x']  player['x']: robot['x'] -= 1

if robot['y']  player['y']: robot['y'] += 1
elif robot['y']  player['y']: robot['y'] -= 1

move_to(robot['shape'], (10*robot['x'], 10*robot['y']))

def move_robots(robots, player):
for robot in robots:
move_robot(robot, player)


def play_game():
begin_graphics(SCREEN_WIDTH, SCREEN_HEIGHT)
player = place_player()
robots = []
place_robots(4)
junk = [ place_robot(GRID_WIDTH/2, GRID_HEIGHT/2, junk=True )]
defeated = False

while not defeated:
quit =  move_player(player)
if quit:
break
move_robots(robots, player)
defeated = check_collisions(robots, junk, player)

if defeated:
remove_from_screen(player['shape'])
for thing in robots + junk:
remove_from_screen(thing['shape'])
Text(They got you!, (240, 240), size=32)
sleep(3)

end_graphics()



if __name__ == '__main__':
play_game()

Roelof


 To: tutor@python.org
 From: alan.ga...@btinternet.com
 Date: Fri, 17 Sep 2010 01:14:32 +0100
 Subject: Re: [Tutor] robots question
 
 
 Roelof Wobben rwob...@hotmail.com wrote
 
 
 #
 # robots.py
 
 This is pretty weird code, there are several odd things in it.
 
 def place_player():
 # x = random.randint(0, GRID_WIDTH)
 # y = random.randint(0, GRID_HEIGHT)
 x, y = GRID_WIDTH/2 + 3, GRID_HEIGHT/2
 return {'shape': Circle((10*x+5, 10*y+5), 5, filled=True), 'x': x, 
 'y': y}
 
 So this returns a dictionary which always contains the same data.
 
 def place_robot(x,y, junk):
 x = random.randint(0, GRID_WIDTH)
 y = random.randint(0, GRID_HEIGHT)
 return {'shape': Box((10*x, 10*y), 10, 10), 'x': x, 'y': y}
 
 This returns a similar dict but with random data.
 It ignores the values of x and y passed in and does not use junk at 
 all.
 
 def place_robots(numbots):
 robots = []
 # for i in range(numbots):
 #x = random.randint(0, GRID_WIDTH)
 #y = random.randint(0, GRID_HEIGHT)
 #robots.append(place_robot(x, y))
 robots.append(place_robot(GRID_WIDTH/2 - 4, GRID_HEIGHT/2 + 2, 
 junk= False))
 robots.append(place_robot(GRID_WIDTH/2 - 4, GRID_HEIGHT/2 - 2, 
 junk = False))
 print type(robots)
 return robots
 
 This returns a list of 2 dictionaries. The x,y parameters are ignored 
 by the function.
 
 
 def move_player(player):
 update_when

[Tutor] robots question

2010-09-16 Thread Roelof Wobben

Hello, 

As a exercise from this book ( Thinking like a computer scientist ) I have to 
make this programm on this 
page(http://openbookproject.net/thinkcs/python/english2e/ch12.html)
Exercise 11 

#
# robots.py
#
from gasp import *

SCREEN_WIDTH = 640
SCREEN_HEIGHT = 480
GRID_WIDTH = SCREEN_WIDTH/10 - 1
GRID_HEIGHT = SCREEN_HEIGHT/10 - 1


def place_player():
# x = random.randint(0, GRID_WIDTH)
# y = random.randint(0, GRID_HEIGHT)
x, y = GRID_WIDTH/2 + 3, GRID_HEIGHT/2
return {'shape': Circle((10*x+5, 10*y+5), 5, filled=True), 'x': x, 'y': y}

def place_robot(x,y, junk):
x = random.randint(0, GRID_WIDTH)
y = random.randint(0, GRID_HEIGHT)
return {'shape': Box((10*x, 10*y), 10, 10), 'x': x, 'y': y}


def place_robots(numbots):
robots = []
# for i in range(numbots):
#x = random.randint(0, GRID_WIDTH)
#y = random.randint(0, GRID_HEIGHT)
#robots.append(place_robot(x, y))
robots.append(place_robot(GRID_WIDTH/2 - 4, GRID_HEIGHT/2 + 2, junk= False))
robots.append(place_robot(GRID_WIDTH/2 - 4, GRID_HEIGHT/2 - 2, junk = 
False))
return robots

def move_player(player):
update_when('key_pressed')
if key_pressed('escape'):
return True
elif key_pressed('4'):
if player['x']  0: player['x'] -= 1
elif key_pressed('7'):
if player['x']  0: player['x'] -= 1
if player['y']  GRID_HEIGHT: player['y'] += 1
elif key_pressed('8'):
if player['y']  GRID_HEIGHT: player['y'] += 1
elif key_pressed('9'):
if player['x']  GRID_WIDTH: player['x'] += 1
if player['y']  GRID_HEIGHT: player['y'] += 1
elif key_pressed('6'):
if player['x']  GRID_WIDTH: player['x'] += 1
elif key_pressed('3'):
if player['x']  GRID_WIDTH: player['x'] += 1
if player['y']  0: player['y'] -= 1
elif key_pressed('2'):
if player['y']  0: player['y'] -= 1
elif key_pressed('1'):
if player['x']  0: player['x'] -= 1
if player['y']  0: player['y'] -= 1
elif key_pressed('0'):
   player['x'] = random.randint(0, GRID_WIDTH)
   player['y'] = random.randint(0, GRID_HEIGHT)
else:
return False

move_to(player['shape'], (10*player['x']+5, 10*player['y']+5))

return False

def collided(thing1, thing2):
return thing1['x'] == thing2['x'] and thing1['y'] == thing2['y']

def check_collisions(robots, junk, player):
# check whether player has collided with anything
for thing in robots + junk:
if collided(thing, player):
return True
return False



def move_robot(robot, player):
if robot['x']  player['x']: robot['x'] += 1
elif robot['x']  player['x']: robot['x'] -= 1

if robot['y']  player['y']: robot['y'] += 1
elif robot['y']  player['y']: robot['y'] -= 1

move_to(robot['shape'], (10*robot['x'], 10*robot['y']))

def move_robots(robots, player):
for robot in robots:
move_robot(robot, player)


def play_game(robots):
begin_graphics(SCREEN_WIDTH, SCREEN_HEIGHT)
player = place_player()
robot = place_robots(4)
junk = [place_robot(GRID_WIDTH/2, GRID_HEIGHT/2, junk=true )]
defeated = False

while not defeated:
quit =  move_player(player)
if quit:
break
move_robots(robot, player)
defeated = check_collisions(robot, player, junk)

if defeated:
remove_from_screen(player['shape'])
for thing in robots + junk:
remove_from_screen(thing['shape'])
Text(They got you!, (240, 240), size=32)
sleep(3)

end_graphics()



if __name__ == '__main__':
play_game(2)

But now Im getting this error message :

Traceback (most recent call last):
  File /root/workspace/test2/src/test.py, line 120, in module
play_game(2)
  File /root/workspace/test2/src/test.py, line 106, in play_game
defeated = check_collisions(robot, player, junk)
  File /root/workspace/test2/src/test.py, line 73, in check_collisions
for thing in robots + junk:
TypeError: can only concatenate list (not dict) to list

I understand that robots is a dict and junk is a list.

Is that right ?

And why does the book say that when this message is appearing. 

Roelof


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


[Tutor] FW: robots question

2010-09-16 Thread Roelof Wobben



From: rwob...@hotmail.com
To: __pete...@web.de
Subject: RE: [Tutor] robots question
Date: Thu, 16 Sep 2010 17:43:41 +








Hello , 

I change everything to this :

#
# robots.py
#
from gasp import *

SCREEN_WIDTH = 640
SCREEN_HEIGHT = 480
GRID_WIDTH = SCREEN_WIDTH/10 - 1
GRID_HEIGHT = SCREEN_HEIGHT/10 - 1


def place_player():
# x = random.randint(0, GRID_WIDTH)
# y = random.randint(0, GRID_HEIGHT)
x, y = GRID_WIDTH/2 + 3, GRID_HEIGHT/2
return {'shape': Circle((10*x+5, 10*y+5), 5, filled=True), 'x': x, 'y': y}

def place_robot(x,y, junk):
x = random.randint(0, GRID_WIDTH)
y = random.randint(0, GRID_HEIGHT)
return {'shape': Box((10*x, 10*y), 10, 10), 'x': x, 'y': y}


def place_robots(numbots):
robots = []
# for i in range(numbots):
#x = random.randint(0, GRID_WIDTH)
#y = random.randint(0, GRID_HEIGHT)
#robots.append(place_robot(x, y))
robots.append(place_robot(GRID_WIDTH/2 - 4, GRID_HEIGHT/2 + 2, junk= False))
robots.append(place_robot(GRID_WIDTH/2 - 4, GRID_HEIGHT/2 - 2, junk = 
False))
print type(robots)
return robots

def move_player(player):
update_when('key_pressed')
if key_pressed('escape'):
return True
elif key_pressed('4'):
if player['x']  0: player['x'] -= 1
elif key_pressed('7'):
if player['x']  0: player['x'] -= 1
if player['y']  GRID_HEIGHT: player['y'] += 1
elif key_pressed('8'):
if player['y']  GRID_HEIGHT: player['y'] += 1
elif key_pressed('9'):
if player['x']  GRID_WIDTH: player['x'] += 1
if player['y']  GRID_HEIGHT: player['y'] += 1
elif key_pressed('6'):
if player['x']  GRID_WIDTH: player['x'] += 1
elif key_pressed('3'):
if player['x']  GRID_WIDTH: player['x'] += 1
if player['y']  0: player['y'] -= 1
elif key_pressed('2'):
if player['y']  0: player['y'] -= 1
elif key_pressed('1'):
if player['x']  0: player['x'] -= 1
if player['y']  0: player['y'] -= 1
elif key_pressed('0'):
   player['x'] = random.randint(0, GRID_WIDTH)
   player['y'] = random.randint(0, GRID_HEIGHT)
else:
return False

move_to(player['shape'], (10*player['x']+5, 10*player['y']+5))

return False

def collided(thing1, thing2):
return thing1['x'] == thing2['x'] and thing1['y'] == thing2['y']

def check_collisions(robots, junk, player):
# check whether player has collided with anything
for thing in robots + junk:
if collided(thing, player):
return True
return False



def move_robot(robot, player):
if robot['x']  player['x']: robot['x'] += 1
elif robot['x']  player['x']: robot['x'] -= 1

if robot['y']  player['y']: robot['y'] += 1
elif robot['y']  player['y']: robot['y'] -= 1

move_to(robot['shape'], (10*robot['x'], 10*robot['y']))

def move_robots(robots, player):
for robot in robots:
move_robot(robot, player)


def play_game():
begin_graphics(SCREEN_WIDTH, SCREEN_HEIGHT)
player = place_player()
robot = place_robots(4)
junk = [ place_robot(GRID_WIDTH/2, GRID_HEIGHT/2, junk=true )]
robots = []
defeated = False

while not defeated:
quit =  move_player(player)
if quit:
break
move_robots(robots, player)
print type robots, type(robots)
print type junk, type(junk)
print type player, type(player)
defeated = check_collisions(robots, player, junk)

if defeated:
remove_from_screen(player['shape'])
for thing in robots + junk:
remove_from_screen(thing['shape'])
Text(They got you!, (240, 240), size=32)
sleep(3)

end_graphics()



if __name__ == '__main__':
play_game()


And now Im getting this message :

** Message: pygobject_register_sinkfunc is deprecated (GtkWindow)
** Message: pygobject_register_sinkfunc is deprecated (GtkInvisible)
** Message: pygobject_register_sinkfunc is deprecated (GtkObject)
type 'list'
type robotsTraceback (most recent call last):
 type 'list'
type junk type 'list'
type player type 'dict'
  File /root/workspace/test2/src/test.py, line 125, in module
play_game()
  File /root/workspace/test2/src/test.py, line 111, in play_game
defeated = check_collisions(robots, player, junk)
  File /root/workspace/test2/src/test.py, line 74, in check_collisions
for thing in robots + junk:
TypeError: can only concatenate list (not dict) to list

So far I can see the problem is that player is a dict and the rest is a list.

Is this the correct conclusion ?

Roelof


 To: tutor@python.org
 From: __pete...@web.de
 Date: Thu, 16 Sep 2010 18:10:13 +0200
 Subject: Re: [Tutor] robots question
 
 Roelof Wobben wrote:
 
  As a exercise from this book ( Thinking like a computer scientist ) I have
  to make this programm on this
  page(http://openbookproject.net/thinkcs/python/english2e/ch12.html)
  Exercise 11
 
  def check_collisions(robots, junk

[Tutor] FW: FW: robots question

2010-09-16 Thread Roelof Wobben




 From: rwob...@hotmail.com
 To: __pete...@web.de
 Subject: RE: [Tutor] FW: robots question
 Date: Thu, 16 Sep 2010 18:22:03 +




 
 To: tutor@python.org
 From: __pete...@web.de
 Date: Thu, 16 Sep 2010 20:10:02 +0200
 Subject: Re: [Tutor] FW: robots question

 Roelof Wobben wrote:

 I change everything to this :

 def check_collisions(robots, junk, player):

 defeated = check_collisions(robots, player, junk)

 Do you see the problem?



yes, Player en junk are swapped.




 print type robots, type(robots)
 print type junk, type(junk)
 print type player, type(player)

 Adding print statements for debugging purposes is a good approach.

 And now Im getting this message :

 ** Message: pygobject_register_sinkfunc is deprecated (GtkWindow)
 ** Message: pygobject_register_sinkfunc is deprecated (GtkInvisible)
 ** Message: pygobject_register_sinkfunc is deprecated (GtkObject)

 type robotsTraceback (most recent call last):

 type junk
 type player
 File /root/workspace/test2/src/test.py, line 125, in
 play_game()
 File /root/workspace/test2/src/test.py, line 111, in play_game
 defeated = check_collisions(robots, player, junk)
 File /root/workspace/test2/src/test.py, line 74, in check_collisions
 for thing in robots + junk:
 TypeError: can only concatenate list (not dict) to list

 So far I can see the problem is that player is a dict and the rest is a
 list.
 Is this the correct conclusion ?

 It may be correct but it's a low-level view. A more appropriate description
 would be that you are trying to concatenate a list of robots with a player.


Oke,

 I will try to make one list which will contain the robots and a player.
 
 


 Peter

 ___
 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] FW: wierd replace problem

2010-09-15 Thread Roelof Wobben




 Date: Tue, 14 Sep 2010 22:15:40 +0100
 From: wpr...@gmail.com
 To: tutor@python.org
 Subject: Re: [Tutor] FW: wierd replace problem



 On 14 September 2010 21:10, Roelof Wobben
 wrote:
 I understand it but I try to understand why in a file there is this
 'word python makes a 'word.

 Python doesn't change what it reads from the file. However, depending
 on how you ask Python to tell you what it's read (or what the contents
 of a string variable is), it might display it quoted, and/or include
 escape charaters, or not as the case may be. If what you've read from
 the file contains quotes, then obviously you need to be careful to not
 mistake Python's quoting of the value of a string as being *part* of
 that string. Neither must you mistake the escape character (if
 applicable) from being actually part of the string.

 For example, consider the following exchange in the Python shell
 (please try all of this yourself and experiment):

 s = 'blah'
 s
 'blah'
 print s
 blah


 I assign the value of 'blah' to the string s. So far simple enough.
 Obviosuly the quotes used int the assignment of the string does not
 form part of the string itself. Their utility is only to delineate to
 Python the start of the string, and the end of the string.

 In the next line I ask Python to evaluate the expression s, which it
 duly reporst as 'blah'. Again, it's using normal Python convention to
 format the data as a string, because that's what s is, a string
 object. But the quotes are formatting, they're not really part of the
 string.

 In the next line I ask Python to print s. Now, the true content of s
 is printed as it is, and hence you can see that the quotes are not part
 of the string.

 Now consider the following exchange in the Python shell where I open a
 file and write some text to it to prove this point:
 f = open('test.txt', 'w+')
 f.write('blah')
 f.close()
 import os
 os.system('notepad test.txt')

 The last line above opens the text file test.txt in Notepad so you can
 see the contents. As you can see, no quotes or anything else. Now,
 while open, suppose we put a single quote in the file, so it reads:
 'blah
 ...and suppose we then save it and exit notepad so you're back in the
 Python shell. Then we do:

 f=open('test.txt','r+')
 s=f.read()
 f.close()
 s
 'blah

 Now I've read the contents of the file back into a string variable s,
 and asked Python to evaluate (output) this string object.

 Notice, Python is now formatting the string with *doube* quotes
 (previously it defaulted to single quotes) to avoid having to escape
 the single quote that forms part of the string. If Python had used
 single quotes instead, then there would've been an ambiguity with the
 single quote that's part of the string and so it would've had to escape
 that too. So consequently it formats the string with double quotes,
 which is valid Python syntax and avoids the backslash. (Stating the
 obvious, strings can be quoted with double or single quotes.) As
 before, the double quotes, as with the single quotes earlier, are not
 part of the string. They are merely formatting since Python is being
 asked to display a string and hence it must indicate the start and end
 of the string with suitable quote characters.

 Now, as before do:

 print s
 'blah

 As before, with print you see the contents of the string as it is (and
 as indeed it is also in the file that you saved). Just the single quote
 you added at the front of Blah. No double or single quotes or anything
 else.

 Now finally, let's try something a bit more elaborate. Do again:

 os.system('notepad test.txt')

 Then put into the file the following 2 lines of text (notice the file
 now contains 2 lines, and both single and double quotes...):
 ++This line is double quoted in the file and the quotes have +
 symbols around them.++
 ---'---This line is single quoted in the file and the quotes have -
 symbols around them.---'---

 Save it, exit Notepad, then do:
 f=open('test.txt', 'r+')
 s=f.read()
 f.close()
 s
 '++This line is double quoted in the file and the quotes have +
 symbols around them.++\n---\'---This line is single quoted in the
 file and the quotes have - symbols around them.---\'---\n'
 print s
 ++This line is double quoted in the file and the quotes have +
 symbols around them.++
 ---'---This line is single quoted in the file and the quotes have -
 symbols around them.---'---

 Notice we read both lines in the file into one single string. See how
 Python formats that as a string object, and escapes not only the single
 quotes but also the line break characters (\n). See also when Python
 is asked to print the string, you can see the escape characters
 really there. See what's happened? Do you understand why?

 Walter






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

[Tutor] FW: wierd replace problem

2010-09-14 Thread Roelof Wobben



Hello,

Strip (''') does not work.
Still this message : SyntaxError: EOL while scanning string literal

So I think I go for the suggestion of Bob en develop a programm which deletes 
all the ' and  by scanning it character by character.

 Roelof


 
 From: st...@pearwood.info
 To: tutor@python.org
 Date: Tue, 14 Sep 2010 09:39:29 +1000
 Subject: Re: [Tutor] wierd replace problem

 On Tue, 14 Sep 2010 09:08:24 am Joel Goldstick wrote:
 On Mon, Sep 13, 2010 at 6:41 PM, Steven D'Aprano
 wrote:
 On Tue, 14 Sep 2010 04:18:36 am Joel Goldstick wrote:
 How about using str.split() to put words in a list, then run
 strip() over each word with the required characters to be removed
 ('`)

 Doesn't work. strip() only removes characters at the beginning and
 end of the word, not in the middle:

 Exactly, you first split the words into a list of words, then strip
 each word

 Of course, if you don't want to remove ALL punctuation marks, but only
 those at the beginning and end of words, then strip() is a reasonable
 approach. But if the aim is to strip out all punctuation, no matter
 where, then it can't work.

 Since the aim is to count words, a better approach might be a hybrid --
 remove all punctuation marks like commas, fullstops, etc. no matter
 where they appear, keep internal apostrophes so that words like can't
 are different from cant, but remove external ones. Although that
 loses information in the case of (e.g.) dialect speech:

 'e said 'e were going to kill the lady, Mister Holmes!
 cried the lad excitedly.

 You probably want to count the word as 'e rather than just e.

 And hyphenation is tricky to. A lone hyphen - like these - should be
 deleted. But double-dashes--like these--are word separators, so need to
 be replaced by a space. Otherwise, single hyphens should be kept. If a
 word begins or ends with a hyphen, it should be be joined up with the
 previous or next word. But then it gets more complicated, because you
 don't know whether to keep the hyphen after joining or not.

 E.g. if the line ends with:

 blah blah blah blah some-
 thing blah blah blah.

 should the joined up word become the compound word some-thing or the
 regular word something? In general, there's no way to be sure,
 although you can make a good guess by looking it up in a dictionary and
 assuming that regular words should be preferred to compound words. But
 that will fail if the word has changed over time, such as cooperate,
 which until very recently used to be written co-operate, and before
 that as coöperate.



 --
 Steven D'Aprano
 ___
 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] FW: wierd replace problem

2010-09-14 Thread Roelof Wobben




 Date: Tue, 14 Sep 2010 09:32:38 +0200
 From: timomli...@gmail.com
 To: tutor@python.org
 Subject: Re: [Tutor] FW: wierd replace problem

 On 14-09-10 09:28, Roelof Wobben wrote:


 Hello,

 Strip (''') does not work.
 Still this message : SyntaxError: EOL while scanning string literal

 Review it again, see how many quotes you are using.

 For example, this won't work either:
 s = 'foo'bar'

 You need to escape the quotes with a backslash, like:
 s = 'foo\'bar'
 print s
 foo'bar


 Cheers,
 Timo

 
Hello Timo,
 
I understand what you mean but we're talking about a text-file which will be 
read in a string.
So I can't escape the quotes. As far as I know I can't control  how Python is 
reading a text-file with quotes.
 
Roelof
 
 
 

 So I think I go for the suggestion of Bob en develop a programm which 
 deletes all the ' and  by scanning it character by character.

 Roelof



 

 From: st...@pearwood.info
 To: tutor@python.org
 Date: Tue, 14 Sep 2010 09:39:29 +1000
 Subject: Re: [Tutor] wierd replace problem

 On Tue, 14 Sep 2010 09:08:24 am Joel Goldstick wrote:

 On Mon, Sep 13, 2010 at 6:41 PM, Steven D'Aprano

 wrote:

 On Tue, 14 Sep 2010 04:18:36 am Joel Goldstick wrote:

 How about using str.split() to put words in a list, then run
 strip() over each word with the required characters to be removed
 ('`)

 Doesn't work. strip() only removes characters at the beginning and
 end of the word, not in the middle:

 Exactly, you first split the words into a list of words, then strip
 each word

 Of course, if you don't want to remove ALL punctuation marks, but only
 those at the beginning and end of words, then strip() is a reasonable
 approach. But if the aim is to strip out all punctuation, no matter
 where, then it can't work.

 Since the aim is to count words, a better approach might be a hybrid --
 remove all punctuation marks like commas, fullstops, etc. no matter
 where they appear, keep internal apostrophes so that words like can't
 are different from cant, but remove external ones. Although that
 loses information in the case of (e.g.) dialect speech:

 'e said 'e were going to kill the lady, Mister Holmes!
 cried the lad excitedly.

 You probably want to count the word as 'e rather than just e.

 And hyphenation is tricky to. A lone hyphen - like these - should be
 deleted. But double-dashes--like these--are word separators, so need to
 be replaced by a space. Otherwise, single hyphens should be kept. If a
 word begins or ends with a hyphen, it should be be joined up with the
 previous or next word. But then it gets more complicated, because you
 don't know whether to keep the hyphen after joining or not.

 E.g. if the line ends with:

 blah blah blah blah some-
 thing blah blah blah.

 should the joined up word become the compound word some-thing or the
 regular word something? In general, there's no way to be sure,
 although you can make a good guess by looking it up in a dictionary and
 assuming that regular words should be preferred to compound words. But
 that will fail if the word has changed over time, such as cooperate,
 which until very recently used to be written co-operate, and before
 that as coöperate.



 --
 Steven D'Aprano
 ___
 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


 ___
 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] FW: wierd replace problem

2010-09-14 Thread Roelof Wobben

Oke, 
 
Can this also be the same problem.
 
In the text is this :
 
'tis is represent as  'this
 
And this
 
part is represent as part.
 
 
Roelof



 Date: Tue, 14 Sep 2010 11:41:28 +0100
 From: wpr...@gmail.com
 To: tutor@python.org
 Subject: Re: [Tutor] FW: wierd replace problem



 On 14 September 2010 11:09, James Mills

 wrote:
 $ python
 Python 2.6.5 (r265:79063, Jun 13 2010, 14:03:16)
 [GCC 4.4.4 (CRUX)] on linux2
 Type help, copyright, credits or license for more information.
 s = foo\bar'
 s
 'foobar\''

 I'd like to point something out here. Typing s as James showed here
 at the prompt outputs a version of the string that Python will
 understand if fed again, consequently it's encoded to do the same
 escaping of characters as you would have to do if you put that
 expression into your python source yourself. If however you entered:

 print s

 ... then Python would've print the value of s as it really is, withou
 any escape characters or anything else, e.g.:

 print s
 foobar'

 So, even though you see a \' in the output posted by James above, the \
 that was output by Python isn't actually part of the string (e.g. it's
 not really there as such), it was only output that way by Python to
 disambiguate the value of the string.

 So, at the risk of belaboring this point to death, if you do:

 s = '\'\'\''

 then the contents of the string s in memory is '''

 The string does not contain the slashes. The slashes are only there to
 help you make Python understand that the quotes must not be interpreted
 as the end of the string, but rather as part of the string. You could
 get the exact same result by doing:

 s = '''

 Here there's no ambiguity and consequently no need for slashes since
 the string is delineated by double quotes and not single quotes.

 Hope that helps.

 Walter

 ___ 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] FW: wierd replace problem

2010-09-14 Thread Roelof Wobben




 From: st...@pearwood.info
 To: tutor@python.org
 Date: Tue, 14 Sep 2010 21:30:01 +1000
 Subject: Re: [Tutor] FW: wierd replace problem

 On Tue, 14 Sep 2010 05:38:18 pm Roelof Wobben wrote:

 Strip (''') does not work.
 Still this message : SyntaxError: EOL while scanning string
 literal
 [...]
 I understand what you mean but we're talking about a text-file which
 will be read in a string. So I can't escape the quotes. As far as I
 know I can't control how Python is reading a text-file with quotes.

 The text file has nothing to do with this. The text file is fine. The
 error is in the strings that YOU type, not the text file.

 Strings must have MATCHING quotation marks:

 This is okay: abcd
 So is this: 'abcd'

 But this is not: abcd'

 You need to *look carefully* at strings you type and make sure that the
 start and end quotes match. Likewise you can't insert the SAME
 quotation mark in a string unless you escape it first:

 This is okay: 'Hello,' he said.
 So is this: 'Goodbye, she replied.'

 But this is not: 'He said I can't see you.'

 But this is okay: 'He said I can\'t see you.'




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

Oke, 
 
I see the problem.
 
When I have this sentence : `'Tis so,' said the Duchess:  `and the moral of 
that is--Oh,
'tis love, 'tis love, that makes the world go round!'

And I do string.strip() the output will be :
 
`'This and that one does not fit your explanation.
So I have to strip everything before I strip it. 
 
Roelof
  
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] FW: wierd replace problem

2010-09-14 Thread Roelof Wobben




 From: rwob...@hotmail.com
 To: joel.goldst...@gmail.com
 Subject: RE: [Tutor] FW: wierd replace problem
 Date: Tue, 14 Sep 2010 15:43:42 +




 
 Date: Tue, 14 Sep 2010 11:28:10 -0400
 From: joel.goldst...@gmail.com
 To: tutor@python.org
 Subject: Re: [Tutor] FW: wierd replace problem



 On Tue, Sep 14, 2010 at 10:29 AM, Roelof Wobben
 wrote:

 I offer my solution. I didn't bother to make every word lower case,
 and I think that would improve the result

 Please offer critique, improvements


 Some explaination:

 line 5 -- I read the complete text into full_text, while first
 replacing -- with a space
 line 7 -- I split the full text string into words
 lines 8 - 15 -- Word by word I strip all sorts of characters that
 aren't in words from the front and back of each 'word'
 lines 11 - 14 -- this is EAFP -- try to add one to the bin with that
 word, if no such bin, make it and give it 1
 lines 16, 17 -- since dicts don't sort, sort on the keys then loop thru
 the keys to print out the key (word) and the count

 
 1 #! /usr/bin/env python
 2
 3 word_count = {}
 4 file = open ('alice_in_wonderland.txt', 'r')
 5 full_text = file.read().replace('--',' ')
 6
 7 full_text_words = full_text.split()
 8 for words in full_text_words:
 9 stripped_words = words.strip(.,!?'`\- ();:)
 10 ##print stripped_words
 11 try:
 12 word_count[stripped_words] += 1
 13 except KeyError:
 14 word_count[stripped_words] = 1
 15
 16 ordered_keys = word_count.keys()
 17 ordered_keys.sort()
 18 ##print ordered_keys
 19 print All the words and their frequency in 'alice in wonderland'
 20 for k in ordered_keys:
 21 print k, word_count[k]
 22
 --
 Joel Goldstick


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



Hello Joel,

Your solution works.
Im getting grazy. I tried it two days with strip and get a eof error message 
and now no messages.

Roelof


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


Re: [Tutor] FW: wierd replace problem

2010-09-14 Thread Roelof Wobben




Date: Tue, 14 Sep 2010 17:45:35 +0200
From: f...@libero.it
To: tutor@python.org
Subject: Re: [Tutor] FW: wierd replace problem


On 14/09/2010 16.29, Roelof Wobben wrote:
...
 Oke,

 I see the problem.

 When I have this sentence : `'Tis so,' said the Duchess: `and the moral of 
 that is--Oh,
 'tis love, 'tis love, that makes the world go round!'

 And I do string.strip() the output will be :

 `'This and that one does not fit your explanation.
 So I have to strip everything before I strip it.

After some trial and error with the interpreter, I found this:

st = `'Tis so,' said the Duchess: `and the moral of that is--Oh,
'tis love, 'tis love, that makes the world go round!' # notice the
starting and ending triple quotes, just to avoid all the backslashes and
the ambiguities with quoting characters ;-)

wordlist = [thisone.strip(',!` :-) for thisone in st.replace('',
 ).replace(-, ).split()]

I don't know if you read the chapter regarding list comprehensions in
your tutorial, but this is one of those. First of all, I replace all
double quotes  and dashes - with spaces:
st.replace('',  ).replace(-, )
then I use split() to divide the long string in a list of almost-words.
At the end, with the for clause in the list comprehension, I strip all
leading and trailing non-letters (again, I enclose them in a
triple-quoted string) from each of the elements of the list.

In the end, I have wordlist:

['Tis', 'so', 'said', 'the', 'Duchess', 'and', 'the', 'moral', 'of',
'that', 'is', 'Oh', 'tis', 'love', 'tis', 'love', 'that', 'makes',
'the', 'world', 'go', 'round', '']

What about this? Was it confusing?

 Roelof
Francesco
 
hello Franceso,
 
It was not confusing when I read your explanation.
Still im grazy wht with you and Joel the strip works and with me I get errors.
 
But how can I use the triple quotes when reading a textf-file ?
Roelof


___
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] FW: wierd replace problem

2010-09-14 Thread Roelof Wobben




 From: rwob...@hotmail.com
 To: sander.swe...@gmail.com
 Subject: RE: [Tutor] FW: wierd replace problem
 Date: Tue, 14 Sep 2010 17:40:28 +




 
 From: sander.swe...@gmail.com
 To: tutor@python.org
 Date: Tue, 14 Sep 2010 19:28:28 +0200
 Subject: Re: [Tutor] FW: wierd replace problem


 - Original message -
 Look at the backslash! It doesn't strip the backslash in the string, but
 it escapes the double quote following it.

 I don't know how people can explain it any better.

 Maybe the link below makes it clear what backslash really does.

 http://pythonconquerstheuniverse.wordpress.com/2008/06/04/gotcha-%e2%80%94-backslashes-are-escape-characters/

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


Oke,

I get it.
When I want to delete a  I have to use a backslash.

For me case closed. Everyone thanks for the patience and explanations.

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


Re: [Tutor] FW: wierd replace problem

2010-09-14 Thread Roelof Wobben




 Date: Tue, 14 Sep 2010 21:05:06 +0100
 Subject: Re: [Tutor] FW: wierd replace problem
 From: wpr...@gmail.com
 To: rwob...@hotmail.com
 CC: tutor@python.org

 Roelof,

 On 14 September 2010 17:35, Roelof Wobben
 wrote:
 But how can I use the triple quotes when reading a textf-file ?

 To repeat what I said before, obviously not clearly enough: All the
 quoting stuff, escaping stuff, all of that ONLY APPLIES TO STRINGS/DATA
 INSIDE OF YOUR PYTHON CODE. It does NOT APPLY TO DATA INSIDE OF
 FILES! Why not to files? Because there's no ambiguity in data inside
 a file. It's understood that everything in a file is just data. By
 contrast, in Python code, quote characters have *meaning*.
 Specifically they indicate the start and end of string literals. So
 when they themselves are part of teh string you have to write them
 specially to indicate their meaning, either as closing the string, or
 as part of the string data.

 In a file by contrast, every character is presumed to be just a piece
 of data, and so quotes have no special inherent meaning to Python, so
 they just represent themselves and always just form part of the data
 being read from the file. Do you understand what I'm saying? If you
 have any doubt please respond so we can try to get this cleared up --
 Unless and until you realise there's a difference between data in a
 file and string literals in your python source code you're not going to
 undertand what you're doing here.

 Regards,

 Walter

 
I understand it but I try to understand why in a file there is this 'word 
python makes a 'word.
I know that a file is just data but I thought that if that data is read in a 
string I could work with the quoting stuff.
But im very wrong here.
 
Roelof
 
  
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] wierd replace problem

2010-09-13 Thread Roelof Wobben

Hello, 

I have this string called test with the contents of 'het is een wonder \\TIS'

Now I want to get rid of the \\ so I do this : test2 = test.replace ('\\', '')
And I get at the python prompt this answer : 'het is een wonder TIS' 
So that's right.

Now I try the same in a IDE with this programm :
 
woorden =[]
letter_counts = {}
file = open ('alice_in_wonderland.txt', 'r')
for line in file:
line2 = line.replace (\\,)
line3 = line2.lower()
woorden = line3.split()
for letter in woorden:
letter_counts[letter] = letter_counts.get (letter, 0) + 1
letter_items = letter_counts.items()
letter_items.sort()
print letter_items 
 
But now Im gettting this output :
 
[('\'tis', 1), 
 
Why does the \ stays here. It should have gone as the test in the python prompt 
says.
 
Roelof


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


[Tutor] wierd replace problem

2010-09-13 Thread Roelof Wobben




 From: rwob...@hotmail.com
 To: bgai...@gmail.com
 Subject: RE: [Tutor] wierd replace problem
 Date: Mon, 13 Sep 2010 15:19:12 +




 
 Date: Mon, 13 Sep 2010 11:07:19 -0400
 From: bgai...@gmail.com
 To: tutor@python.org
 Subject: Re: [Tutor] wierd replace problem

 On 9/13/2010 8:19 AM, Roelof Wobben wrote:
 Hello,

 I have this string called test with the contents of 'het is een wonder 
 \\TIS'

 Now I want to get rid of the \\ so I do this : test2 = test.replace ('\\', 
 '')
 And I get at the python prompt this answer : 'het is een wonder TIS'
 So that's right.

 Now I try the same in a IDE with this programm :

 woorden =[]
 letter_counts = {}
 file = open ('alice_in_wonderland.txt', 'r')
 for line in file:
 line2 = line.replace (\\,)
 line3 = line2.lower()
 woorden = line3.split()
 for letter in woorden:
 letter_counts[letter] = letter_counts.get (letter, 0) + 1
 letter_items = letter_counts.items()
 letter_items.sort()
 print letter_items

 But now Im gettting this output :

 [('\'tis', 1),

 Why does the \ stays here. It should have gone as the test in the python 
 prompt says.
 I ran your program against a 1 line file containing 'het is een wonder
 \\TIS'
 The result I get is [('een', 1), ('het', 1), ('is', 1), ('tis', 1),
 ('wonder', 1)]

 Dunno why you are getting a different result.

 Here is where using the debugger and going step by step can help. I have
 no experience with the IDLE debugger. Perhaps others can offer advice on
 that.

 --
 Bob Gailer
 919-636-4239
 Chapel Hill NC

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


Hello everyone.

Chancing to (r\\, '') or (, '') did not help.

I know that there were more outcome. I would only let see that on the python 
prompt the \ is deleted and if I use Eclipse the / stays when I use the text 
from alice in wonderland.

 And im still wondering why this happens.
 Maybe put the text from alice into the python prompt and look what happens.

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


Re: [Tutor] wierd replace problem

2010-09-13 Thread Roelof Wobben




Date: Mon, 13 Sep 2010 12:17:47 -0400
From: mich...@trollope.org
To: tutor@python.org
Subject: Re: [Tutor] wierd replace problem


On Mon, Sep 13, 2010 at 12:19:23PM +, Roelof Wobben wrote:

 Hello,

 I have this string called test with the contents of 'het is een wonder \\TIS'

 Now I want to get rid of the \\ so I do this : test2 = test.replace ('\\', '')
 And I get at the python prompt this answer : 'het is een wonder TIS'
 So that's right.

 Now I try the same in a IDE with this programm :

 woorden =[]
 letter_counts = {}
 file = open ('alice_in_wonderland.txt', 'r')
 for line in file:
 line2 = line.replace (\\,)
 line3 = line2.lower()
 woorden = line3.split()
 for letter in woorden:
 letter_counts[letter] = letter_counts.get (letter, 0) + 1
 letter_items = letter_counts.items()
 letter_items.sort()
 print letter_items

 But now Im gettting this output :

 [('\'tis', 1),

 Why does the \ stays here. It should have gone as the test in the python 
 prompt says.

Hello,

Actually, on closer look I can see the answer.

The original text must look something like this:

\\'tis the season to be jolly, said santa.

When you run your process against a string in that format, you get the
output shown: ('\'tis', 1). The appearance of the backslash is
fortuitous. It has nothing to do with the string.replace(), it's
there to escape the single quote, which is appearing in the middle of
a single-quoted string. IF the double-quote had not also been there,
python would have replaced the outer quotes with double quotes, as it
does on my system before I got to thinking about that lonely double
quote.

Thanks.

mp

--
Michael Powe mich...@trollope.org Naugatuck CT USA
I wrote what I did because as a woman, as a mother, I was oppressed
and brokenhearted with the sorrows and injustice I saw, because as a
Christian I felt the dishonor to Christianity, -- because as a lover
of my country, I trembled at the coming day of wrath. -- H.B. Stowe

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

 
Hello Michael,
 
The original text is this : 
 
`'Tis so,' said the Duchess:  `and the moral of that is--Oh,
'tis love, 'tis love, that makes the world go round!'

So I think I have to replace the '.
 
Roelof
  
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] wierd replace problem

2010-09-13 Thread Roelof Wobben




 From: rwob...@hotmail.com
 To: joel.goldst...@gmail.com
 Subject: RE: [Tutor] wierd replace problem
 Date: Mon, 13 Sep 2010 16:45:28 +




 
 Date: Mon, 13 Sep 2010 12:42:56 -0400
 From: joel.goldst...@gmail.com
 To: tutor@python.org
 Subject: Re: [Tutor] wierd replace problem



 On Mon, Sep 13, 2010 at 12:37 PM, Roelof Wobben
 wrote:



 
 Date: Mon, 13 Sep 2010 12:17:47 -0400
 From: mich...@trollope.org
 To: tutor@python.org
 Subject: Re: [Tutor] wierd replace problem


 On Mon, Sep 13, 2010 at 12:19:23PM +, Roelof Wobben wrote:

 Hello,

 I have this string called test with the contents of 'het is een
 wonder \\TIS'

 Now I want to get rid of the \\ so I do this : test2 = test.replace
 ('\\', '')
 And I get at the python prompt this answer : 'het is een wonder TIS'
 So that's right.

 Now I try the same in a IDE with this programm :

 woorden =[]
 letter_counts = {}
 file = open ('alice_in_wonderland.txt', 'r')
 for line in file:
 line2 = line.replace (\\,)
 line3 = line2.lower()
 woorden = line3.split()
 for letter in woorden:
 letter_counts[letter] = letter_counts.get (letter, 0) + 1
 letter_items = letter_counts.items()
 letter_items.sort()
 print letter_items

 But now Im gettting this output :

 [('\'tis', 1),

 Why does the \ stays here. It should have gone as the test in the
 python prompt says.

 Hello,

 Actually, on closer look I can see the answer.

 The original text must look something like this:

 \\'tis the season to be jolly, said santa.

 When you run your process against a string in that format, you get the
 output shown: ('\'tis', 1). The appearance of the backslash is
 fortuitous. It has nothing to do with the string.replace(), it's
 there to escape the single quote, which is appearing in the middle of
 a single-quoted string. IF the double-quote had not also been there,
 python would have replaced the outer quotes with double quotes, as it
 does on my system before I got to thinking about that lonely double
 quote.

 Thanks.

 mp

 --
 Michael Powe mich...@trollope.org
 Naugatuck CT USA
 I wrote what I did because as a woman, as a mother, I was oppressed
 and brokenhearted with the sorrows and injustice I saw, because as a
 Christian I felt the dishonor to Christianity, -- because as a lover
 of my country, I trembled at the coming day of wrath. -- H.B. Stowe

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


 Hello Michael,

 The original text is this :

 `'Tis so,' said the Duchess: `and the moral of that is--Oh,
 'tis love, 'tis love, that makes the world go round!'

 So I think I have to replace the '.

 Roelof

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


 That is a completely different problem than the one you originally
 posed. I doubt that what you inserted above is actually completely
 correct. It opens with a back tick, has a back tick before and, then
 ens with what looks like a double quote then a single quote
 --
 Joel Goldstick


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


Hello Joel,

The orginal text can be found here : 
http://openbookproject.net/thinkcs/python/english2e/resources/ch10/alice_in_wonderland.txt
So you can see I copied it right.

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


Re: [Tutor] wierd replace problem

2010-09-13 Thread Roelof Wobben




 From: rwob...@hotmail.com
 To: tutor@python.org
 Date: Mon, 13 Sep 2010 16:46:09 +
 Subject: [Tutor] wierd replace problem




 
 From: rwob...@hotmail.com
 To: joel.goldst...@gmail.com
 Subject: RE: [Tutor] wierd replace problem
 Date: Mon, 13 Sep 2010 16:45:28 +




 
 Date: Mon, 13 Sep 2010 12:42:56 -0400
 From: joel.goldst...@gmail.com
 To: tutor@python.org
 Subject: Re: [Tutor] wierd replace problem



 On Mon, Sep 13, 2010 at 12:37 PM, Roelof Wobben
 wrote:



 
 Date: Mon, 13 Sep 2010 12:17:47 -0400
 From: mich...@trollope.org
 To: tutor@python.org
 Subject: Re: [Tutor] wierd replace problem


 On Mon, Sep 13, 2010 at 12:19:23PM +, Roelof Wobben wrote:

 Hello,

 I have this string called test with the contents of 'het is een
 wonder \\TIS'

 Now I want to get rid of the \\ so I do this : test2 = test.replace
 ('\\', '')
 And I get at the python prompt this answer : 'het is een wonder TIS'
 So that's right.

 Now I try the same in a IDE with this programm :

 woorden =[]
 letter_counts = {}
 file = open ('alice_in_wonderland.txt', 'r')
 for line in file:
 line2 = line.replace (\\,)
 line3 = line2.lower()
 woorden = line3.split()
 for letter in woorden:
 letter_counts[letter] = letter_counts.get (letter, 0) + 1
 letter_items = letter_counts.items()
 letter_items.sort()
 print letter_items

 But now Im gettting this output :

 [('\'tis', 1),

 Why does the \ stays here. It should have gone as the test in the
 python prompt says.

 Hello,

 Actually, on closer look I can see the answer.

 The original text must look something like this:

 \\'tis the season to be jolly, said santa.

 When you run your process against a string in that format, you get the
 output shown: ('\'tis', 1). The appearance of the backslash is
 fortuitous. It has nothing to do with the string.replace(), it's
 there to escape the single quote, which is appearing in the middle of
 a single-quoted string. IF the double-quote had not also been there,
 python would have replaced the outer quotes with double quotes, as it
 does on my system before I got to thinking about that lonely double
 quote.

 Thanks.

 mp

 --
 Michael Powe mich...@trollope.org
 Naugatuck CT USA
 I wrote what I did because as a woman, as a mother, I was oppressed
 and brokenhearted with the sorrows and injustice I saw, because as a
 Christian I felt the dishonor to Christianity, -- because as a lover
 of my country, I trembled at the coming day of wrath. -- H.B. Stowe

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


 Hello Michael,

 The original text is this :

 `'Tis so,' said the Duchess: `and the moral of that is--Oh,
 'tis love, 'tis love, that makes the world go round!'

 So I think I have to replace the '.

 Roelof

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


 That is a completely different problem than the one you originally
 posed. I doubt that what you inserted above is actually completely
 correct. It opens with a back tick, has a back tick before and, then
 ens with what looks like a double quote then a single quote
 --
 Joel Goldstick


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


 Hello Joel,

 The orginal text can be found here : 
 http://openbookproject.net/thinkcs/python/english2e/resources/ch10/alice_in_wonderland.txt
 So you can see I copied it right.

 Roelof
 ___
 Tutor maillist - Tutor@python.org
 To unsubscribe or change subscription options:
 http://mail.python.org/mailman/listinfo/tutor
 
Hello, 
 
I tried my programm in IDLE and the problem stays.
So I think it has to do with the text-file and how python reads it.
 
Roelof

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


Re: [Tutor] wierd replace problem

2010-09-13 Thread Roelof Wobben




 To: tutor@python.org
 From: alan.ga...@btinternet.com
 Date: Mon, 13 Sep 2010 18:28:46 +0100
 Subject: Re: [Tutor] wierd replace problem


 Roelof Wobben wrote

 Now I want to get rid of the \\ so I do this : test2 = test.replace
 ('\\', '')
 And I get at the python prompt this answer : 'het is een wonder TIS'
 So that's right.

 OK,. Thats replacing a double slash in the data

 for line in file:
 line2 = line.replace (\\,)

 And this is doing the same. Any double slashes in your file content
 will be replaced.

 letter_items = letter_counts.items()
 letter_items.sort()
 print letter_items

 Now we have an issue of representing characters.

 [('\'tis', 1),

 This is a representation issue. Python is using the \ to escape
 the single quote since you are using single quotes on the outside.
 Without the backslash the \' would look like the end of the
 string to Python.

 If you print the actual string it will not show the quote:

 for item in letter_items:
 print item[0]

 Backslashes are awkward characters because they are used
 for several different special purposes as well as being characters
 in their own right. If you had tried replacing almost any other
 character you would not have gotten confused.

 HTH,

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




 Why does the \ stays here. It should have gone as the test in the
 python prompt says.

 Roelof



 ___
 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
 
hello Alan, 
 
Your right. Then it prints like this 'tis
Which is not right. It must be tis.
So the replace does not what it supposed to do.
 
Roelof

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


[Tutor] FW: wierd replace problem

2010-09-13 Thread Roelof Wobben





 From: rwob...@hotmail.com
 To: bgai...@gmail.com
 Subject: RE: [Tutor] wierd replace problem
 Date: Mon, 13 Sep 2010 18:19:43 +




 
 Date: Mon, 13 Sep 2010 14:08:46 -0400
 From: bgai...@gmail.com
 To: tutor@python.org
 Subject: Re: [Tutor] wierd replace problem

 On 9/13/2010 1:50 PM, Roelof Wobben wrote:

 [snip]
 hello Alan,

 Your right. Then it prints like this 'tis
 Which is not right. It must be tis.
 So the replace does not what it supposed to do.

 Sorry but I am now more confused. After discovering no \ in the text
 file now you seem to have have a new specification, which is to get rid
 of the '.

 I suggest you give a clear, complete and correct problem statement.
 Right now we are shooting in the dark at a moving target.

 Something like.

 Given the file alice_in_wonderland.txt, copied from url so-and-so

 Remove these characters ...

 Split into words (not letters?) where word is defined as

 Count the frequency of each word.

 --
 Bob Gailer
 919-636-4239
 Chapel Hill NC

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

 Hello,

 The problem as stated in the book is :


3.Write a program called alice_words.py that creates a text file named 
alice_words.txt containing an alphabetical listing of all the words found in 
alice_in_wonderland.txt together with the number of times each word occurs. The 
first 10 lines of your output file should look something like this:
Word Count
===
a 631
a-piece 1
abide 1
able 1
about 94
above 3
absence 1
absurd 2How many times does the word, alice, occur in the book?

The text can be found here : 
http://openbookproject.net/thinkcs/python/english2e/resources/ch10/alice_in_wonderland.txt

So I open the file.
Read the first rule.

This is no problem for me.

Then I want to remove some characters like ' ,  when the word in the text 
begins with these characters.
And there is the problem. The ' and  can't be removed with replace.
So in the output you will see something like this dark instead of dark

word is the words of the sentence which is read in from the text-file.

Am i now clear what the problem is Im facing.

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


[Tutor] FW: wierd replace problem

2010-09-13 Thread Roelof Wobben




 From: rwob...@hotmail.com
 To: joel.goldst...@gmail.com
 Subject: RE: [Tutor] wierd replace problem
 Date: Mon, 13 Sep 2010 18:23:36 +




 
 Date: Mon, 13 Sep 2010 14:18:36 -0400
 From: joel.goldst...@gmail.com
 To: tutor@python.org
 Subject: Re: [Tutor] wierd replace problem



 On Mon, Sep 13, 2010 at 2:08 PM, bob gailer
 wrote:
 On 9/13/2010 1:50 PM, Roelof Wobben wrote:

 [snip]

 hello Alan,

 Your right. Then it prints like this 'tis
 Which is not right. It must be tis.
 So the replace does not what it supposed to do.

 Sorry but I am now more confused. After discovering no \ in the text
 file now you seem to have have a new specification, which is to get rid
 of the '.

 I suggest you give a clear, complete and correct problem statement.
 Right now we are shooting in the dark at a moving target.

 Something like.

 Given the file alice_in_wonderland.txt, copied from url so-and-so

 Remove these characters ...

 Split into words (not letters?) where word is defined as

 Count the frequency of each word.


 --
 Bob Gailer
 919-636-4239
 Chapel Hill NC

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

 How about using str.split() to put words in a list, then run strip()
 over each word with the required characters to be removed ('`)

 --
 Joel Goldstick


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


Hello Joel.

That can be a solution but when i have --dark the -- must be removed.
But in a-piece the - must not be removed.

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


Re: [Tutor] FW: wierd replace problem

2010-09-13 Thread Roelof Wobben




 Date: Mon, 13 Sep 2010 15:31:08 -0400
 Subject: Re: [Tutor] FW: wierd replace problem
 From: joel.goldst...@gmail.com
 To: rwob...@hotmail.com



 On Mon, Sep 13, 2010 at 2:24 PM, Roelof Wobben
 wrote:



 
 From: rwob...@hotmail.com
 To: joel.goldst...@gmail.com
 Subject: RE: [Tutor] wierd replace problem
 Date: Mon, 13 Sep 2010 18:23:36 +




 
 Date: Mon, 13 Sep 2010 14:18:36 -0400
 From: joel.goldst...@gmail.com
 To: tutor@python.org
 Subject: Re: [Tutor] wierd replace problem



 On Mon, Sep 13, 2010 at 2:08 PM, bob gailer
 wrote:
 On 9/13/2010 1:50 PM, Roelof Wobben wrote:

 [snip]

 hello Alan,

 Your right. Then it prints like this 'tis
 Which is not right. It must be tis.
 So the replace does not what it supposed to do.

 Sorry but I am now more confused. After discovering no \ in the text
 file now you seem to have have a new specification, which is to get rid
 of the '.

 I suggest you give a clear, complete and correct problem statement.
 Right now we are shooting in the dark at a moving target.

 Something like.

 Given the file alice_in_wonderland.txt, copied from url so-and-so

 Remove these characters ...

 Split into words (not letters?) where word is defined as

 Count the frequency of each word.


 --
 Bob Gailer
 919-636-4239
 Chapel Hill NC

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

 How about using str.split() to put words in a list, then run strip()
 over each word with the required characters to be removed ('`)

 --
 Joel Goldstick


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


 Hello Joel.

 That can be a solution but when i have --dark the -- must be removed.
 But in a-piece the - must not be removed.

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

 strip only removes from start and end of string. Not from the middle,
 so a-piece would stay as a word

 --
 Joel Goldstick

 
Oke, 
 
I have tried that but then I see this message :
 
 File C:\Users\wobben\workspace\oefeningen\src\test.py, line 8
letter2 = letter.strip('`)
  ^
SyntaxError: EOL while scanning string literal
 
Change it to (''`) do not help either.
 
Roelof

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


[Tutor] recursive problem

2010-09-12 Thread Roelof Wobben




 From: rwob...@hotmail.com
 To: st...@pearwood.info
 Subject: RE: [Tutor] recursive problem
 Date: Sun, 12 Sep 2010 07:58:48 +




 
 From: st...@pearwood.info
 To: tutor@python.org
 Date: Sun, 12 Sep 2010 10:10:53 +1000
 Subject: Re: [Tutor] recursive problem

 On Sun, 12 Sep 2010 09:03:49 am Walter Prins wrote:

 So, perhaps it's an idea to call dir() on a given object and see
 whether the object provides the necessary methods to function, e.g.
 __iter__, __delitem__, __setitem__ and friends?

 There's no need to do this:

 attributes = dir(obj)
 if '__iter__' in attributes and '__len__' in attributes:
 print Quacks like a list
 else:
 print Not like a list


 when you can do this:


 if hasattr(obj, '__iter__') and hasattr(obj, '__len__'):
 print Quacks like a list
 else:
 print Not like a list


 or this:

 try:
 obj.__iter__
 obj.__len__
 except AttributeError:
 print Not like a list
 else:
 print Quacks like a list


 or even

 try:
 iter(obj)
 len(obj)
 except TypeError:
 print Not like a list
 else:
 print Quacks like a list


 Where possible, the last version is to be preferred, because it doesn't
 care about internal details which might change.



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



Oke,

This is to far for me.
Im only at chapter 11 and this stuff will be in chapter 13 and further.

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


[Tutor] tree problem

2010-09-12 Thread Roelof Wobben


Hello, 

I have this problem.

Write a program named litter.py that creates an empty file named trash.txt in 
each subdirectory of a directory tree given the root of the tree as an argument 
(or the current directory as a default). 

So I change the example to this :

def traverse(path, s='.\n', f=0, d=0):
path2file = os.path.join(path) *** pathfile contains the path 
if os.path.isdir(path2file):  if pathfile is a dir.
d += 1 * the is one more directory
if getdirlist(path2file): ** if the outcome of getdirlist is the same as 
the current directory
s, f, d = traverse(path2file, '| ' + s, f, d) do this module again
else:
f += 1 ** else f (number of files increases with 1 
return s, f, d ** return s , numbers of files and the number of directories.


When I try to make it run I get this message :

File C:\Users\wobben\workspace\oefeningen\src\test.py, line 31, in traverse
s, f, d = traverse(path2file, '| ' + s, f, d)
File C:\Users\wobben\workspace\oefeningen\src\test.py, line 31, in traverse
s, f, d = traverse(path2file, '| ' + s, f, d)
File C:\Users\wobben\workspace\oefeningen\src\test.py, line 31, in traverse
s, f, d = traverse(path2file, '| ' + s, f, d)
File C:\Users\wobben\workspace\oefeningen\src\test.py, line 28, in traverse
if os.path.isdir(path2file):
File C:\Python27\lib\genericpath.py, line 44, in isdir
return stat.S_ISDIR(st.st_mode)
File C:\Python27\lib\stat.py, line 41, in S_ISDIR
return S_IFMT(mode) == S_IFDIR
RuntimeError: maximum recursion depth exceeded

I can't see why this happens.
I know I have to fish but I can't see what's wrong here.
So I hope someone can learn how to fish here.

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


Re: [Tutor] tree problem

2010-09-12 Thread Roelof Wobben




 Subject: Re: [Tutor] tree problem
 From: evert@gmail.com
 Date: Sun, 12 Sep 2010 13:29:12 +0200
 CC: tutor@python.org
 To: rwob...@hotmail.com

 Write a program named litter.py that creates an empty file named trash.txt 
 in each subdirectory of a directory tree given the root of the tree as an 
 argument (or the current directory as a default).

 So I change the example to this :

 def traverse(path, s='.\n', f=0, d=0):
 path2file = os.path.join(path) *** pathfile contains the path
 if os.path.isdir(path2file):  if pathfile is a dir.
 d += 1 * the is one more directory
 if getdirlist(path2file): ** if the outcome of getdirlist is the same as 
 the current directory
 s, f, d = traverse(path2file, '| ' + s, f, d) do this module again
 else:
 f += 1 ** else f (number of files increases with 1
 return s, f, d ** return s , numbers of files and the number of 
 directories.

 That can't be a valid program: no indentation, comments not preceded by a 
 comment mark (#), and getdirlist is nowhere defined afaics. While probably 
 anyone can understand what's the real code of the above snippet, it doesn't 
 help putting non-valid code like this in your email. If you can directly 
 copy-paste code (plain text), that is almost always better.


 When I try to make it run I get this message :

 File C:\Users\wobben\workspace\oefeningen\src\test.py, line 31, in traverse
 s, f, d = traverse(path2file, '| ' + s, f, d)
 File C:\Users\wobben\workspace\oefeningen\src\test.py, line 31, in traverse
 s, f, d = traverse(path2file, '| ' + s, f, d)
 File C:\Users\wobben\workspace\oefeningen\src\test.py, line 31, in traverse
 s, f, d = traverse(path2file, '| ' + s, f, d)
 File C:\Users\wobben\workspace\oefeningen\src\test.py, line 28, in traverse
 if os.path.isdir(path2file):
 File C:\Python27\lib\genericpath.py, line 44, in isdir
 return stat.S_ISDIR(st.st_mode)
 File C:\Python27\lib\stat.py, line 41, in S_ISDIR
 return S_IFMT(mode) == S_IFDIR
 RuntimeError: maximum recursion depth exceeded

 I can't see why this happens.
 I know I have to fish but I can't see what's wrong here.
 So I hope someone can learn how to fish here.

 Fishing is debugging. You could use the logging module for that, but assuming 
 you're not familiar with that, litter your program with print statements, and 
 print out the value of the various variables at certain points in your 
 program (it helps putting a short string in the print statement as well, so 
 you know which print statement print where. Eg, print '1:', s, f, d; and then 
 a few lines below, print '2:', s, f, d).
 Having done that (you will get a lot of output), try to follow the logic of 
 the program and see why things happen the way they do. In this case, why you 
 keep spiraling in and never break out of your recursion. Then, step by step, 
 you can try and change or add statements so you actually find a way to break 
 out the recursion.

 Evert

 
Hello Evert.
 
Sorry but the change to plain text destroyed also this.
 
What I have it this.
 
def getdirlist(path):
dirlist = os.listdir(path)
dirlist = [name for name in dirlist if name[0] != '.']
dirlist.sort()
return dirlist

def traverse(path, s='.\n', f=0, d=0):
dirlist = getdirlist(path)
for file in enumerate(dirlist):
print file
path2file = os.path.join(path)
if os.path.isdir(path2file):
d += 1
if getdirlist(path2file):
print path2file
myfile = open ('trash.txt', 'w')
myfile.close () 
return s, f, d
 
The file is made. Now find out why it doesn't go into the next level.
With this : s, f, d = traverse(path2file, '|   ' + s, f, d) I goes into a loop 
which never ends.
 
Roelof


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


Re: [Tutor] tree problem

2010-09-12 Thread Roelof Wobben




 Date: Sun, 12 Sep 2010 09:46:08 -0400
 From: joel.goldst...@gmail.com
 To: tutor@python.org
 Subject: Re: [Tutor] tree problem



 On Sun, Sep 12, 2010 at 9:32 AM, Roelof Wobben
 wrote:


 
 Date: Sun, 12 Sep 2010 09:08:18 -0400
 From: joel.goldst...@gmail.com
 To: tutor@python.org

 Subject: Re: [Tutor] tree problem



 On Sun, Sep 12, 2010 at 7:54 AM, Lie Ryan
 wrote:
 On 09/12/10 21:15, Roelof Wobben wrote:


 Hello,

 I have this problem.

 Write a program named litter.py that creates an empty file named
 trash.txt in each subdirectory of a directory tree given the root of
 the tree as an argument (or the current directory as a default).

 By default, Python has a recursion limit of 1000 deep; that is, your
 function is calling itself 1000 times without returning.

 In this case, the only reason why you hit the recursion limit is if you
 have a directory which is 1000 deep (quite unlikely, Windows has a
 directory depth limit much lower than that).

 Or your function somehow never returns, in a typical recursive function,
 it's usually because you have problem in the precondition.

 You really have two problems here:

 1. You need to know how to write an empty file with the name
 litter.py. You should probably write a function to see if you can do
 that. That's pretty easy

 2. You need to traverse a tree. I see you are using os module. You
 should try help(os) while in your python shell to learn what methods
 are available. Traversing a tree is also sometimes called 'walking'

 good luck


 --
 Joel Goldstick


 ___ Tutor maillist -

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

 Hello Joel.

 Youre right.
 Problem 1 is easily solved by using myfile = open ('filename', 'w')
 followed by myfile.close()

 Problem 2 is more difficult.

 I have to use recursion and as example the source of the tree command
 in linux is given.
 The traverse module looks like this :

 def traverse(path, prefix='|--', s='.\n', f=0, d=0):

 what's up with the prefix???

 dirlist = getdirlist(path)
 for num, file in enumerate(dirlist):

 why are you using enumerate? it gives you num which you never use
 for file in dirlist gives what you seem to be using
 lastprefix = prefix[:-3] + '``--'
 dirsize = len(dirlist)
 if num  dirsize - 1:
 s += '%s %s\n' % (prefix, file)
 else:
 s += '%s %s\n' % (lastprefix, file)
 path2file = os.path.join(path, file)

 if os.path.isdir(path2file):
 d += 1
 if getdirlist(path2file):
 s, f, d = traverse(path2file, '| ' + prefix, s, f, d)
 else:
 f += 1
 return s, f, d

 For me it looks like the pathfile = os.path.join(path, file)
 and then the s.f.d. rule take care that a subdir is entered.
 what are s.f.d. Can you use more descriptive names

 Am I right on this ?

 Roelof





 --
 Joel Goldstick


 ___ Tutor maillist -
 Tutor@python.org To unsubscribe or change subscription options:
 http://mail.python.org/mailman/listinfo/tutor
 
Hello, 
 
I solved this by this programm :
 
import os
import sys

def getroot():
if len(sys.argv) == 1:
path = ''
else:
path = sys.argv[1]
if os.path.isabs(path):
tree_root = path
else:
tree_root = os.path.join(os.getcwd(), path)
return tree_root

def getdirlist(path):
dirlist = os.listdir(path)
dirlist = [name for name in dirlist if name[0] != '.']
dirlist.sort()
return dirlist

def traverse(path, s='.\n', f=0, d=0):
file = os.path.join(path,'trash.txt')
myfile = open (file, 'w')
myfile.close()
dirlist = getdirlist(path)
for num, file in enumerate(dirlist):
dirsize = len(dirlist)
if num  dirsize - 1:
s += '%s \n' % (file)
else:
s += '%s \n' % (file)
path2file = os.path.join(path, file)
if os.path.isdir(path2file):
d += 1
s, f, d = traverse(path2file, '|   ' + s, f, d)
return s,f,d

if __name__ == '__main__':
root =  getroot()
tree_str, files, dirs = traverse(root)

 
Roelof

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


Re: [Tutor] tree problem

2010-09-12 Thread Roelof Wobben




 Date: Sun, 12 Sep 2010 13:40:09 -0400
 Subject: Re: [Tutor] tree problem
 From: joel.goldst...@gmail.com
 To: rwob...@hotmail.com



 On Sun, Sep 12, 2010 at 1:20 PM, Roelof Wobben
 wrote:



 
 Date: Sun, 12 Sep 2010 11:59:07 -0400
 From: joel.goldst...@gmail.com
 To: tutor@python.org
 Subject: Re: [Tutor] tree problem



 On Sun, Sep 12, 2010 at 10:48 AM, Roelof Wobben
 wrote:



 
 Date: Sun, 12 Sep 2010 09:46:08 -0400
 From: joel.goldst...@gmail.com
 To: tutor@python.org
 Subject: Re: [Tutor] tree problem



 On Sun, Sep 12, 2010 at 9:32 AM, Roelof Wobben
 wrote:


 
 Date: Sun, 12 Sep 2010 09:08:18 -0400
 From: joel.goldst...@gmail.com
 To: tutor@python.org

 Subject: Re: [Tutor] tree problem



 On Sun, Sep 12, 2010 at 7:54 AM, Lie Ryan
 wrote:
 On 09/12/10 21:15, Roelof Wobben wrote:


 Hello,

 I have this problem.

 Write a program named litter.py that creates an empty file named
 trash.txt in each subdirectory of a directory tree given the root of
 the tree as an argument (or the current directory as a default).

 By default, Python has a recursion limit of 1000 deep; that is, your
 function is calling itself 1000 times without returning.

 In this case, the only reason why you hit the recursion limit is if you
 have a directory which is 1000 deep (quite unlikely, Windows has a
 directory depth limit much lower than that).

 Or your function somehow never returns, in a typical recursive function,
 it's usually because you have problem in the precondition.

 You really have two problems here:

 1. You need to know how to write an empty file with the name
 litter.py. You should probably write a function to see if you can do
 that. That's pretty easy

 2. You need to traverse a tree. I see you are using os module. You
 should try help(os) while in your python shell to learn what methods
 are available. Traversing a tree is also sometimes called 'walking'

 good luck


 --
 Joel Goldstick


 ___ Tutor maillist -

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

 Hello Joel.

 Youre right.
 Problem 1 is easily solved by using myfile = open ('filename', 'w')
 followed by myfile.close()

 Problem 2 is more difficult.

 I have to use recursion and as example the source of the tree command
 in linux is given.
 The traverse module looks like this :

 def traverse(path, prefix='|--', s='.\n', f=0, d=0):

 what's up with the prefix???

 dirlist = getdirlist(path)
 for num, file in enumerate(dirlist):

 why are you using enumerate? it gives you num which you never use
 for file in dirlist gives what you seem to be using
 lastprefix = prefix[:-3] + '``--'
 dirsize = len(dirlist)
 if num  dirsize - 1:
 s += '%s %s\n' % (prefix, file)
 else:
 s += '%s %s\n' % (lastprefix, file)
 path2file = os.path.join(path, file)

 if os.path.isdir(path2file):
 d += 1
 if getdirlist(path2file):
 s, f, d = traverse(path2file, '| ' + prefix, s, f, d)
 else:
 f += 1
 return s, f, d

 For me it looks like the pathfile = os.path.join(path, file)
 and then the s.f.d. rule take care that a subdir is entered.
 what are s.f.d. Can you use more descriptive names

 Am I right on this ?

 Roelof





 --
 Joel Goldstick


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

 Hello,

 I solved this by this programm :

 import os
 import sys

 def getroot():
 if len(sys.argv) == 1:
 path = ''
 else:
 path = sys.argv[1]
 if os.path.isabs(path):
 tree_root = path
 else:
 tree_root = os.path.join(os.getcwd(), path)
 return tree_root

 def getdirlist(path):
 dirlist = os.listdir(path)
 dirlist = [name for name in dirlist if name[0] != '.']
 dirlist.sort()
 return dirlist

 def traverse(path, s='.\n', f=0, d=0):
 file = os.path.join(path,'trash.txt')
 myfile = open (file, 'w')
 myfile.close()
 dirlist = getdirlist(path)
 for num, file in enumerate(dirlist):
 dirsize = len(dirlist)
 if num  dirsize - 1:
 s += '%s \n' % (file)
 else:
 s += '%s \n' % (file)
 path2file = os.path.join(path, file)
 if os.path.isdir(path2file):
 d += 1
 s, f, d = traverse(path2file, '| ' + s, f, d)
 return s,f,d

 if __name__ == '__main__':
 root = getroot()
 tree_str, files, dirs = traverse(root)


 Roelof


 Good for you. Some questions:

 What do you mean to be happening here:

 if num  dirsize - 1:
 s += '%s \n' % (file)
 else:
 s += '%s \n' % (file)

 it does the same thing in either case

 What exactly does s do for you?

 You use the first parameter 'path' in your calls to traverse, but I
 don't see how you are using f or d anywhere either
 --
 Joel Goldstick


 ___ Tutor maillist -
 Tutor@python.org To unsubscribe or change
 subscription options:
 http

Re: [Tutor] recursive problem

2010-09-12 Thread Roelof Wobben




 To: tutor@python.org
 From: alan.ga...@btinternet.com
 Date: Sun, 12 Sep 2010 20:52:06 +0100
 Subject: Re: [Tutor] recursive problem

 Roelof Wobben wrote

 I guess the question to ask/consider is: How can be establish
 whether a
 particular object supports a particular interface/set of
 behaviours

 In general we try it and handle the exceptions

 that we require? E.g. how do we most pythonically check whether
 some
 object walks like a list and quacks like a list without tying
 such
 code to explicit type checking?

 But the risk is that although it may quack, it does so like a missile
 launch program rather than a list - oops! :-)

 With the knowlegde I have from the few chapters of thinking like
 a computer scientist I don't know the answer to the last question.

 If you do need to avoid accidentally launching missiles then you need
 to do some type checking - although ideally using isinstance() instead
 of type(). But in the majority of cases some sensible documentation
 and Python's culture that we are all adults here usually means you
 don't
 need to.

 HTH,

 --
 Alan Gauld
 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
 
Hello Alan, 
 
The last chapter I don't understand completly.
Do i have no need for type checking or make use of isinstance() or do I 
misunderstood you.
Sorry that English is not a language I speak very well.
 
Roelof

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


Re: [Tutor] exceptions problem

2010-09-11 Thread Roelof Wobben




 Date: Sat, 11 Sep 2010 11:05:54 -0400
 From: bgai...@gmail.com
 To: tutor@python.org
 Subject: Re: [Tutor] exceptions problem

 On 9/11/2010 6:56 AM, Peter Otten wrote:
 Steven D'Aprano wrote:

 On Sat, 11 Sep 2010 09:56:41 am bob gailer wrote:
 I never thought that you can use a float and a integer to look if
 the number is a integer.
 You can't.

 I made that comment in the context of the OPs function:

 def readposint():
 x = raw_input(Please enter a positive integer :)
 try:
 if (int(x)0 or (float(x) - int(x) 0)): raise(ValueError)
 except:
 print x , is not a positive integer. Try again.
 return -1
 return x

 The OP thought (incorrectly) that, given for example:
 x = '3.1'
 float(x) - int(x) would evaluate to 0.1

 In reality int(x) in this case raises an exception.
 ValueError: invalid literal for int() with base 10: '3.1'

 Since the expression was in a try he could not tell exactly what was
 happening.

 I also don't quite understand the use of raise in the try.

 I wish and hope that Roelof will learn how to do program walkthroughs
 and use the interactive prompt to solve things himself. I applaud the
 patience some of you have ih hand-holding him. I don't have that
 patience. I wish him to learn to fish.

 --
 Bob Gailer
 919-636-4239
 Chapel Hill NC

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

Hello Bob, 
 
Oke, I try to  fish.
 
When I do 
 
x= a
y= int(x) 
Then I get ValueError.
 
When I do 
 
x= 1.2
y=int(x)
No exception is raised.
But when I do then x ==y I get a false.
When I now do float(x) - int(x) I get 1.2 - 1 = 0.2 and that's greater then 0 
 
Because one of the two is true the Raise is executed.
 
 
x = -9 
y=int(x) 
No exception is raised.
X == y is True.
But float(x) - int(x) I get 0.0 and 0.0 0 is False.
Because x == y is True the Raise is executed.
 
Are these the right conclusions ??
 
Roelof
 
 
  
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] recursive problem

2010-09-11 Thread Roelof Wobben




 From: st...@pearwood.info
 To: tutor@python.org
 Date: Sun, 12 Sep 2010 03:18:19 +1000
 Subject: Re: [Tutor] recursive problem

 On Fri, 10 Sep 2010 09:30:23 pm Ewald Horn wrote:

 While EAFP is great, it's not
 always the best way to proceed.

 That, at least, is correct. But what you say next is not:

 Sometimes you want programs to be
 very robust and secure, this is where LBYL comes in - it is quite
 often used in online transaction processing and other areas where
 absolute certainty is more important than any other consideration.

 If what you are saying is correct, and I doubt seriously that it is,
 then chances are good that they're not succeeding in their aim.

 EAFP tends to use less code and is faster to use, while LBYL
 principles makes your program more bulletproof.

 That's almost 100% backwards.

 Let's take a simple example: you want to open a file, and deal with the
 case of the file being missing:

 filename = 'myfile.txt' # whatever...
 fp = open(filename)
 do_something_with(fp)

 Let's add some error checking. With EAFP, you get this:

 try:
 fp = open(filename)
 except IOError:
 handle_error()


 With LBYL, you get:

 if os.path.exists(filename):
 fp = open(filename)
 else:
 handle_error()


 The amount of code is about the same, but the try...except block
 automatically handles a whole slew of errors -- missing files,
 permission denied, bad file names, corrupt disks, all sorts of things
 that would be difficult or tedious to Look Before You Leap. Some of
 these things -- like disk corruption -- you simply can't check ahead of
 time. There is no way of knowing if a file is corrupt without actually
 opening and/or reading from it.

 It gets worse. Your computer is a multitasking system. Virtually all
 computers are these days, yes, even the iPhone. Even if os.path.exists
 returns True, there is no guarantee that the file will still be there a
 millisecond later when you try to open it. Perhaps the operating
 system, or some other process, has deleted the file or renamed it.
 That's a bug waiting to happen -- a race condition.

 So if you're silly, you write this:

 if os.path.exists(filename):
 try:
 fp = open(filename)
 except IOError:
 handle_error()
 else:
 handle_error()

 If you're sensible, you realise that for reliable, secure code, checking
 for existence *before* opening the file is a waste of time and energy.
 It's barely acceptable for quick and dirty scripts, certainly not for
 high reliability applications.

 This is not the only sort of race condition. Imagine you're writing one
 of these high reliability online transactions you talked about, and you
 want to transfer money from one account to another:

 amount = 1000.00
 if balance= amount:
 transfer(old_account, new_account, amount)
 else:
 insufficient_balance()


 Wait a second... that looks almost exactly like the LBYL code above, and
 it is vulnerable to the same sort of race condition if multiple
 processes can connect to the account at the same time. Does your bank
 allow you to log in twice? Does it have automatic transfers? If so,
 then one process can be transferring money while the other is checking
 the balance, and you have a bug waiting to happen.

 In practice, the banks allow accounts to become temporarily overdrawn,
 and often charge you for the privilege. And they write complicated code
 that looks like this:


 lock_id = lock_account() # Stop anything else from transferring funds.
 while lock_id == 0
 # Lock failed, wait a second and try again.
 time.sleep(1)
 lock_id = lock_account()
 if number_of_attempts() 10:
 handle_error(internal error, please try again)
 # Now it's safe to check the balance.
 if balance= amount:
 transfer(old_account, new_account, amount, lock_id)
 else:
 insufficient_balance()
 # Don't forget to unlock the account, or there will be trouble later!
 errcode = unlock_account(lock_id)
 if errcode != 0:
 # This should never happen. If it does, it might mean the lock ID
 # is incorrect (how?), but probably means the database is corrupt.
 log_serious_error(errcode, lock_id)


 It's ugly and error-prone, but it's also a kind of EAFP: instead of
 checking whether a lock is available, and then taking it, you just try
 to acquire a lock, and deal with the consequences of not receiving one
 if it fails. The only difference is that you're manually checking an
 error code rather than catching an exception.

 Whatever mechanism is used for EAFP, it is most often shorter, simpler,
 more reliable and safer than LBYL.

 So why would anyone ever use LBYL? Well, sometimes it is more convenient
 for quick and dirty scripts, such as using os.path.exists. But more
 importantly, sometimes you need a transaction to apply in full, or not
 at all. You can't do this:

 try:
 do_this()
 do_that()
 do_something_else()
 except Exception:
 do_error()


 because if do_this() succeeds and do_that() fails, you might leave your
 data is a seriously inconsistent or 

Re: [Tutor] recursive problem

2010-09-11 Thread Roelof Wobben




 From: st...@pearwood.info
 To: tutor@python.org
 Date: Sun, 12 Sep 2010 03:27:42 +1000
 Subject: Re: [Tutor] recursive problem

 On Sun, 12 Sep 2010 03:18:19 am Steven D'Aprano wrote:

 But that hasn't done anything to prevent race conditions. So the real
 reason people use LBYL is that they're too lazy to write hideously
 ugly, but reliable, code, and they're just hoping that they will
 never expose the race condition. (Often this is a pretty safe hope,
 but not always.)

 http://en.wikipedia.org/wiki/Ostrich_algorithm


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

Oke,
 
But why is type checking then wrong.
Lets says I want a module who must work on strings, tuple and lists.
 
Can I then use EAFP ?
 
Without type checking I never know which one is used now.
 
Roelof
  
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] recursive problem

2010-09-11 Thread Roelof Wobben




 From: rwob...@hotmail.com
 To: wpr...@gmail.com
 Subject: RE: [Tutor] recursive problem
 Date: Sat, 11 Sep 2010 18:05:12 +




 
 Date: Sat, 11 Sep 2010 19:01:39 +0100
 Subject: Re: [Tutor] recursive problem
 From: wpr...@gmail.com
 To: rabidpoob...@gmail.com
 CC: rwob...@hotmail.com; tutor@python.org


 That's the whole point! You don't WANT to know what type it is. You
 want to just use it how you want, an if it behaves properly, who cares
 what type it is?

 See when you type check you are forcing the user to use those types.
 What if they want to derive a subclass from list? Is there really a
 reason why you should prevent them from using that subclass with your
 function?
 If there is a valid reason, type checking is fine. But if there isn't,
 type checking is just making your code more inflexible.


 Well, I would submit that if were going to do type checking in such a
 context you'd probably check for a base class, so deriving a subclass
 wouldn't break entirely. Your point still stands however, we don't
 even want to require from users to derive from class list. We'd be
 quite happy to work with any object that walks like a list and
 quacks like a list, that's the beauty of duck typing...

 I guess the question to ask/consider is: How can be establish whether a
 particular object supports a particular interface/set of behaviours
 that we require? E.g. how do we most pythonically check whether some
 object walks like a list and quacks like a list without tying such
 code to explicit type checking?

 Walter

 Exactly what I mean.

 With the knowlegde I have from the few chapters of thinking like a computer 
 scientist I don't know the answer to the last question.


 Roelof

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


Re: [Tutor] recursive problem

2010-09-11 Thread Roelof Wobben




 From: st...@pearwood.info
 To: tutor@python.org
 Date: Sun, 12 Sep 2010 04:03:43 +1000
 Subject: Re: [Tutor] recursive problem

 On Sun, 12 Sep 2010 03:40:38 am Roelof Wobben wrote:

 But why is type checking then wrong.
 Lets says I want a module who must work on strings, tuple and lists.

 It's not *always* wrong, but let me ask you... why do you want to
 *limit* the function to work on ONLY strings, tuples and lists?

 The Python philosophy is duck typing -- if it walks like a duck, and
 swims like a duck, it is close enough to a duck that we don't care that
 it's not actually a duck, but a goose.

 Here's an example:


 def f1(x):
 if type(x) is int or type(x) is float:
 print(x + 1 = %s % (x+1))
 else:
 print(x is not a number)


 def f2(x):
 try:
 print(x + 1 = %s % (x+1))
 except (ValueError, TypeError):
 print(x is not a number)

 f1(3)
 x + 1 = 4
 from decimal import Decimal
 f1(Decimal(3))
 x is not a number
 f2(Decimal(3))
 x + 1 = 4

 Function f1 makes the assumption that only ints and floats can be added,
 and so it gives the wrong results with Decimal numbers. But function f2
 uses duck typing -- it doesn't care what sort of number x is, only
 that it can be added.



 Can I then use EAFP ?

 Without type checking I never know which one is used now.


 Going back to type-checking... sometimes you can't avoid it. Sometimes
 you use it because it is easier, and you don't care enough to write
 more complicated code. Sometimes you really do care what the type is:

 abc[2.0]
 Traceback (most recent call last):
 File , line 1, in 
 TypeError: string indices must be integers



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

Hello Steven,
 
Because I follow this book Thinking like a computer scientist and I have only 
read the chapters about strings. lists and tuples.

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


[Tutor] recursive problem

2010-09-11 Thread Roelof Wobben




 From: rwob...@hotmail.com
 To: st...@pearwood.info
 Subject: RE: [Tutor] recursive problem
 Date: Sat, 11 Sep 2010 18:39:31 +




 
 From: st...@pearwood.info
 To: tutor@python.org
 Date: Sun, 12 Sep 2010 04:19:57 +1000
 Subject: Re: [Tutor] recursive problem

 On Sun, 12 Sep 2010 04:09:20 am Roelof Wobben wrote:

 On Sun, 12 Sep 2010 03:40:38 am Roelof Wobben wrote:
 But why is type checking then wrong.
 Lets says I want a module who must work on strings, tuple and
 lists.

 It's not *always* wrong, but let me ask you... why do you want to
 *limit* the function to work on ONLY strings, tuples and lists?

 Because I follow this book Thinking like a computer scientist and I
 have only read the chapters about strings. lists and tuples.

 Good answer!

 Don't worry about all the complications. Learn to walk first, then learn
 to run.



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


 Oke,

So EAFP for me is one step to far ?

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


Re: [Tutor] recursive problem

2010-09-10 Thread Roelof Wobben

Hello , 

 

So my book teach me the wrong principle.

But can everything programmed on Eafp.

 

If you dont know if something is a list, a tuple or a string, you can get a lot 
of nested try except think.

 

Roelof


 


Subject: Re: [Tutor] recursive problem
From: rabidpoob...@gmail.com
Date: Thu, 9 Sep 2010 15:32:44 -0500
To: rwob...@hotmail.com


No you misunderstood me. Eafp is a python design principle. lbyl is common in 
older languages. Please reply all in the future so our discussion takes place 
on the list instead of just between us.

Sent from my iPhone

On Sep 9, 2010, at 1:31 PM, Roelof Wobben rwob...@hotmail.com wrote:




Oke, 
 
So If I understand you right LBYL is more the python way.
Wierd that the book im following (Thinking like a computer scientist) is more 
EAFP.
 
Roelof

 


Subject: Re: [Tutor] recursive problem
From: rabidpoob...@gmail.com
Date: Thu, 9 Sep 2010 13:24:06 -0500
To: rwob...@hotmail.com


It's easier to ask for forgiveness than permission vs. Look before you leap. An 
example of LBYL would be checking the type of a variable before you use it. 
EAFP would be just using the variable, and if something goes wrong, handle the 
exception. It's a core tenet of python software design and goes hand in hand w/ 
duck typing and other principles.

Sent from my iPhone

On Sep 9, 2010, at 1:16 PM, Roelof Wobben rwob...@hotmail.com wrote:





 Sorry. 
 
Im also new to Python and programming.
 
What does EAFP and LBYL mean ?
 
Roelof
 


From: rabidpoob...@gmail.com
Date: Thu, 9 Sep 2010 12:59:46 -0500
To: joel.goldst...@gmail.com
CC: tutor@python.org
Subject: Re: [Tutor] recursive problem


Nope Joel, that's what I meant. Remember EAFP over LBYL! I'm not sure the best 
way to make sure the object is iterable though.

Sent from my iPhone

On Sep 9, 2010, at 11:41 AM, Joel Goldstick joel.goldst...@gmail.com wrote:







On Thu, Sep 9, 2010 at 12:07 PM, Steven D'Aprano st...@pearwood.info wrote:




On Fri, 10 Sep 2010 01:05:22 am Joel Goldstick wrote:
 On Thu, Sep 9, 2010 at 10:26 AM, Luke Paireepinart

 rabidpoob...@gmail.comwrote:
  Shouldn't there be a way to do this without type checking? Duck
  typing!
 
  Your post got me thinking.  Maybe better to test if the object can
  return
 an iter method.  If it throws an error, then look at its value.  If
 it doesn't, then its a list or a tuple


It's not clear what you mean by return an iter method. Taken
literally, that would imply the object is a function. I think you
mean *has* an iter method -- except that's not right either:

 [].iter
Traceback (most recent call last):
 File stdin, line 1, in module
AttributeError: 'list' object has no attribute 'iter'


Perhaps you mean an object which can be passed to iter(), but lots of
objects can do that, not just lists and tuples:

 iter(not a list or tuple)
str_iterator object at 0xb7d3520c
 iter({1: None, 2: a, 4: 5})
dict_keyiterator object at 0xb7d3420c


I was googling, and found that if an object has an __iter__ method it will 
return it.  If not it will throw an error.  You are right about more than lists 
and tuples being iterable.  But, in this thread, it was brought up that 
checking type may not be pythonic.  If you wanted to use the same code to find 
values in a nested list of any objects, you could dispense with the type 
checking and just see if it is iterable.


I'm new to python.  Am I off base? 



--
Steven D'Aprano



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


-- 
Joel Goldstick



___
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   
 ___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] exceptions problem

2010-09-10 Thread Roelof Wobben

Hello, 

 

I have this problem :

 

Write a function named readposint that prompts the user for a positive integer 
and then checks the input to confirm that it meets the requirements. A sample 
session might look like this:

 num = readposint()
Please enter a positive integer: yes
yes is not a positive integer.  Try again.
Please enter a positive integer: 3.14
3.14 is not a positive integer.  Try again.
Please enter a positive integer: -6
-6 is not a positive integer.  Try again.
Please enter a positive integer: 42
 num
42
 num2 = readposint(Now enter another one: )
Now enter another one: 31
 num2
31

Now I thought this would work:def readposint(): 
x = raw_input(Please enter a positive integer :)
try:
x = int(x) and x  0 
except:
print x , is not a positive integer.  Try again.
return False
return Truey = readposint()
print y
while y == False:
readposint()
print You have entered : , yBut the x  10 is never checked.Must I use two 
try except now ? Roelof  ___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] exceptions problem

2010-09-10 Thread Roelof Wobben


 
Date: Fri, 10 Sep 2010 18:07:13 +0200
From: f...@libero.it
To: tutor@python.org
Subject: Re: [Tutor] exceptions problem

Oops, I sent this to Roelof... Ok, I must amend it anyway...
 
On 10/09/2010 17.13, Roelof Wobben wrote:
 ...
 def readposint():
 x = raw_input(Please enter a positive integer :)
 try:
 x = int(x) and x  0
 except:
 print x , is not a positive integer.Try again.
 return False
 return True

 y = readposint()
 print y
 while y == False:
 readposint()
 print You have entered : , y

 But the x  10 is never checked.

 Must I use two try except now ?
Your first problem has nothing to do with exception handling.
The culprit is Line 4:
 x = int(x) and x  0
I suppose that you forgot a second equal sign between x and int(x). If 
it were
x == int(x) and x  0
it would have worked as expected. But this would not trigger any 
exception, if X is a number. So let's add one:
 if not (x == int(x) and x  0): raise(ValueError)
 
Hope that helps,
 
 Roelof
FrancescoHello Francesco,I change it to this :def readposint(): 
x = raw_input(Please enter a positive integer :)
try:
   if not (x == int(x) and x  0): raise(ValueError) 
except:
print x , is not a positive integer.  Try again.
return False
return Truey = readposint()
print y
while y == False:
readposint()
print You have entered : , yBut -9 and 2 are both true.Roelof
 
___ 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] exceptions problem

2010-09-10 Thread Roelof Wobben


 


From: rwob...@hotmail.com
To: tutor@python.org
Date: Fri, 10 Sep 2010 16:12:08 +
Subject: Re: [Tutor] exceptions problem





 
Date: Fri, 10 Sep 2010 18:07:13 +0200
From: f...@libero.it
To: tutor@python.org
Subject: Re: [Tutor] exceptions problem

Oops, I sent this to Roelof... Ok, I must amend it anyway...
 
On 10/09/2010 17.13, Roelof Wobben wrote:
 ...
 def readposint():
 x = raw_input(Please enter a positive integer :)
 try:
 x = int(x) and x  0
 except:
 print x , is not a positive integer.Try again.
 return False
 return True

 y = readposint()
 print y
 while y == False:
 readposint()
 print You have entered : , y

 But the x  10 is never checked.

 Must I use two try except now ?
Your first problem has nothing to do with exception handling.
The culprit is Line 4:
 x = int(x) and x  0
I suppose that you forgot a second equal sign between x and int(x). If 
it were
x == int(x) and x  0
it would have worked as expected. But this would not trigger any 
exception, if X is a number. So let's add one:
 if not (x == int(x) and x  0): raise(ValueError)
 
Hope that helps,
 
 Roelof
FrancescoHello Francesco,I change it to this :def readposint(): 
x = raw_input(Please enter a positive integer :)
try:
   if not (x == int(x) and x  0): raise(ValueError) 
except:
print x , is not a positive integer.  Try again.
return False
return Truey = readposint()
print y
while y == False:
readposint()
print You have entered : , yBut -9 and 2 are both true.RoelofBecause I want 
to understand why this happens I wrote this test programm :def readposint(): 
x = raw_input(Please enter a positive integer :)
print x 
if x == int(x) :
print 01-True
else:
print 01-False
print int(x)
if x  0 :
print 02-True
else:
print 02-False
return y = readposint()
print y
while y == False:
readposint()
print You have entered : , y But I see wierd output :When x = 3 I get this 
output :Please enter a positive integer :3301-False302-TrueNoneYou have entered 
: None
 

That's wierd. 3 is a integer so 01 must be True and 3 is bigger then 0 so that 
one must be false.

 

Can someone explain me why this happens ?

 

Roelof

 


 
___ 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   
 ___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] exceptions problem

2010-09-10 Thread Roelof Wobben


 
Date: Fri, 10 Sep 2010 20:23:09 +0200
From: f...@libero.it
To: tutor@python.org
Subject: Re: [Tutor] exceptions problem

On 10/09/2010 18.12, Roelof Wobben wrote:
 ...
 def readposint():
 x = raw_input(Please enter a positive integer :)
 try:
   if not (x == int(x) and x  0): raise(ValueError)
 except:
 print x , is not a positive integer.Try again.
 return False
 return True

 y = readposint()
 print y
 while y == False:
 readposint()
 print You have entered : , y

 But -9 and 2 are both true.
My fault, I didn't notice that after raw_input, whatever you enter is a 
STRING, not an integer! So, without any exception thrown, the comparison
x == int(x) is always False. Let's make it better:
if (int(x)0 or (float(x) - int(x)  0)): raise(ValueError)
 
 
Then, if the input value x is indeed a positive integer, you should 
return x, not True or False. Try returning -1 if the exception is 
thrown, in line 7, and returning x in line 8. Then, you should change 
also line 12... ok, here's to you:
 
def readposint():
 x = raw_input(Please enter a positive integer :)
 try:
 if (int(x)0 or (float(x) - int(x)  0)): raise(ValueError)
 except:
 print x , is not a positive integer.Try again.
 return -1
 return x
 
y = readposint()
print y
while y == -1:
 readposint()
print You have entered : , y
 

 Roelof
FrancescoThank you.I never thought that you can use a float and a integer to 
look if the number is a integer.Roelof
 
___ 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


[Tutor] recursive problem

2010-09-09 Thread Roelof Wobben

Hello, 

 

I have this :

 

def recursive_count(target, nested_num_list):

   recursive_count(2, [2, 9, [2, 1, 13, 2], 8, [2, 6]])
  4
   recursive_count(7, [[9, [7, 1, 13, 2], 8], [7, 6]])
  2
   recursive_count(15, [[9, [7, 1, 13, 2], 8], [2, 6]])
  0
   recursive_count(5, [[5, [5, [1, 5], 5], 5], [5, 6]])
  6

for element in nested_num_list:
if type(element) == type([]):
   test = recursive_count(target, element)
print element, target
if element == target :
   count = count + 1
return count

 

if __name__ == __main__:
import doctest
doctest.testmod()

 

 

Now I get this message :

 

UnboundLocalError: local variable 'count' referenced before assignment

 

But if I do this :

 

def recursive_count(target, nested_num_list):

   recursive_count(2, [2, 9, [2, 1, 13, 2], 8, [2, 6]])
  4
   recursive_count(7, [[9, [7, 1, 13, 2], 8], [7, 6]])
  2
   recursive_count(15, [[9, [7, 1, 13, 2], 8], [2, 6]])
  0
   recursive_count(5, [[5, [5, [1, 5], 5], 5], [5, 6]])
  6

  count = 0 

  for element in nested_num_list:
if type(element) == type([]):
   test = recursive_count(target, element)
print element, target
if element == target :
   count = count + 1
return count

 

if __name__ == __main__:
import doctest
doctest.testmod()

 

The count will always be 0 if a nested list is being found.

 

What's the python way to solve this 

 

Roelof

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


Re: [Tutor] recursive problem

2010-09-09 Thread Roelof Wobben


 


From: anand.shash...@gmail.com
Date: Thu, 9 Sep 2010 15:08:10 +0530
Subject: Re: [Tutor] recursive problem
To: rwob...@hotmail.com
CC: tutor@python.org




On Thu, Sep 9, 2010 at 2:21 PM, Roelof Wobben rwob...@hotmail.com wrote:


Hello, 
 
I have this :
 
def recursive_count(target, nested_num_list):

   recursive_count(2, [2, 9, [2, 1, 13, 2], 8, [2, 6]])
  4
   recursive_count(7, [[9, [7, 1, 13, 2], 8], [7, 6]])
  2
   recursive_count(15, [[9, [7, 1, 13, 2], 8], [2, 6]])
  0
   recursive_count(5, [[5, [5, [1, 5], 5], 5], [5, 6]])
  6

for element in nested_num_list:
if type(element) == type([]):
   test = recursive_count(target, element)
print element, target
if element == target :
   count = count + 1
return count
 
if __name__ == __main__:
import doctest
doctest.testmod()
 
 
Now I get this message :
 
UnboundLocalError: local variable 'count' referenced before assignment


It is because you are doing count = count + 1
But where is count defined.
 


 
But if I do this :
 
def recursive_count(target, nested_num_list):

   recursive_count(2, [2, 9, [2, 1, 13, 2], 8, [2, 6]])
  4
   recursive_count(7, [[9, [7, 1, 13, 2], 8], [7, 6]])
  2
   recursive_count(15, [[9, [7, 1, 13, 2], 8], [2, 6]])
  0
   recursive_count(5, [[5, [5, [1, 5], 5], 5], [5, 6]])
  6

  count = 0 
  for element in nested_num_list:
if type(element) == type([]):
   test = recursive_count(target, element)
print element, target
if element == target :
   count = count + 1
return count
 
if __name__ == __main__:
import doctest
doctest.testmod()
 
The count will always be 0 if a nested list is being found.
 
What's the python way to solve this 


I am not sure what do you want to achieve by this ?
What is the problem statement ?
 
The problem statement is that I must count how many times the target is in the 
nested_list.
So I thougt that every nested list the function is called again so this list is 
also iterated.
 
Roelof
  ___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] sort problem

2010-09-08 Thread Roelof Wobben

Hello, 

 

I have this :

 

def sort_sequence(seq):

   sort_sequence([3, 4, 6, 7, 8, 2])
  [2, 3, 4, 6, 7, 8]
   sort_sequence((3, 4, 6, 7, 8, 2))
  (2, 3, 4, 6, 7, 8)
   sort_sequence(nothappy)
  'ahnoppty'

   if type(seq) == type([]):
seq.sort()
elif type(seq)== type(()):
seq = tuple(sorted(seq))
else:
seq2 = list(seq)
seq2.sort()
print seq2
seq.join(seq2)
return seq

 

The problem is that if I want to sort the characters in a string, the list 
exist of the sorted characters but as soon as I convert them to a string I get 
the old string.

 

What went wrong ?

 

Roelof

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


Re: [Tutor] sort problem

2010-09-08 Thread Roelof Wobben


 

 Subject: Re: [Tutor] sort problem
 From: evert@gmail.com
 Date: Wed, 8 Sep 2010 17:26:58 +0200
 CC: tutor@python.org
 To: rwob...@hotmail.com
 
  I have this :
  
  def sort_sequence(seq):
  
   sort_sequence([3, 4, 6, 7, 8, 2])
  [2, 3, 4, 6, 7, 8]
   sort_sequence((3, 4, 6, 7, 8, 2))
  (2, 3, 4, 6, 7, 8)
   sort_sequence(nothappy)
  'ahnoppty'
  
  if type(seq) == type([]):
  seq.sort()
  elif type(seq)== type(()):
  seq = tuple(sorted(seq))
  else:
  seq2 = list(seq)
  seq2.sort()
  print seq2
  seq.join(seq2)
  return seq
  
  The problem is that if I want to sort the characters in a string, the list 
  exist of the sorted characters but as soon as I convert them to a string I 
  get the old string.
 
 Carefully read the documentation for str.join: 
 http://docs.python.org/library/stdtypes.html#str.join
 
 How does it work, what does it return, etc. Then fix the corresponding line 
 in your code.
 As a hint: str.join does work quite different than list.sort; I assume you're 
 confusing their syntaxes.
 
 Good luck,
 
 Evert
 


str.join(iterable)¶
 

How it works.

It puts all the elements of iterable into one string named str.

 

So it returns a string. 

 

Str is here seq  and the iterable is the list made by list.sort so seq2

 

So I don't see the error in that line.

 

 

Roelof

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


Re: [Tutor] sort problem

2010-09-08 Thread Roelof Wobben


 


Date: Wed, 8 Sep 2010 12:38:03 -0400
From: gregb...@gmail.com
To: tutor@python.org
Subject: Re: [Tutor] sort problem




On Wed, Sep 8, 2010 at 11:50 AM, Roelof Wobben rwob...@hotmail.com wrote:



 
 Subject: Re: [Tutor] sort problem
 From: evert@gmail.com
 Date: Wed, 8 Sep 2010 17:26:58 +0200
 CC: tutor@python.org
 To: rwob...@hotmail.com

 
  I have this :
  
  def sort_sequence(seq):
  
   sort_sequence([3, 4, 6, 7, 8, 2])
  [2, 3, 4, 6, 7, 8]
   sort_sequence((3, 4, 6, 7, 8, 2))
  (2, 3, 4, 6, 7, 8)
   sort_sequence(nothappy)
  'ahnoppty'
  
  if type(seq) == type([]):
  seq.sort()
  elif type(seq)== type(()):
  seq = tuple(sorted(seq))
  else:
  seq2 = list(seq)
  seq2.sort()
  print seq2
  seq.join(seq2)
  return seq
  
  The problem is that if I want to sort the characters in a string, the list 
  exist of the sorted characters but as soon as I convert them to a string I 
  get the old string.
 
 Carefully read the documentation for str.join: 
 http://docs.python.org/library/stdtypes.html#str.join
 
 How does it work, what does it return, etc. Then fix the corresponding line 
 in your code.
 As a hint: str.join does work quite different than list.sort; I assume you're 
 confusing their syntaxes.
 
 Good luck,
 
 Evert
 


str.join(iterable)¶ 
How it works.
It puts all the elements of iterable into one string named str.
 
So it returns a string. 
 
Str is here seq  and the iterable is the list made by list.sort so seq2
 
So I don't see the error in that line.
 
 
Roelof
 


The error is that you misunderstand the usage of str.join.  It doesn't do it in 
place, i.e. it doesn't change the actual string, so you have to have a variable 
to capture the response.


The biggest thing, though, is that in str.join, str is not the string to store 
the joined iterator in, it's the separator for the string.  so, in your case, 
where you have


seq.join(seq2)


You really want


seq = .join(seq2)


where  is the separator to join seq2 on (an empty string in this case)

HTH.

-- 
Greg Bair
gregb...@gmail.com
 
Oke, 
 
If I understand it right with join I can put two strings into 1 string.
 
Roelof
 

___ 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] sort problem

2010-09-08 Thread Roelof Wobben


 
Date: Wed, 8 Sep 2010 20:10:28 +0200
From: f...@libero.it
To: tutor@python.org
Subject: Re: [Tutor] sort problem

On 08/09/2010 19.12, Francesco Loffredo wrote:
 ...
 a little example:

 separator = Roelof
 list = [Wobben, Python, Learner]
 print separator.join(list)

 ... what you will get? Guess before you try.
 
There's more, I forgot to add:
 
print separator
 
This is important, this method *returns* a *NEW* string, it does not 
modify the providing string (here separator)! This means you must save 
the result somewhere, if you want to use it later:
 
together = separator.join(list)
 
Francesco


___ Tutor maillist - 
Tutor@python.org To unsubscribe or change subscription options: 

http://mail.python.org/mailman/listinfo/tutor

 

Oke, 

 

I now see what everyone try to teach me.

 

Roelof

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


Re: [Tutor] exercise correct ??

2010-09-07 Thread Roelof Wobben

Hello, 

 

Oke, the 4 is a starting point for the index.

 

Next problem.

 

The begin looks like this :

 

 index_of(5, (1, 2, 4, 5, 6, 10, 5, 5), 4)


But in the module I get this result :

 

val = 5

seq = (1, 2, 4, 5, 6, 10, 5, 5

 

So the 4 is not avaible anymore.

 

Now I can change the header to  index(val, seq, start=0) to index (val, seq, 
start)

But I think that's not what the exercise wants.

 

Is there another way I can use the 4 ?

 

Roelof

 


 
 To: tutor@python.org
 From: alan.ga...@btinternet.com
 Date: Mon, 6 Sep 2010 23:28:22 +0100
 Subject: Re: [Tutor] exercise correct ??
 
 
 Roelof Wobben rwob...@hotmail.com wrote
 
 #
 def index_of(val, seq, start=0):
 
  index_of(5, (1, 2, 4, 5, 6, 10, 5, 5), 4)
 6
 
 
 But I get this message :
 Failed example:
 index_of(5, (1, 2, 4, 5, 6, 10, 5, 5), 4)
 Expected:
 6
 Got:
 3
 #
 
  But in that tuple 5 is on position 3.
  Is the exercise here wrong ?
 
 No because the start position is 4 so you don;t see the 5 in position 
 3.
 
 HTH,
 
 -- 
 Alan Gauld
 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 maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] exercise correct ??

2010-09-07 Thread Roelof Wobben


 


Date: Tue, 7 Sep 2010 00:52:38 -0700
From: alan.ga...@btinternet.com
Subject: Re: [Tutor] exercise correct ??
To: rwob...@hotmail.com; tutor@python.org









Oke, the 4 is a starting point for the index.
 
Next problem.
 
The begin looks like this :
 
 index_of(5, (1, 2, 4, 5, 6, 10, 5, 5), 4)

But in the module I get this result :
 
val = 5
seq = (1, 2, 4, 5, 6, 10, 5, 5
 
So the 4 is not avaible anymore.


Yes it is. It is the start parameter.

The function definition is

def index_of(val, seq, start=0):

val is the first value, 5, seq is the tuple and start is 4.
 



Now I can change the header to  index(val, seq, start=0) to index (val, seq, 
start)
But I think that's not what the exercise wants.


Why would you want to do that? It would force you to provide a start value 
for every call. The point of having a default value (=0) is so that you do not 
need to specify start every time you use the function. But eveb if you do not
use the start value it will still have a value, 0.
There is no difference, you can access it exactly like the other parameters.
Just use its name.
 
HTH,

Alan G.
 
Oke, 
 
Then this is the solution :
 
def index_of(val, seq, start=0):

   index_of(9, [1, 7, 11, 9, 10])
  3
   index_of(5, (1, 2, 4, 5, 6, 10, 5, 5))
  3
   index_of(5, (1, 2, 4, 5, 6, 10, 5, 5), 4)
  6
   index_of('y', 'happy birthday')
  4
   index_of('banana', ['apple', 'banana', 'cherry', 'date'])
  1
   index_of(5, [2, 3, 4])
  -1
   index_of('b', ['apple', 'banana', 'cherry', 'date'])
  -1

try:
plek = seq.index(val, start)
except:
plek = -1
return plek 
 
Roelof


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


[Tutor] why do i get None as output

2010-09-06 Thread Roelof Wobben

Hello, 

 

I have this programm:

 

def encapsulate(val, seq):
if type(seq) == type():
return str(val)
if type(seq) == type([]):
return [val]
return (val,)

 

def insert_in_middle(val, seq):
middle = len(seq)/2
return seq[:middle] + encapsulate(val, seq) + seq[middle:]

 

def make_empty(seq):

   make_empty([1, 2, 3, 4])
  []
   make_empty(('a', 'b', 'c'))
  ()
   make_empty(No, not me!)
  ''

word2=
teller=0
if type(seq) == type([]):
teller=0 
while teller  len(seq):
seq[teller]=
teller = teller + 1 
elif type(seq) == type(()):
tup2 = list (seq)
while teller  tup2.len():
tup2[teller]=
teller = teller + 1
seq = tuple(tup2)
else:
seq = 
   
test = make_empty([1, 2, 3, 4])
print test

 

But now I get None as output instead of []

 

Can anyone explain why that happens ?

 

Roelof


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


Re: [Tutor] why do i get None as output

2010-09-06 Thread Roelof Wobben


 

 To: tutor@python.org
 From: alan.ga...@btinternet.com
 Date: Mon, 6 Sep 2010 08:27:31 +0100
 Subject: Re: [Tutor] why do i get None as output
 
 
 Roelof Wobben rwob...@hotmail.com wrote 
 
 def make_empty(seq):
 word2=
 teller=0
 if type(seq) == type([]):
 teller=0 
 while teller  len(seq):
 seq[teller]=
 teller = teller + 1 
 elif type(seq) == type(()):
 tup2 = list (seq)
 while teller  tup2.len():
 tup2[teller]=
 teller = teller + 1
 seq = tuple(tup2)
 else:
 seq = 
 
 test = make_empty([1, 2, 3, 4])
 
 But now I get None as output instead of []
 
 
 Because None is the default return value from a function.
 If you do not return a value (which you don;t in this case) then 
 Python automatically returns None.
 
 You need to return something from your make_empty function.
 
 Also, if all you want to do is return an empty version of 
 whatever has been passed in there are much easier 
 ways of doing it! And in fact, a list of empty strings is 
 not the same as an empty list...
 
 
 HTH
 
 -- 
 Alan Gauld
 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

 

Oke, 

 

I put a return seq in the programm and it looks now like this :

 

def encapsulate(val, seq):
if type(seq) == type():
return str(val)
if type(seq) == type([]):
return [val]
return (val,)

 

def insert_in_middle(val, seq):
middle = len(seq)/2
return seq[:middle] + encapsulate(val, seq) + seq[middle:]

 

def make_empty(seq):

   make_empty([1, 2, 3, 4])
  []
   make_empty(('a', 'b', 'c'))
  ()
   make_empty(No, not me!)
  ''

if type(seq) == type([]):
seq = []
elif type(seq) == type(()):
seq=()
else:
seq = 
return seq

 

if __name__ == __main__:
import doctest
doctest.testmod()

 

This works but I don't think its what the exercise means :

 



Create a module named seqtools.py. Add the functions encapsulate and 
insert_in_middle from the chapter. Add doctests which test that these two 
functions work as intended with all three sequence types.

Add each of the following functions to seqtools.py:

def make_empty(seq):

   make_empty([1, 2, 3, 4])
  []
   make_empty(('a', 'b', 'c'))
  ()
   make_empty(No, not me!)
  ''


So i think I have to use encapsulate and insert_in_middle. And I don't use it.

 

Roelof


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


[Tutor] exercise correct ??

2010-09-06 Thread Roelof Wobben

Hello, 

 

I have this programm :

 

def index_of(val, seq, start=0):

   index_of(9, [1, 7, 11, 9, 10])
  3
   index_of(5, (1, 2, 4, 5, 6, 10, 5, 5))
  3
   index_of(5, (1, 2, 4, 5, 6, 10, 5, 5), 4)
  6
   index_of('y', 'happy birthday')
  4
   index_of('banana', ['apple', 'banana', 'cherry', 'date'])
  1
   index_of(5, [2, 3, 4])
  -1
   index_of('b', ['apple', 'banana', 'cherry', 'date'])
  -1

plek = 0 
if type(seq) == type([]):
plek = seq.index(val)
elif type(seq) == type(()):
seq = list (seq)
plek = seq.index(val)
else :
plek = seq.find(val)
return plek 


 

But I get this message :

 

File C:\Users\wobben\workspace\oefeningen\src\test.py, line 70, in 
__main__.index_of
Failed example:
index_of(5, (1, 2, 4, 5, 6, 10, 5, 5), 4)
Expected:
6
Got:
3

 

But in that tuple 5 is on position 3.

 

Is the exercise here wrong ?

 

Roelof

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


Re: [Tutor] exercise correct ??

2010-09-06 Thread Roelof Wobben


 

 Date: Mon, 6 Sep 2010 21:45:17 +0200
 Subject: Re: [Tutor] exercise correct ??
 From: sander.swe...@gmail.com
 To: rwob...@hotmail.com
 CC: tutor@python.org
 
 On 6 September 2010 19:32, Roelof Wobben rwob...@hotmail.com wrote:
  def index_of(val, seq, start=0):
  
 index_of(9, [1, 7, 11, 9, 10])
3
 index_of(5, (1, 2, 4, 5, 6, 10, 5, 5))
3
 index_of(5, (1, 2, 4, 5, 6, 10, 5, 5), 4)
6
 index_of('y', 'happy birthday')
4
 index_of('banana', ['apple', 'banana', 'cherry', 'date'])
1
 index_of(5, [2, 3, 4])
-1
 index_of('b', ['apple', 'banana', 'cherry', 'date'])
-1
  
  plek = 0
  if type(seq) == type([]):
  plek = seq.index(val)
  elif type(seq) == type(()):
  seq = list (seq)
  plek = seq.index(val)
  else :
  plek = seq.find(val)
  return plek
 
 Not sure if this is correct but why don't you check for the index
 attribute? It is part of both lists and strings. Also you can use
 try/except to catch a ValueError. My version below, but I dislike the
 list() usage...
 
 def index_of(val, seq, start=0):
 if hasattr(seq, 'index'):
 try:
 return seq.index(val, start)
 except ValueError:
 return -1
 else:
 try:
 return list(seq).index(val, start)
 except ValueError:
 return -1
 
  File C:\Users\wobben\workspace\oefeningen\src\test.py, line 70, in
  __main__.index_of
 
  Failed example:
 
  index_of(5, (1, 2, 4, 5, 6, 10, 5, 5), 4)
 
  Expected:
 
  6
 
  Got:
 
  3
 
  But in that tuple 5 is on position 3.
 
  Is the exercise here wrong ?
 
 Looks like it, or it's a typo.
 
 Greets
 Sander


Hello Sander, 

 

I agree that index is a part of string and list.

But not a part of a tuple.

As far as I know index is not a part of tuple so I have to convert it to a list 
so I can use index.

 

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


[Tutor] (no subject)

2010-09-05 Thread Roelof Wobben

Hello, 

 

I have made this program as solution to a exercise from thinking like a 
computer scientist.

 

def encapsulate(val, seq):
if type(seq) == type():
return str(val)
if type(seq) == type([]):
return [val]
return (val,)
 

def insert_in_middle(val, seq):
middle = len(seq)/2
return seq[:middle] + encapsulate(val, seq) + seq[middle:]

 
def make_empty(seq):

 make_empty([1, 2, 3, 4])
[]
 make_empty(('a', 'b', 'c'))
()
 make_empty(No, not me!)
''

if type(element) == type([]):
for word2 in seq :
word2 = 
elif type(element) == type(()):
tup2 = list (seq)
while teller  tup2.len():
tup2[teller]=
teller = teller + 1
seq = tuple(tup2)
else:
seq = 

test = make_empty([1, 2, 3, 4])
print test

 

But now Im getting this error message :

 

Traceback (most recent call last):
File C:\Users\wobben\workspace\oefeningen\src\test.py, line 33, in module
test = make_empty([1, 2, 3, 4])
File C:\Users\wobben\workspace\oefeningen\src\test.py, line 21, in make_empty
if type(element) == type([]):
NameError: global name 'element' is not defined

 

What went wrong here ?

 

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


Re: [Tutor] (no subject)

2010-09-05 Thread Roelof Wobben


 

 From: st...@pearwood.info
 To: tutor@python.org
 Date: Sun, 5 Sep 2010 23:55:32 +1000
 Subject: Re: [Tutor] (no subject)
 
 On Sun, 5 Sep 2010 11:44:09 pm Roelof Wobben wrote:
  Hello,
 
  I have made this program as solution to a exercise from thinking like
  a computer scientist.
 [...]
  But now Im getting this error message :
 
  Traceback (most recent call last):
  File C:\Users\wobben\workspace\oefeningen\src\test.py, line 33, in
  module test = make_empty([1, 2, 3, 4])
  File C:\Users\wobben\workspace\oefeningen\src\test.py, line 21, in
  make_empty if type(element) == type([]):
  NameError: global name 'element' is not defined
 
 
 
  What went wrong here ?
 
 Read the error message again:
 
 NameError: global name 'element' is not defined
 
 You are trying to use something called element, but you haven't 
 created anything with that name. The error message even tells you were 
 the problem is: line 21, in the function make_empty.
 
 
 
 -- 
 Steven D'Aprano
 ___
 Tutor maillist - Tutor@python.org
 To unsubscribe or change subscription options:
 http://mail.python.org/mailman/listinfo/tutor


Hello Steven.

 

I understand the error message.

I follow this example in the book : 
http://openbookproject.net/thinkcs/python/english2e/ch11.html

And there element is not defined.

 

Roelof

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


[Tutor] can this be done easerly

2010-08-30 Thread Roelof Wobben

Hello,

 

For a exerise I made this one :

 

import string

def extract_words(s):

   extract_words('Now is the time!  Now, is the time? Yes, now.')
  ['now', 'is', 'the', 'time', 'now', 'is', 'the', 'time', 'yes', 'now']
   extract_words('she tried to curtsey as she spoke--fancy')
  ['she', 'tried', 'to', 'curtsey', 'as', 'she', 'spoke', 'fancy']

word= 
s=string.lower(s)
for char in s :
if ord(char) =65 and ord(char) = 122 or ord(char)==32 or 
ord(char)==45:
  word= word + char 
word=string.split(word, --)
word=string.join(word,  )
word=word.replace (  ,  )
word=string.split(word,  )
return word

if __name__ == '__main__':
import doctest
doctest.testmod()

 

But now I wonder if this can be done more easerly ?

 

Roelof

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


  1   2   >