[Tutor] removing file from zip archive.
Hi all, How can we remove one file inside of a zip archive? I'm using this method: import zipfile ziparchive = zipfile.ZipFile('test.odt', 'r') xmldata = ziparchive.read('content.xml') ziparchive.close Thanks in advance, Sophon ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] ASCII
Hi Kaushal,Please clarify the problem more specific.Or you can tell us that you have a problem and want to use python to solve it?Sincerely Yours,pujoOn 3/29/06, Kaushal Shriyan <[EMAIL PROTECTED]> wrote: Hi AllHow do i use this ASCII values in my day to day activities, I am going throughlearning python,Please illustrate with examplesThanks in AdvanceRegardsKaushal___ Tutor maillist - Tutor@python.orghttp://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] get a character of an ascii-value
On Wednesday 29 March 2006 13:54, Keo Sophon wrote: > Hi all, > > I wonder how to get a character of an Ascii-value. For example, i have r = > 37. So i wanna print the character of 37. Is there any function? > > Thanks, > Sophon I just got the answer from Pujo. How about r is bigger than 127. How can i get the character? For example, r = 191. Thanks, Sophon ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] ASCII
Hi All How do i use this ASCII values in my day to day activities, I am going through learning python, Please illustrate with examples Thanks in Advance Regards Kaushal ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] get a character of an ascii-value
Keo Sophon wrote: > Hi all, > > I wonder how to get a character of an Ascii-value. For example, i have r = > 37. So i wanna print the character of 37. Is there any function? > Hi ..yeah, it's called chr(), and its opposite is ord() >>> ord('r') 114 >>> chr(114) 'r' >>> Hugo ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] get a character of an ascii-value
Hello use this function: print ord('a') print chr(97)Cheers,pujoOn 3/29/06, Keo Sophon < [EMAIL PROTECTED]> wrote:Hi all,I wonder how to get a character of an Ascii-value. For example, i have r = 37. So i wanna print the character of 37. Is there any function?Thanks,Sophon___Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] get a character of an ascii-value
Hi all, I wonder how to get a character of an Ascii-value. For example, i have r = 37. So i wanna print the character of 37. Is there any function? Thanks, Sophon ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Alternating patterns
Hi,you can also use simple way of iterating using modus: L = [1,2] for i in range(6): print L[i%len(L)]121212Cheers,pujo On 3/29/06, kevin parks <[EMAIL PROTECTED]> wrote: -->> Message: 10> Date: Tue, 28 Mar 2006 22:43:38 -0500> From: Kent Johnson <[EMAIL PROTECTED]> > Subject: Re: [Tutor] Alternating patterns> Cc: tutor@python.org> Message-ID: <[EMAIL PROTECTED]>> Content-Type: text/plain; charset=ISO-8859-1; format=flowed >> kevin parks wrote:>> I have a set that i iterate over... but each time through it i would>> like to alternate between the original set and a variation of the set>> that has one of the members of the set altered (by + or - 1) So if my original set is: [0, 2, 4, 5, 7, 9, 11] I would use that the first pass but on the second pass i might like>> the third member (4,) to become 3, (-1) resulting in : [0, 2, 3, 5, 7, >> 9, 11] But then back again to the original on the next pass (+1 back to 4,):>> [0, 2, 4, 5, 7, 9, 11] and then back: [0, 2, 3, 5, 7, 9, 11] again, etc. >>> How can one make such alternating patterns?>> itertools.cycle() will repeat a sequence indefinitely:> In [2]: from itertools import cycle>> In [3]: i=cycle([1,2]) >> In [5]: for j in range(6):> ...: print i.next()> ...:> ...:> 1> 2> 1> 2> 1> 2>> For non-repeating sequences I would look at writing a generator > function> for the sequences.>> Kentokay.. i am painfully unaware of generators, iterators, sets, genexesand a lot of the new stuff post 2.3 & 2.4 stuffs... my problem is that i find the online docs kind of terse and few of the Python books yetcover these newer constructs in detailitertools looks very cool are there any toots on the above and onSets & itertools? It really seems like it would help to know these for my work... That liddo bit right up there with itertools.cycle alreadyhas me a drooling... (so helpful that would be!)-kp--___Tutor maillist - Tutor@python.orghttp://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Program for outputing the letter backward
On 29/03/06, Hoffmann <[EMAIL PROTECTED]> wrote: > Hi John, > > (1) vehicle[index] is: 'c' > (2) If index = index = 1, so vehicle[index] becomes: > 'a' What I'm getting at here is that, by changing index, we can change which letter we are looking at. And index is a number, which means it's easier to reason about than letters are. Let's have a look at a possible solution: >>> vehicle = 'car' >>> index = 2 >>> print vehicle[index] r >>> index = 1 >>> print vehicle[index] a >>> index = 0 >>> print vehicle[index] c Notice that the three print statements are identical. That suggests we could write the code in a loop, with 'print vehicle[index]' in the body of the loop. Can you have a go at that? -- John. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Program for outputing the letter backward
--- John Fouhy <[EMAIL PROTECTED]> wrote: > On 29/03/06, Hoffmann <[EMAIL PROTECTED]> wrote: > > >>> vehicle='car' > > >>> index = 0 > > >>> lenght =len(vehicle) > > >>> last = vehicle[lenght -1] > > >>> while last >= vehicle[0]: > > ... letter = vehicle[index] > > ... print letter > > ... last -= 1 > > ... > > What is vehicle[index] ? > > What if I change index, say, > >index = index + 1 > > Now what is vehicle[index] ? > > -- > John. > ___ Hi John, (1) vehicle[index] is: 'c' (2) If index = index = 1, so vehicle[index] becomes: 'a' I changed a bit more the code, but I am still in trouble. please, take a look: (1st. try): >>> vehicle='car' >>> index = vehicle[-1]#'r' >>> lenght =len(vehicle) # 3 leters >>> last = vehicle[lenght -1] # >>> while last >= vehicle[0]: ... letter = vehicle[index] ... print letter ... last -= 1 ... Traceback (most recent call last): File "", line 2, in ? TypeError: string indices must be integers (2nd, try): >>> vehicle='car' >>> index = vehicle[-1] >>> while vehicle[-1] >= vehicle[0]: ... letter = vehicle[index] ... print letter ... index -= 1 ... Traceback (most recent call last): File "", line 2, in ? TypeError: string indices must be integers Such a 'hard' simple problem... Hoffmann __ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Alternating patterns
> > > > -- > > Message: 10 > Date: Tue, 28 Mar 2006 22:43:38 -0500 > From: Kent Johnson <[EMAIL PROTECTED]> > Subject: Re: [Tutor] Alternating patterns > Cc: tutor@python.org > Message-ID: <[EMAIL PROTECTED]> > Content-Type: text/plain; charset=ISO-8859-1; format=flowed > > kevin parks wrote: >> I have a set that i iterate over... but each time through it i would >> like to alternate between the original set and a variation of the set >> that has one of the members of the set altered (by + or - 1) >> >> So if my original set is: >> >> [0, 2, 4, 5, 7, 9, 11] >> >> I would use that the first pass but on the second pass i might like >> the third member (4,) to become 3, (-1) resulting in : [0, 2, 3, 5, 7, >> 9, 11] >> >> But then back again to the original on the next pass (+1 back to 4,): >> [0, 2, 4, 5, 7, 9, 11] >> >> and then back: [0, 2, 3, 5, 7, 9, 11] again, etc. > >> How can one make such alternating patterns? > > itertools.cycle() will repeat a sequence indefinitely: > In [2]: from itertools import cycle > > In [3]: i=cycle([1,2]) > > In [5]: for j in range(6): > ...: print i.next() > ...: > ...: > 1 > 2 > 1 > 2 > 1 > 2 > > For non-repeating sequences I would look at writing a generator > function > for the sequences. > > Kent okay.. i am painfully unaware of generators, iterators, sets, genexes and a lot of the new stuff post 2.3 & 2.4 stuffs... my problem is that i find the online docs kind of terse and few of the Python books yet cover these newer constructs in detail itertools looks very cool are there any toots on the above and on Sets & itertools? It really seems like it would help to know these for my work... That liddo bit right up there with itertools.cycle already has me a drooling... (so helpful that would be!) -kp-- ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Program for outputing the letter backward
On 29/03/06, Hoffmann <[EMAIL PROTECTED]> wrote: > >>> vehicle='car' > >>> index = 0 > >>> lenght =len(vehicle) > >>> last = vehicle[lenght -1] > >>> while last >= vehicle[0]: > ... letter = vehicle[index] > ... print letter > ... last -= 1 > ... What is vehicle[index] ? What if I change index, say, index = index + 1 Now what is vehicle[index] ? -- John. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Program for outputing the letter backward
--- John Fouhy <[EMAIL PROTECTED]> wrote: > On 29/03/06, Hoffmann <[EMAIL PROTECTED]> wrote: > > vehicle='car' > > index = vehicle[-1] #the last letter > > index_zero = vehicle[0] #the first letter > > > > while index >= index_zero: > >letter=vehicle[index] > >print letter > >index -= 1 > > > > The problem is that I get no output here. Could I > hear > > from you? > > I can print the letters backwards like this: > > vehicle = 'car' > print vehicle[2] > print vehicle[1] > print vehicle[0] > > Output: > > r > a > c > > - > > This is not very useful, though, because it will > only work for strings > that are exactly three letters long. Can you see > how to write a loop > to produe this output? > > Hint: the len() function will tell you how long a > string is. > > eg: if vehicle == 'car' then len(vehicle) == 3. > > -- > John. > ___ Hi John, I am still 'blind' here. Please, see below what I did, and what I got: >>> vehicle='car' >>> index = 0 >>> lenght =len(vehicle) >>> last = vehicle[lenght -1] >>> while last >= vehicle[0]: ... letter = vehicle[index] ... print letter ... last -= 1 ... c Traceback (most recent call last): File "", line 4, in ? TypeError: unsupported operand type(s) for -=: 'str' and 'int' As you can see, I am still a newbie... Could anyone, please, guide me on this exercise? Thanks! Hoffmann __ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Bigrams and nested dictionaries
Aha! John wrote: "Are you sure you haven't mistakenly assigned something other than a dict to D or D['d'] ?" Thanks for the tip! Yup that was it (and apologies for not reporting the problem more precisely). I hadn't initialized the nested dictionary before trying to assign to it. (I think Perl doesn't require initialization of dictionaries prior to assignment, which in this case, would be a nice thing...) >>> D['a'] = {'a':1, 'b':2}#oops Traceback (most recent call last): File "", line 1, in ? NameError: name 'D' is not defined >>> D = {} >>> D['a'] = {'a':1, 'b':2} >>> D {'a': {'a': 1, 'b': 2}} >>> D['c']['a'] = 1 #ooops Traceback (most recent call last): File "", line 1, in ? KeyError: 'c' >>> D['c'] = {} >>> D['c']['a'] = 1 >>> D {'a': {'a': 1, 'b': 2}, 'c': {'a': 1}} And Kent wrote: "Encapsulating this in a generator is probably a good plan." Yay, I get to play with generators... thanks for the suggestion, I would never have looked in that direction. -- Python: [x for S in L for x in S] Mathematica: Flatten[L] (but where's the fun in that?) ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Python help
Why not post where you are stuck or what you are trying to understand? and we'll give you help and direction. What we cannot do is solve your homework for you. Hugo Natasha Menon wrote: > hi, > > i need help on a terrible homework assignment. do ul offer hw help? > ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Program for outputing the letter backward
Hoffmann wrote: > --- Kent Johnson <[EMAIL PROTECTED]> wrote: > >>You are confusing the index of a letter - the number >>which represents >>its position in the word - with the letter itself. >>In your code, index >>and index_zero are actually letters, not indices. >>Try to rewrite the >>code so they are numbers. > > Sorry for not showing the traceback the first time. > Please, see it below: > > Traceback (most recent call last): > File "", line 2, in ? > TypeError: string indices must be integers > > Any hint? Already gave the hint in the first part of my reply. The error message repeats it. Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Alternating patterns
kevin parks wrote: > I have a set that i iterate over... but each time through it i would > like to alternate between the original set and a variation of the set > that has one of the members of the set altered (by + or - 1) > > So if my original set is: > > [0, 2, 4, 5, 7, 9, 11] > > I would use that the first pass but on the second pass i might like > the third member (4,) to become 3, (-1) resulting in : [0, 2, 3, 5, 7, > 9, 11] > > But then back again to the original on the next pass (+1 back to 4,): > [0, 2, 4, 5, 7, 9, 11] > > and then back: [0, 2, 3, 5, 7, 9, 11] again, etc. > How can one make such alternating patterns? itertools.cycle() will repeat a sequence indefinitely: In [2]: from itertools import cycle In [3]: i=cycle([1,2]) In [5]: for j in range(6): ...: print i.next() ...: ...: 1 2 1 2 1 2 For non-repeating sequences I would look at writing a generator function for the sequences. Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Bigrams and nested dictionaries
Michael Broe wrote: > I'm playing with the whole idea of creating bigram (digram?) > frequencies for text analysis and cryptographic and entropy analysis > etc (this is as much an exercise in learning Python and programming > as anything else, I realise everything has already been done > somewhere somehow :) Though I *am* aiming to run this over unicoded > phonetic representations of natural languages, which doesn't seem to > be that common. > > I implemented a single character count using a dictionary, and it > worked really well: > > Character_Count = {} > for character in text: > Character_Count[character] = Character_Count.get(character, 0) + 1 > > And so for bigrams I was thinking of creating a data-structure that > was a nested dictionary, where the key was the character in position > 1, and the value was a sub-dictionary that gave a count of each > character in position 2. > > So the dictionary might begin something like: > > {'a': {'a':1, 'b':8, 'c':10,...}, 'b' : {'a':23, 'b':0, 'c': > 1,...},..., 'z' : {'a':11, 'b':0, 'c':0,...}} > > The count of the character in position one could be retrieved by > summing over the characters in position 2, so the bigram and single- > character counts can be done in one pass. > > I don't want anyone to tell me how to do this :) I'd just like to get > a feel for: > > (i) is this idea of a nested dictionary a good/efficient/tractable > data-structure? It can work. An alternative is a dictionary keyed by the two-letter pairs. I don't know which will work better. > > (ii) is there a straightforward path to the goal of constructing this > thing in a single pass over the input string (yes or no will suffice > for the moment!), or is there a can of worms lurking in my future. I think so. > > I'd rather have less information than more, but there is something > about grabbing characters two-at-a-time, but moving forward one-at-a- > time, and sticking the count down a level inside the dictionary > that's just a little baffling at the moment. Encapsulating this in a generator is probably a good plan. If you want help look at the online cookbook. The generator can yield two-character strings or tuples of characters, whichever is more convenient. When you have a generator for the pairs the rest of the program will be pretty straightforward. Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Program for outputing the letter backward
--- Kent Johnson <[EMAIL PROTECTED]> wrote: > Hoffmann wrote: > > Hello: > > > > I am trying to write a code (this is an exercose > from > > a book). The goal is to write a program that takes > a > > string and outputs the letters backward, ine per > > line. > > Ok. I did a test first, by writing a code with > > numbers: > > > > a=0; b=10 > > while a<=b: > >print b > >b -= 1 > > > > Here the output is: > > 10 > > 9 > > 8 > > 7 > > 6 > > 5 > > 4 > > 3 > > 2 > > 1 > > 0 > > That worked fine. > > Now, back to my exercise. I tried to write a code > that > > takes the string 'car' as the input: > > > > vehicle='car' > > index = vehicle[-1] #the last letter > > index_zero = vehicle[0] #the first letter > > > > while index >= index_zero: > >letter=vehicle[index] > >print letter > >index -= 1 > > You are confusing the index of a letter - the number > which represents > its position in the word - with the letter itself. > In your code, index > and index_zero are actually letters, not indices. > Try to rewrite the > code so they are numbers. > > > > The problem is that I get no output here. > > My guess is you got a TypeError on the line >letter=vehicle[index] > > decause index is a letter. It's important to give us > accurate > descriptions of what happens, and to show error > messages and the > tracebacks that come with them. This can be very > helpful when you have a > problem. > > Kent > > ___ Hi Kent, Sorry for not showing the traceback the first time. Please, see it below: Traceback (most recent call last): File "", line 2, in ? TypeError: string indices must be integers Any hint? Thanks, Hoffmann __ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Program for outputing the letter backward
Hoffmann wrote: > Hello: > > I am trying to write a code (this is an exercose from > a book). The goal is to write a program that takes a > string and outputs the letters backward, ine per > line. > Ok. I did a test first, by writing a code with > numbers: > > a=0; b=10 > while a<=b: >print b >b -= 1 > > Here the output is: > 10 > 9 > 8 > 7 > 6 > 5 > 4 > 3 > 2 > 1 > 0 > That worked fine. > Now, back to my exercise. I tried to write a code that > takes the string 'car' as the input: > > vehicle='car' > index = vehicle[-1] #the last letter > index_zero = vehicle[0] #the first letter > > while index >= index_zero: >letter=vehicle[index] >print letter >index -= 1 You are confusing the index of a letter - the number which represents its position in the word - with the letter itself. In your code, index and index_zero are actually letters, not indices. Try to rewrite the code so they are numbers. > > The problem is that I get no output here. My guess is you got a TypeError on the line letter=vehicle[index] decause index is a letter. It's important to give us accurate descriptions of what happens, and to show error messages and the tracebacks that come with them. This can be very helpful when you have a problem. Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Alternating patterns
I have a set that i iterate over... but each time through it i would like to alternate between the original set and a variation of the set that has one of the members of the set altered (by + or - 1) So if my original set is: [0, 2, 4, 5, 7, 9, 11] I would use that the first pass but on the second pass i might like the third member (4,) to become 3, (-1) resulting in : [0, 2, 3, 5, 7, 9, 11] But then back again to the original on the next pass (+1 back to 4,): [0, 2, 4, 5, 7, 9, 11] and then back: [0, 2, 3, 5, 7, 9, 11] again, etc. in other words i would like to alternate members of the set back and forth. Usually only 1 (or sometimes 2,) member at time. i could also imagine a needing(alter one, alter another, undo that, undo the first back to the original set): [0, 2, 4, 5, 7, 9, 11] --> [0, 2, 3, 5, 7, 9, 11] --> [0, 2, 3, 5, 7, 8, 10] --> [0, 2, 3, 5, 7, 9, 11] --> [0, 2, 4, 5, 7, 9, 11] or: original --> [0, 2, 4, 5, 7, 9, 11] altered --> [0, 2, 3, 5, 7, 9, 11] now back to 4, but change something else (like 11, is now 10): [0, 2, 4, 5, 7, 9, 10] etc... How can one make such alternating patterns? -kp-- ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Program for outputing the letter backward
--- John Fouhy <[EMAIL PROTECTED]> wrote: > On 29/03/06, Hoffmann <[EMAIL PROTECTED]> wrote: > > vehicle='car' > > index = vehicle[-1] #the last letter > > index_zero = vehicle[0] #the first letter > > > > while index >= index_zero: > >letter=vehicle[index] > >print letter > >index -= 1 > > > > The problem is that I get no output here. Could I > hear > > from you? > > I can print the letters backwards like this: > > vehicle = 'car' > print vehicle[2] > print vehicle[1] > print vehicle[0] > > Output: > > r > a > c > > - > > This is not very useful, though, because it will > only work for strings > that are exactly three letters long. Can you see > how to write a loop > to produe this output? > > Hint: the len() function will tell you how long a > string is. > > eg: if vehicle == 'car' then len(vehicle) == 3. > > -- > John. > ___ Hi John and the other colleagues from the Tutor, I still didn't realized how to solve this exercise. Regarding the for loop. I can do that for the "forward" version of the program. See below: name = 'car' for char in name: print char However, I still write a "backward" version (in order to get r a c Could you guys, please, continue talking to me? Thanks! Hoffmann __ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Bigrams and nested dictionaries
On 29/03/06, Michael Broe <[EMAIL PROTECTED]> wrote: > Well I ran into an interesting glitch already. For a dictionary D, I > can pull out a nested value using this syntax: > > >>> D['b']['a'] > 23 > > and I can assign to this dictionary using > > >>> D['d'] = {'a':7, 'b':0'} > > but I can't assign like this: > > >>> D['d']['c'] = 1 > TypeError: object does not support item assignment. I can't reproduce this... >>> D = {} >>> D['d'] = {'a':7, 'b':0} >>> D['d']['c'] = 1 >>> D {'d': {'a': 7, 'c': 1, 'b': 0}} Are you sure you haven't mistakenly assigned something other than a dict to D or D['d'] ? -- John. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Bigrams and nested dictionaries
Well I ran into an interesting glitch already. For a dictionary D, I can pull out a nested value using this syntax: >>> D['b']['a'] 23 and I can assign to this dictionary using >>> D['d'] = {'a':7, 'b':0'} but I can't assign like this: >>> D['d']['c'] = 1 TypeError: object does not support item assignment. hmmm. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Program for outputing the letter backward
Hoffman,I am a newbie at python and programming in general so excuse me if I'm wrong. In your example, you hadwhile index >= index_zero:which I believe to not be what you intended as you are essentially saying:while "last letter of vehicle" >= "first letter of vehicle""e" is respectively "less than" "v", so that is why your code never executes. You probably mean for the index to actually be the index, not the last letter. "index -= 1" is illegal as the variable points to a string, which can not be subtracted from. Hope I was of help!Johnston Jiaa ([EMAIL PROTECTED]) New Yahoo! Messenger with Voice. Call regular phones from your PC and save big.___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Bigrams and nested dictionaries
I'm playing with the whole idea of creating bigram (digram?) frequencies for text analysis and cryptographic and entropy analysis etc (this is as much an exercise in learning Python and programming as anything else, I realise everything has already been done somewhere somehow :) Though I *am* aiming to run this over unicoded phonetic representations of natural languages, which doesn't seem to be that common. I implemented a single character count using a dictionary, and it worked really well: Character_Count = {} for character in text: Character_Count[character] = Character_Count.get(character, 0) + 1 And so for bigrams I was thinking of creating a data-structure that was a nested dictionary, where the key was the character in position 1, and the value was a sub-dictionary that gave a count of each character in position 2. So the dictionary might begin something like: {'a': {'a':1, 'b':8, 'c':10,...}, 'b' : {'a':23, 'b':0, 'c': 1,...},..., 'z' : {'a':11, 'b':0, 'c':0,...}} The count of the character in position one could be retrieved by summing over the characters in position 2, so the bigram and single- character counts can be done in one pass. I don't want anyone to tell me how to do this :) I'd just like to get a feel for: (i) is this idea of a nested dictionary a good/efficient/tractable data-structure? (ii) is there a straightforward path to the goal of constructing this thing in a single pass over the input string (yes or no will suffice for the moment!), or is there a can of worms lurking in my future. I'd rather have less information than more, but there is something about grabbing characters two-at-a-time, but moving forward one-at-a- time, and sticking the count down a level inside the dictionary that's just a little baffling at the moment. On the other hand it's like moving a two-character window across the text and recording information as you go, which seems like it should be a good thing to do computationally. I like being baffled, I'd just kinda like to know if this is a good problem to work on to gain enlightenment, or a bad one and I should think about a totally different path with a less jazzy data structure. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Program for outputing the letter backward
Hoffmann wrote: > while index >= index_zero: >letter=vehicle[index] >print letter >index -= 1 > > The problem is that I get no output here. Could I hear > from you? Hi, remember that the condition for the while has to be true. When does index >= index_zero stop being true??? Hope that gets you going, Hugo Ps: there are easier ways of doing this in Python, consider the "for" statement. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Program for outputing the letter backward
On 29/03/06, Hoffmann <[EMAIL PROTECTED]> wrote: > vehicle='car' > index = vehicle[-1] #the last letter > index_zero = vehicle[0] #the first letter > > while index >= index_zero: >letter=vehicle[index] >print letter >index -= 1 > > The problem is that I get no output here. Could I hear > from you? I can print the letters backwards like this: vehicle = 'car' print vehicle[2] print vehicle[1] print vehicle[0] Output: r a c - This is not very useful, though, because it will only work for strings that are exactly three letters long. Can you see how to write a loop to produe this output? Hint: the len() function will tell you how long a string is. eg: if vehicle == 'car' then len(vehicle) == 3. -- John. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Program for outputing the letter backward
Hello: I am trying to write a code (this is an exercose from a book). The goal is to write a program that takes a string and outputs the letters backward, ine per line. Ok. I did a test first, by writing a code with numbers: a=0; b=10 while a<=b: print b b -= 1 Here the output is: 10 9 8 7 6 5 4 3 2 1 0 That worked fine. Now, back to my exercise. I tried to write a code that takes the string 'car' as the input: vehicle='car' index = vehicle[-1] #the last letter index_zero = vehicle[0] #the first letter while index >= index_zero: letter=vehicle[index] print letter index -= 1 The problem is that I get no output here. Could I hear from you? Thanks! Hoffmann __ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Guessing a number with limited no. of tries game gone wrong.
Hi Ros, Look what happens when the user tried for more than 5 times: if tries > 5: break This just takes you out of the loop, but it does not handle the issue that the user did not guess correctly. The next statement will be to print the congratulations message. You should instead tell the user they did not make it and exit the program altogether, probably letting them know what the actual number was. Something like: if tries > 5: print "Too bad. You tried one too many times." print "The number was", the_number sys.exit() You have to 'import sys' first though. Try it out and analyze the flow of the program. Use the debugger to try your code one step at a time to see what is going wrong. I would also change the initial guess to specify the range, like: guess = int(raw_input("Take a guess between 1 and 100: ")) Best of luck. Victor On Tue, 2006-03-28 at 12:20 -0500, Ros Daniel wrote: > I am a newbie at Python. Just bought Python Programming 2nd ed. by Michael > Dawson. While I understand the concepts as the book is going through the > code, and I am able get the same results, when it comes to applying what > I've learned to the exercises at the end of each chapter, I seem to be > stumped. I think my logic is off somehow. I am able to get the program to > work if it's just a case of the user guessing the random number, and then > being told they guessed correctly in a certain number of tries. It's when > the user has a limited number of guesses that I am stumped. Either I get an > infinite loop, or the program will say I guessed right in a certain number > of tries, but the guess is not correct > > Can anyone explain to me what I'm missing and doing wrong? Thanks. > > # Modify the Guess My Number game so that the player has a limited number of > guesses. If the player fails to guess in time, the program should display an > appropriately chastising message. > > > > import random > > print "Welcome to the new and improved 'Guess My Number' game." > print "This time you have a limited number of guesses, so guess wisely.\n" > > > the_number = random.randrange(100) + 1 > > guess = int(raw_input("Take a guess: ")) > tries = 1 > > # guessing loop > while (guess != the_number): > if tries > 5: > break > elif guess > the_number: > print "Lower..." > elif guess < the_number: > print "Higher..." > > guess = int(raw_input("Guess again:")) > tries += 1 > > > # message of congratulations > print "You guessed it! The number was", the_number > print "And it only took you", tries, "tries!\n" > > > ___ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Python tutor
On 3/27/06, Noufal Ibrahim <[EMAIL PROTECTED] > wrote: Greetings all, Are there any programs for python that offer an "interactive" tutorial?Something on the lines of the builtin emacs tutorial (which isbasically just a buffer that tells you to try this and try that with itself) or the Inkscape tutorial (which is an SVG document that comesalong with inkscape which has instructions on manipulating it so thatthe reader learns stuff). Another example that comes to mind is the tcltutor program to learn TCL. It contains an instruction window, acode window and an output window. The user is told something, they tryit and the output is visible. I personally used it when I was learningTCL. The python tutorial is great and probably all one needs to learn thelanguage but I think a more interactive program to teach it might beuseful. I googled a little and found Guido van Robot although I'm not sure if it's exactly like what I'm talking about. Are there any others?Do you all think it'll be a worthwhile project?There are several of us on the edupython list who want something like this but it hasn't (to my knowledge) been created yet. The best things out there so far, are livewires, guido von robot, and rur-ple. If you're interested in working on such a project, you're welcome to join us. http://groups.google.com/group/edupython-- cordially,Anna--It is fate, but call it Italy if it pleases you, Vicar! ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Object Oriented Programmin
> Subject: > [Tutor] Object Oriented Programmin > From: > "Kaushal Shriyan" <[EMAIL PROTECTED]> > Date: > Tue, 28 Mar 2006 12:57:58 +0530 > To: > tutor@python.org > > To: > tutor@python.org > > > Hi ALL > > I have gone through the object oriented programming in Python, I am > not able to understand OOP concept in python, > > is there a methodical way to understand it and simplfy things > > Thanks in Advance > > Regards > > Kaushal > If you are reading Learning Python(2nd Ed), the OOP section was a little thick to me. I read the book, The Object Oriented Thought Process. Then I went back and read the chapters on OOP in Learning Python, and it made a lot more sense. Mike ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Data Type with Dictionary and List Behavior
Carroll, Barry wrote: >Greetings: > >I have a function that computes the checksum of an integer, including or >excluding digits in the computation based on the content of a mask string. >For example, > >cksum(123456789, '***...***') > >will do its computation on 123789, masking out the three non-significant >digits. > >My question concerns assigning the value of the mask string. The class that >defines the function also pre-defines several masks, say '*', >'***...***', and '..***'. The masks have names: 'all', 'first-last', >'last'. Of these, 'all' is the most commonly used. The user may select one of >these masks, or may supply their own, arbitrary value. Further, the user can >choose to add their value to the group of pre-defines, and reuse that value >later in the session. (The user-defined mask is not saved between sessions; >no permanent storage is required.) > >So far, this structure looks like a dictionary. However, the user also wants >to access the group of pre-defined masks as if they were elements of a list: > > masks[0] returns '*' > masks[1] returns '***...***' > >and so on. To make matters even more complex, if the user does not specify a >mask to use, the function should use the mask employed in the previous >invocation, defaulting to masks[0] if this is the first invocation. Finally, >the user can set a mask as 'default', which essentially marks a mask as 'last >used' without invoking the function. > >Is there a derived type or data structure in existence that implements these >capabilities (in descending order of importance? > >1. Access by name (dict) >2. Access by position (list) >3. Addition of new items (dict, list) >4. Set a 'last used' item (??) >5. Set a 'default' item (dict???) > >Thanks in advance for your help. > >Regards, > >Barry >[EMAIL PROTECTED] >541-302-1107 > >We who cut mere stones must always be envisioning cathedrals. >-Quarry worker's creed > > >___ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor > > > Would the following fit the bill? >>> class maskdict(dict): def __init__(self, seq={}): dict.__init__(self,{True:["*","***...***","..***"],False:{"all":"*","first-last":"***...***","last":"..***",None:"**"}}) self.update(seq) def __getitem__(self, index=None): dict.__getitem__(self, isinstance(index,int))[index] self[None] = dict.__getitem__(self,isinstance(index,int))[index] return dict.__getitem__(self, False)[None] def __setitem__(self, index, value): if isinstance(index, int): return dict.__setitem__(self, isinstance(index,int), dict.__getitem__(self,isinstance(index,int))+[value]) return dict.__setitem__(dict.__getitem__(self, False), index, value) def setdef(self, default): self[None] = default >>> md = maskdict() >>> md[0] '*' >>> md["all"] '*' >>> md[1] '***...***' >>> md["first-last"] '***...***' >>> md[2] '..***' >>> md["last"] '..***' >>> md.__getitem__() # md[] results in a syntax error instead of passing None on to __getitem__ like you'd expect '..***' >>> md[1] '***...***' >>> md.__getitem__() '***...***' >>> md[0] '*' >>> md.__getitem__() '*' >>> md[3] = "." >>> md[3] '.' >>> md["first-four"] = md[3] >>> md["first-four"] '.' >>> md.setdef(md[3]) >>> md.__getitem__() '.' You'd still have to figure out how to integrate it in to your checksum function as well as make meaningful error messages, but it should give you a good start. Cheers, Orri -- Email: singingxduck AT gmail DOT com AIM: singingxduck Programming Python for the fun of it. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Python help
On Tue, 28 Mar 2006, Natasha Menon wrote: > i need help on a terrible homework assignment. do ul offer hw help? Not directly. Your homework is really your own to do. Please try to avoid the temptation of just posting a homework question here and hoping that someone will do the work for you. See: http://www.catb.org/~esr/faqs/smart-questions.html#homework But if you are asking for documentation or tutorial resources, or if you'd like to talk about general concepts or examples to help make things less confusing, we'll be happy to help in that way. Good luck to you. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Python help
hi,i need help on a terrible homework assignment. do ul offer hw help?natasha Yahoo! Messenger with Voice. PC-to-Phone calls for ridiculously low rates.___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Python tutor
This actually sounds like very good idea. I have not heard of it before, but I think it would be a very good way to learn. Let me know if you find anything.JohnOn 3/28/06, Noufal Ibrahim <[EMAIL PROTECTED]> wrote: Greetings all, Are there any programs for python that offer an "interactive" tutorial?Something on the lines of the builtin emacs tutorial (which isbasically just a buffer that tells you to try this and try that with itself) or the Inkscape tutorial (which is an SVG document that comesalong with inkscape which has instructions on manipulating it so thatthe reader learns stuff). Another example that comes to mind is the tcltutor program to learn TCL. It contains an instruction window, acode window and an output window. The user is told something, they tryit and the output is visible. I personally used it when I was learningTCL. The python tutorial is great and probably all one needs to learn thelanguage but I think a more interactive program to teach it might beuseful. I googled a little and found Guido van Robot although I'm not sure if it's exactly like what I'm talking about. Are there any others?Do you all think it'll be a worthwhile project?Bye---NI___Tutor maillist - Tutor@python.orghttp://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Guessing a number with limited no. of tries game gone wrong.
I am a newbie at Python. Just bought Python Programming 2nd ed. by Michael Dawson. While I understand the concepts as the book is going through the code, and I am able get the same results, when it comes to applying what I've learned to the exercises at the end of each chapter, I seem to be stumped. I think my logic is off somehow. I am able to get the program to work if it's just a case of the user guessing the random number, and then being told they guessed correctly in a certain number of tries. It's when the user has a limited number of guesses that I am stumped. Either I get an infinite loop, or the program will say I guessed right in a certain number of tries, but the guess is not correct Can anyone explain to me what I'm missing and doing wrong? Thanks. # Modify the Guess My Number game so that the player has a limited number of guesses. If the player fails to guess in time, the program should display an appropriately chastising message. import random print "Welcome to the new and improved 'Guess My Number' game." print "This time you have a limited number of guesses, so guess wisely.\n" the_number = random.randrange(100) + 1 guess = int(raw_input("Take a guess: ")) tries = 1 # guessing loop while (guess != the_number): if tries > 5: break elif guess > the_number: print "Lower..." elif guess < the_number: print "Higher..." guess = int(raw_input("Guess again:")) tries += 1 # message of congratulations print "You guessed it! The number was", the_number print "And it only took you", tries, "tries!\n" ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Tutor Digest, Vol 25, Issue 70
John: Well, I haven't made a custom container class before. This looks like a good time to start. And the sample code you provided looks like a good starting place. Thanks for your help. Regards, Barry [EMAIL PROTECTED] 541-302-1107 We who cut mere stones must always be envisioning cathedrals. -Quarry worker's creed > -- > > Message: 2 > Date: Tue, 28 Mar 2006 12:33:46 +1200 > From: "John Fouhy" <[EMAIL PROTECTED]> > Subject: Re: [Tutor] Data Type with Dictionary and List Behavior > To: tutor@python.org > Message-ID: > <[EMAIL PROTECTED]> > Content-Type: text/plain; charset=ISO-8859-1 > <> > > Probably your best bet is to define your own container class. If you > define __getitem__, you can use [] with instances of your class, just > like lists or dicts. > <> > > HTH! > > -- > John. > > ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] setdefault method
Terry and Kent: Thanks for your timely replies. I agree: its creator could have chosen a more intuitive name for setdefault. Regards, Barry [EMAIL PROTECTED] 541-302-1107 We who cut mere stones must always be envisioning cathedrals. -Quarry worker's creed ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Learning Python
I do recommend three books: (1) "How to Think Like a Computer Scientist: Learning with Python", by Allen Downey, Jeffrey Elkner, and Chris Meyers. There exist a free online version, too: http://www.ibiblio.org/obp/thinkCSpy/ (2) "Learning Python", by Mark Lutz and David Ascher. (3) "Beginning Python", by Magnus Lie Hetland. This is all you need for a good start with python. Hoffmann __ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Learning Python
If you're a bookish type, I found Magnus Lie Hetland's "Beginning Python" excellent. It's really more than a beginners books. I came to Python with a scripting background--mostly lightweight OS stuff (Applescript, DOS) as well as a lot of lightweight application programming (Filemaker, SQL, VBA for Excel, etc) and I got a lot out of the book. It covers the basics for a true beginner, but not in a dumbed-down way. It's also well indexed & somewhat useful as a reference for the most common things. Mark Pilgrim's "Dive Into Python" comes highly recommended, and is available on-line. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] BeautifulSoup - deleting tags
Kent Johnson writes: > [EMAIL PROTECTED] wrote: >> Is possible deleting all tags from a text and how? >> >> i.e.: >> >> s='foo bar; >> foo2 > title="...">bar2' >> >> so, I would get only: foo bar, foo2, bar2 > > How about this? > > In [1]: import BeautifulSoup > > In [2]: s=BeautifulSoup.BeautifulSoup('''foo > bar; >...: foo2 title="...">bar2''') > > In [4]: ' '.join(i.string for i in s.fetch() if i.string) > Out[4]: 'foo bar foo2 bar2' > > > Here are a couple of tag strippers that don't use BS: > http://www.aminus.org/rbre/python/cleanhtml.py > http://www.oluyede.org/blog/2006/02/13/html-stripper/ > > Kent > Another way (valid only for this case): : for i in s.fetch('a'): print i.string ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Object Oriented Programmin
On 3/28/06, Kent Johnson <[EMAIL PROTECTED]> wrote: > Kaushal Shriyan wrote: > > Hi ALL > > > > I have gone through the object oriented programming in Python, I am > > not able to understand OOP concept in python, > > Both Alan Gauld's tutorial and A Byte of Python have beginner's > introductions to OOP: > http://www.freenetpages.co.uk/hp/alan.gauld/ > http://www.byteofpython.info/read/oops.html > > I have written an essay that talks about *why* you might want to use > OOP, rathre than how... > http://www.pycs.net/users/323/stories/15.html > > Kent > > ___ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > Thanks a Bunch to All Kaushal ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] BeautifulSoup - deleting tags
[EMAIL PROTECTED] wrote: > Is possible deleting all tags from a text and how? > > i.e.: > > qwe='foo bar; > foo2 bar2' > > so, I would get only: foo bar, foo2, bar2 How about this? In [1]: import BeautifulSoup In [2]: s=BeautifulSoup.BeautifulSoup('''foo bar; ...: foo2 bar2''') In [4]: ' '.join(i.string for i in s.fetch() if i.string) Out[4]: 'foo bar foo2 bar2' Here are a couple of tag strippers that don't use BS: http://www.aminus.org/rbre/python/cleanhtml.py http://www.oluyede.org/blog/2006/02/13/html-stripper/ Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Object Oriented Programmin
Kaushal Shriyan wrote: > Hi ALL > > I have gone through the object oriented programming in Python, I am > not able to understand OOP concept in python, Both Alan Gauld's tutorial and A Byte of Python have beginner's introductions to OOP: http://www.freenetpages.co.uk/hp/alan.gauld/ http://www.byteofpython.info/read/oops.html I have written an essay that talks about *why* you might want to use OOP, rathre than how... http://www.pycs.net/users/323/stories/15.html Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] BeautifulSoup - deleting tags
Is possible deleting all tags from a text and how? i.e.: qwe='foo bar; foo2 bar2' so, I would get only: foo bar, foo2, bar2 Thanks in advance! ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] using BeautifulSoup
Kent Johnson writes: > [EMAIL PROTECTED] wrote: >> anchor.findNext('code') fails: >> >> anchor = soup.fetch('a', {'href': '/wiki/List_of_country_calling_codes'}) >> print anchor >> >> [Calling code] >> >> anchor.findNext('code') >> [] > > are you sure that's what you got? Looks like an AttributeError to me - > anchor is a *list* of anchors. Try > anchor[0].findNext('code') > > Kent > With 'fetch' you get a list of Tag objects, so there is that using: anchor = soup.fetch('a', {'href': '/wiki/List_of_country_calling_codes'}) anchor[0].findNext('code') But with 'findChild' or 'first' you get only the first Tag that matches, so: anchor = soup.findChild('a', {'href': '/wiki/List_of_country_calling_codes'}) anchor.findNext('code') Thanks for your help, Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Object Oriented Programmin
Object is object, means like ordinary object we know.Let's say good things about objecs paradigm.First you can create object of course. object can contain property and action.You can put your object as part as other object. It makes sense since for example object hand is part of object body in human term. You can derive a new object from your old one (with its property and action). You can, in this new object, add a new function or change the function from the old one. This will make your old object untouchable and your new object easy to build (you don't have to build from the start) Let's start with a simple code.We can create a simple dog classclass dog: def __init__(self, name): self.name = name pass def action(self): print 'run'class doberman(dog): def __init__(self, name): dog.__init__(self,name) def bark(self): print 'wuu'class coco(dog): def __init__(self, name): dog.__init__(self,name) def action(self): print 'jump' def bark(self): print 'waa'#--d1 = doberman('deni') d1.action() # 'run'd1.bark() # 'wuu' d2 = coco('mayin')d2.action() # 'jump'd2.bark() # 'waa'Note:Each has name as an ID. a doberman uses the same action like dog classa coco uses different action than the original action from dog which is 'run'In this example we can see we can change one object easily and doesn't change the original class which is dog. This make less prone to error. both doberman and coco can use bark but the result will be differentboth doberman and coco can access name this also result in different way.It is nice since you can use the same word bark to all of the new dogs you've created. I try to describe as simple as I can. In this example you can put another function like getname in dog class so that all type of dogs has this function automaticaly.Hope this helppujo On 3/28/06, Kaushal Shriyan <[EMAIL PROTECTED]> wrote: Hi ALLI have gone through the object oriented programming in Python, I amnot able to understand OOP concept in python,is there a methodical way to understand it and simplfy thingsThanks in Advance RegardsKaushal___Tutor maillist - Tutor@python.orghttp://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor