smart baba new year special offer
Smart Baba special limited offer. We are the only world lowest-cost, yet professional and elegant-designing website developing company. Follow us for further details: www.websitedeals.com -- http://mail.python.org/mailman/listinfo/python-list
Re: pythagorean triples exercise
On Oct 22, 8:07 am, Dennis Lee Bieber wlfr...@ix.netcom.com wrote: On Thu, 21 Oct 2010 03:51:07 -0700 (PDT), Baba raoul...@gmail.com declaimed the following in gmane.comp.python.general: Hi everyone i need a hint regarding the following exercise question: Write a program that generates all Pythagorean triples whose small sides are no larger than n. Try it with n = 200. what is n ? i am guessing that it is a way to give a bound to the triples to be returned but i can't figure out where to fit in n. a^a + b^b = c^c is the condition to satisfy and i need to use loops Well, I'd interpret it to mean that a = 200 AND b = 200 since c is the hypotenuse, which by definition is longer than either of the sides. The brute force approach is a nested set of for loops, running 1-200 (remember that (x)range(200) runs 0-199 G). The alternative is to study the information at http://www.math.uic.edu/~fields/puzzle/triples.html and filtering out entries where the first two components are 200... Looking at the middle term 2*m*n would have to be less than 201, and the first term n*n-m*m 201 In Python, this can all be done in a one-liner... [(n*n - m*m, 2*m*n, n*n + m*m) for n in xrange(2,101) for m in xrange(1,n) if 2*m*n 201 and n*n-m*m 201] Converting this to a clean set of nested loops and nice lines of output is a different matter. Oh, and DO study the link I gave so you can cite it when you turn in this intriguing formulation... after all, no need for math.sqrt G -- Wulfraed Dennis Lee Bieber AF6VN wlfr...@ix.netcom.com HTTP://wlfraed.home.netcom.com/ Hi Wulfraed, only a has an upper limit of 200 the program needs to output the following triple for a == 200: (200 , 609,641) so at this stage my problem is: how to set the upper limit for b in a smart way? My solution below is not efficient i believe. import math for a in range (190,200): for b in range (a,a*a): csqrd = a * a + b * b csqrt = math.sqrt(csqrd) for c in range (1, csqrd): if c * c == a * a + b * b and math.floor(csqrt) == csqrt: print (a,b,c) -- http://mail.python.org/mailman/listinfo/python-list
Re: pythagorean triples exercise
On Oct 22, 6:35 am, Terry Reedy tjre...@udel.edu wrote: On 10/21/2010 7:55 PM, Baba wrote: the bit i'm having difficulties with in constructing my loops is: whose small sides are no larger than n from math import sqrt def py_trips(n): for b in range(4,n+1): for a in range(3,b+1): cf = sqrt(a*a+b*b) c = int(cf) if c == cf: yield a, b, c for t in py_trips(200): print(t) # prints (3,4,5) ... (150, 200, 250) This version assumes that if a*a+b*c is an exact square of an integer, the floating point sqrt will be an exact integral value, which I believe it should be for values up to the max (for n max 200) of 8. It produces multiples of each triple, such as (3,4,5), (6,8,10), (9,12,15), ... (150,200, 250), which a different formulation of the problem might exclude, to only ask for 'basic' triples of relatively prime numbers. -- Terry Jan Reedy Hi Terry Only a has an upper limit of 200. The exercise is n ot clar about that i agree but assuming i am correct my program would need to be able to generate the following triple: (200 ,609,641 ) My code below does that now but i think the way i compute b's upper limit is not efficient. import math for a in range (1,200): for b in range (a,200): csqrd = a * a + b * b c = math.sqrt(csqrd) if math.floor(c) == c: print (a,b,int(c)) thanks Baba -- http://mail.python.org/mailman/listinfo/python-list
Re: pythagorean triples exercise
On Oct 22, 6:35 am, Terry Reedy tjre...@udel.edu wrote: On 10/21/2010 7:55 PM, Baba wrote: the bit i'm having difficulties with in constructing my loops is: whose small sides are no larger than n from math import sqrt def py_trips(n): for b in range(4,n+1): for a in range(3,b+1): cf = sqrt(a*a+b*b) c = int(cf) if c == cf: yield a, b, c for t in py_trips(200): print(t) # prints (3,4,5) ... (150, 200, 250) This version assumes that if a*a+b*c is an exact square of an integer, the floating point sqrt will be an exact integral value, which I believe it should be for values up to the max (for n max 200) of 8. It produces multiples of each triple, such as (3,4,5), (6,8,10), (9,12,15), ... (150,200, 250), which a different formulation of the problem might exclude, to only ask for 'basic' triples of relatively prime numbers. -- Terry Jan Reedy Hi All, Only 'a' has an upper limit of 200. The exercise is not clar about that maybe but assuming i am correct my program would need to be able to generate the following triple: (200 ,609,641 ) My code below does that now but i think the way i compute b's upper limit is not efficient. import math for a in range (1,200): for b in range (a, a * a): csqrd = a * a + b * b c = math.sqrt(csqrd) if math.floor(c) == c: print (a,b,int(c)) thanks Baba -- http://mail.python.org/mailman/listinfo/python-list
pythagorean triples exercise
Hi everyone i need a hint regarding the following exercise question: Write a program that generates all Pythagorean triples whose small sides are no larger than n. Try it with n = 200. what is n ? i am guessing that it is a way to give a bound to the triples to be returned but i can't figure out where to fit in n. a^a + b^b = c^c is the condition to satisfy and i need to use loops and n will be an upper limit of one (or more?) of the loops but i am a bit lost. Please help me get thinking about this right. exercise source: Java by Dissection (Ira Pohl and Charlie McDowell) thanks Baba -- http://mail.python.org/mailman/listinfo/python-list
pythagorean triples exercise
Hi everyone i need a hint regarding the following exercise question: Write a program that generates all Pythagorean triples whose small sides are no larger than n. Try it with n = 200. what is n ? i am guessing that it is a way to give a bound to the triples to be returned but i can't figure out where to fit in n. a^a + b^b = c^c is the condition to satisfy and i need to use loops and n will be an upper limit of one (or more?) of the loops but i am a bit lost. Please help me get thinking about this right. import math for b in range(20): for a in range(1, b): c = math.sqrt( a * a + b * b) if c % 1 == 0: print (a, b, int(c)) this returns (3, 4, 5) (6, 8, 10) (5, 12, 13) (9, 12, 15) (8, 15, 17) (12, 16, 20) is that the desired output? what is the step that i'm missing? thanks in advance Baba p.s. this is not homework but self-study -- http://mail.python.org/mailman/listinfo/python-list
Re: pythagorean triples exercise
On Oct 21, 10:18 pm, Terry Reedy tjre...@udel.edu wrote: On 10/21/2010 6:55 AM, Baba wrote: Hi everyone i need a hint regarding the following exercise question: Write a program that generates all Pythagorean triples whose small sides are no larger than n. This is not well worded. I take 'small sides' (plural) to mean the two smaller, non-hypotenuse sides (which are necessarily shorter than the hypotenuse). So the possible pairs of values i,j, where i is the shorter of the two, have Try it with n= 200. Again, not well worded; I believe this is meant to be n==200, except that the program should take n as a parameter and then give it value 200, so that the could work if n were given some other value. So the possible pairs of values i,j, where i is the shorter of the two, have j = n (==200) and i = j. -- Terry Jan Reedy Hi Terry, the full exercise reads as follows: Write a program that generates all Pythagorean triples whose small sides are no larger than n. Try it with n = 200. (Hint: Use two for loops to enumerate possible values for the small sides and then test to determine whether the result is an integral square. source: http://users.soe.ucsc.edu/~pohl/12A/ch03-state.pdf (exercise 11, it's a Java book but i like to use Python for solving such basic exercises as it is a much less cumbersome language) i agree that possibly the wording makes this more difficult than it is. Anyway, i'm a beginner so my problem solving techniques are still quite shaky. the bit i'm having difficulties with in constructing my loops is: whose small sides are no larger than n i don't know what to do with that :( Baba -- http://mail.python.org/mailman/listinfo/python-list
Re: lists and list item matches (ghost wodgame)
On Sep 23, 4:17 pm, nn prueba...@latinmail.com wrote: On Sep 23, 10:56 am, nn prueba...@latinmail.com wrote: On Sep 22, 6:39 pm, Baba raoul...@gmail.com wrote: On Sep 22, 9:18 pm, Baba raoul...@gmail.com wrote: On Sep 22, 3:38 pm, nn prueba...@latinmail.com wrote: On Sep 21, 6:39 pm, Baba raoul...@gmail.com wrote: Hi query level: beginner as part of a learning exercise i have written code that: a) asks for a single letter input (assumption: only 1 letter wil be entered) b) adds that letter to list1 and then goes through list2 and checks: 1) if any item in list2 starts with list1 if False: break 2) if list1 == any item in list2 if True: break c) start again until 2) is True wordlist = ['hello', 'bye'] handlist = [] letter = raw_input('enter letter: ') handlist.append(letter) hand = .join(handlist) for item in wordlist: if item.startswith(hand): while item.startswith(hand): if hand not in wordlist: letter = raw_input('enter letter: ') handlist.append(letter) hand = .join(handlist) else: break else: break print 'you loose' this code works but can it be optimised? i have the feeling that my nesting of IF, WHILE and FOR statements is overkill? inspired by part IV ofhttp://ocw.mit.edu/courses/electrical-engineering-and-computer-scienc... thanks Baba Yes it is overkill. Especially the else:break from the while loop makes it difficult to follow the logic. Also the program breaks down if I use the following word list: wordlist = ['hello', 'hamburger', 'bye'] enter letter: h enter letter: a you loose I am not going to post any spoilers but I wrote your program using one while loop and one generator expression for a total of 5 lines. My version might be a bit too advanced but you should still be able to do it using only one while, one for and one if instead. Hi nn, i wasn't expecting my code to fail with an additional word in it. While i was conscious that the whole construct was heavy i thought the reasoning worked. I keep looking at it but can't figure out the problem Can you give me a hint? In the meantime i found out that it is actually possible to populate a string (just like a list, a dictionary or a tuple). Here's what i've got now: wordlist = ['hello', 'bye'] hand = '' for item in wordlist: if item.startswith(hand): while item.startswith(hand): if hand not in wordlist: hand += raw_input('enter letter: ') print hand else: break else: break print 'you loose' But i can't figure out why it won't work when adding the extra word. Thanks by the way, it taught me not to be too confident when things SEEM to work... Why does it work when i use the built-in function any(iterable)?? To me using the any(iterable) function seems just like regrouping 3 lines into one... wordlist = ['hello','hamburger', 'bye', 'cello'] hand = '' while any(item.startswith(hand) for item in wordlist): if hand not in wordlist: hand += raw_input('enter letter: ') else: break print 'you loose' thanks Baba Hi nn, looking at my original code again i realise that having a raw_input inside a FOR loop is flawed per se (at least for my purposes) so i will just assume that i was taking the wrong approach initially. No point in analysing it further. Thanks for your help. Baba Since you seem to have figured it out I will post my version (python 3): wordlist = ['hello', 'hamburger', 'bye'] inp='' while any(word.startswith(inp) and word!=inp for word in wordlist): inp += input('enter letter: ') print('you lose') The reason why your original version didn't work was because each time you add a letter you have to go again over all words (in reality only a subset is required) and find a new one. Your version would find one word using the first letter and then exit. Actually my version isn't right (for some values of right): wordlist = ['hello', 'hamburger', 'bye'] inp='' while any(word.startswith(inp) for word in wordlist) and (inp not in wordlist): inp += input('enter letter: ') print('you lose') An explanation of how this changes the rules of the wordgame is left as an exercise to the reader. Hi, for now i will stick to Python2.7 but thank you for sharing. for learning purposes i still want to figure out a way to solve this without built-in function ('any' in this case). My understanding was that in programming almost anything can be done with IF, FOR and WHILE statements. However i turn
Re: lists and list item matches (ghost wodgame)
On Sep 23, 8:13 pm, nn prueba...@latinmail.com wrote: On Sep 23, 1:25 pm, Baba raoul...@gmail.com wrote: On Sep 23, 4:17 pm, nn prueba...@latinmail.com wrote: On Sep 23, 10:56 am, nn prueba...@latinmail.com wrote: On Sep 22, 6:39 pm, Baba raoul...@gmail.com wrote: On Sep 22, 9:18 pm, Baba raoul...@gmail.com wrote: On Sep 22, 3:38 pm, nn prueba...@latinmail.com wrote: On Sep 21, 6:39 pm, Baba raoul...@gmail.com wrote: Hi query level: beginner as part of a learning exercise i have written code that: a) asks for a single letter input (assumption: only 1 letter wil be entered) b) adds that letter to list1 and then goes through list2 and checks: 1) if any item in list2 starts with list1 if False: break 2) if list1 == any item in list2 if True: break c) start again until 2) is True wordlist = ['hello', 'bye'] handlist = [] letter = raw_input('enter letter: ') handlist.append(letter) hand = .join(handlist) for item in wordlist: if item.startswith(hand): while item.startswith(hand): if hand not in wordlist: letter = raw_input('enter letter: ') handlist.append(letter) hand = .join(handlist) else: break else: break print 'you loose' this code works but can it be optimised? i have the feeling that my nesting of IF, WHILE and FOR statements is overkill? inspired by part IV ofhttp://ocw.mit.edu/courses/electrical-engineering-and-computer-scienc... thanks Baba Yes it is overkill. Especially the else:break from the while loop makes it difficult to follow the logic. Also the program breaks down if I use the following word list: wordlist = ['hello', 'hamburger', 'bye'] enter letter: h enter letter: a you loose I am not going to post any spoilers but I wrote your program using one while loop and one generator expression for a total of 5 lines. My version might be a bit too advanced but you should still be able to do it using only one while, one for and one if instead. Hi nn, i wasn't expecting my code to fail with an additional word in it. While i was conscious that the whole construct was heavy i thought the reasoning worked. I keep looking at it but can't figure out the problem Can you give me a hint? In the meantime i found out that it is actually possible to populate a string (just like a list, a dictionary or a tuple). Here's what i've got now: wordlist = ['hello', 'bye'] hand = '' for item in wordlist: if item.startswith(hand): while item.startswith(hand): if hand not in wordlist: hand += raw_input('enter letter: ') print hand else: break else: break print 'you loose' But i can't figure out why it won't work when adding the extra word. Thanks by the way, it taught me not to be too confident when things SEEM to work... Why does it work when i use the built-in function any(iterable)?? To me using the any(iterable) function seems just like regrouping 3 lines into one... wordlist = ['hello','hamburger', 'bye', 'cello'] hand = '' while any(item.startswith(hand) for item in wordlist): if hand not in wordlist: hand += raw_input('enter letter: ') else: break print 'you loose' thanks Baba Hi nn, looking at my original code again i realise that having a raw_input inside a FOR loop is flawed per se (at least for my purposes) so i will just assume that i was taking the wrong approach initially. No point in analysing it further. Thanks for your help. Baba Since you seem to have figured it out I will post my version (python 3): wordlist = ['hello', 'hamburger', 'bye'] inp='' while any(word.startswith(inp) and word!=inp for word in wordlist): inp += input('enter letter: ') print('you lose') The reason why your original version didn't work was because each time you add a letter you have to go again over all words (in reality only a subset is required) and find a new one. Your version would find one word using the first letter and then exit. Actually my version isn't right (for some values of right): wordlist = ['hello', 'hamburger', 'bye'] inp='' while any(word.startswith(inp) for word in wordlist) and (inp not in wordlist): inp += input('enter letter: ') print('you lose') An explanation
Re: lists and list item matches (ghost wodgame)
On Sep 23, 8:13 pm, nn prueba...@latinmail.com wrote: On Sep 23, 1:25 pm, Baba raoul...@gmail.com wrote: On Sep 23, 4:17 pm, nn prueba...@latinmail.com wrote: On Sep 23, 10:56 am, nn prueba...@latinmail.com wrote: On Sep 22, 6:39 pm, Baba raoul...@gmail.com wrote: On Sep 22, 9:18 pm, Baba raoul...@gmail.com wrote: On Sep 22, 3:38 pm, nn prueba...@latinmail.com wrote: On Sep 21, 6:39 pm, Baba raoul...@gmail.com wrote: Hi query level: beginner as part of a learning exercise i have written code that: a) asks for a single letter input (assumption: only 1 letter wil be entered) b) adds that letter to list1 and then goes through list2 and checks: 1) if any item in list2 starts with list1 if False: break 2) if list1 == any item in list2 if True: break c) start again until 2) is True wordlist = ['hello', 'bye'] handlist = [] letter = raw_input('enter letter: ') handlist.append(letter) hand = .join(handlist) for item in wordlist: if item.startswith(hand): while item.startswith(hand): if hand not in wordlist: letter = raw_input('enter letter: ') handlist.append(letter) hand = .join(handlist) else: break else: break print 'you loose' this code works but can it be optimised? i have the feeling that my nesting of IF, WHILE and FOR statements is overkill? inspired by part IV ofhttp://ocw.mit.edu/courses/electrical-engineering-and-computer-scienc... thanks Baba Yes it is overkill. Especially the else:break from the while loop makes it difficult to follow the logic. Also the program breaks down if I use the following word list: wordlist = ['hello', 'hamburger', 'bye'] enter letter: h enter letter: a you loose I am not going to post any spoilers but I wrote your program using one while loop and one generator expression for a total of 5 lines. My version might be a bit too advanced but you should still be able to do it using only one while, one for and one if instead. Hi nn, i wasn't expecting my code to fail with an additional word in it. While i was conscious that the whole construct was heavy i thought the reasoning worked. I keep looking at it but can't figure out the problem Can you give me a hint? In the meantime i found out that it is actually possible to populate a string (just like a list, a dictionary or a tuple). Here's what i've got now: wordlist = ['hello', 'bye'] hand = '' for item in wordlist: if item.startswith(hand): while item.startswith(hand): if hand not in wordlist: hand += raw_input('enter letter: ') print hand else: break else: break print 'you loose' But i can't figure out why it won't work when adding the extra word. Thanks by the way, it taught me not to be too confident when things SEEM to work... Why does it work when i use the built-in function any(iterable)?? To me using the any(iterable) function seems just like regrouping 3 lines into one... wordlist = ['hello','hamburger', 'bye', 'cello'] hand = '' while any(item.startswith(hand) for item in wordlist): if hand not in wordlist: hand += raw_input('enter letter: ') else: break print 'you loose' thanks Baba Hi nn, looking at my original code again i realise that having a raw_input inside a FOR loop is flawed per se (at least for my purposes) so i will just assume that i was taking the wrong approach initially. No point in analysing it further. Thanks for your help. Baba Since you seem to have figured it out I will post my version (python 3): wordlist = ['hello', 'hamburger', 'bye'] inp='' while any(word.startswith(inp) and word!=inp for word in wordlist): inp += input('enter letter: ') print('you lose') The reason why your original version didn't work was because each time you add a letter you have to go again over all words (in reality only a subset is required) and find a new one. Your version would find one word using the first letter and then exit. Actually my version isn't right (for some values of right): wordlist = ['hello', 'hamburger', 'bye'] inp='' while any(word.startswith(inp) for word in wordlist) and (inp not in wordlist): inp += input('enter letter: ') print('you lose') An explanation
Re: lists and list item matches (ghost wodgame)
On Sep 22, 3:38 pm, nn prueba...@latinmail.com wrote: On Sep 21, 6:39 pm, Baba raoul...@gmail.com wrote: Hi query level: beginner as part of a learning exercise i have written code that: a) asks for a single letter input (assumption: only 1 letter wil be entered) b) adds that letter to list1 and then goes through list2 and checks: 1) if any item in list2 starts with list1 if False: break 2) if list1 == any item in list2 if True: break c) start again until 2) is True wordlist = ['hello', 'bye'] handlist = [] letter = raw_input('enter letter: ') handlist.append(letter) hand = .join(handlist) for item in wordlist: if item.startswith(hand): while item.startswith(hand): if hand not in wordlist: letter = raw_input('enter letter: ') handlist.append(letter) hand = .join(handlist) else: break else: break print 'you loose' this code works but can it be optimised? i have the feeling that my nesting of IF, WHILE and FOR statements is overkill? inspired by part IV ofhttp://ocw.mit.edu/courses/electrical-engineering-and-computer-scienc... thanks Baba Yes it is overkill. Especially the else:break from the while loop makes it difficult to follow the logic. Also the program breaks down if I use the following word list: wordlist = ['hello', 'hamburger', 'bye'] enter letter: h enter letter: a you loose I am not going to post any spoilers but I wrote your program using one while loop and one generator expression for a total of 5 lines. My version might be a bit too advanced but you should still be able to do it using only one while, one for and one if instead. Hi nn, i wasn't expecting my code to fail with an additional word in it. While i was conscious that the whole construct was heavy i thought the reasoning worked. I keep looking at it but can't figure out the problem Can you give me a hint? In the meantime i found out that it is actually possible to populate a string (just like a list, a dictionary or a tuple). Here's what i've got now: wordlist = ['hello', 'bye'] hand = '' for item in wordlist: if item.startswith(hand): while item.startswith(hand): if hand not in wordlist: hand += raw_input('enter letter: ') print hand else: break else: break print 'you loose' But i can't figure out why it won't work when adding the extra word. Thanks by the way, it taught me not to be too confident when things SEEM to work... Why does it work when i use the built-in function any(iterable)?? To me using the any(iterable) function seems just like regrouping 3 lines into one... wordlist = ['hello','hamburger', 'bye', 'cello'] hand = '' while any(item.startswith(hand) for item in wordlist): if hand not in wordlist: hand += raw_input('enter letter: ') else: break print 'you loose' thanks Baba -- http://mail.python.org/mailman/listinfo/python-list
Re: lists and list item matches (ghost wodgame)
On Sep 22, 9:18 pm, Baba raoul...@gmail.com wrote: On Sep 22, 3:38 pm, nn prueba...@latinmail.com wrote: On Sep 21, 6:39 pm, Baba raoul...@gmail.com wrote: Hi query level: beginner as part of a learning exercise i have written code that: a) asks for a single letter input (assumption: only 1 letter wil be entered) b) adds that letter to list1 and then goes through list2 and checks: 1) if any item in list2 starts with list1 if False: break 2) if list1 == any item in list2 if True: break c) start again until 2) is True wordlist = ['hello', 'bye'] handlist = [] letter = raw_input('enter letter: ') handlist.append(letter) hand = .join(handlist) for item in wordlist: if item.startswith(hand): while item.startswith(hand): if hand not in wordlist: letter = raw_input('enter letter: ') handlist.append(letter) hand = .join(handlist) else: break else: break print 'you loose' this code works but can it be optimised? i have the feeling that my nesting of IF, WHILE and FOR statements is overkill? inspired by part IV ofhttp://ocw.mit.edu/courses/electrical-engineering-and-computer-scienc... thanks Baba Yes it is overkill. Especially the else:break from the while loop makes it difficult to follow the logic. Also the program breaks down if I use the following word list: wordlist = ['hello', 'hamburger', 'bye'] enter letter: h enter letter: a you loose I am not going to post any spoilers but I wrote your program using one while loop and one generator expression for a total of 5 lines. My version might be a bit too advanced but you should still be able to do it using only one while, one for and one if instead. Hi nn, i wasn't expecting my code to fail with an additional word in it. While i was conscious that the whole construct was heavy i thought the reasoning worked. I keep looking at it but can't figure out the problem Can you give me a hint? In the meantime i found out that it is actually possible to populate a string (just like a list, a dictionary or a tuple). Here's what i've got now: wordlist = ['hello', 'bye'] hand = '' for item in wordlist: if item.startswith(hand): while item.startswith(hand): if hand not in wordlist: hand += raw_input('enter letter: ') print hand else: break else: break print 'you loose' But i can't figure out why it won't work when adding the extra word. Thanks by the way, it taught me not to be too confident when things SEEM to work... Why does it work when i use the built-in function any(iterable)?? To me using the any(iterable) function seems just like regrouping 3 lines into one... wordlist = ['hello','hamburger', 'bye', 'cello'] hand = '' while any(item.startswith(hand) for item in wordlist): if hand not in wordlist: hand += raw_input('enter letter: ') else: break print 'you loose' thanks Baba Hi nn, looking at my original code again i realise that having a raw_input inside a FOR loop is flawed per se (at least for my purposes) so i will just assume that i was taking the wrong approach initially. No point in analysing it further. Thanks for your help. Baba -- http://mail.python.org/mailman/listinfo/python-list
basic 2 player wordgame
Hi I am working on a simple wordgame exercise: 2 players form a word by alternating turns saying a letter, which is added on to the end of the word fragment. I am familiar with loops, iterations etc but i need a hint as to how to approach alternating turns when writing this code? exercise source: http://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-00-introduction-to-computer-science-and-programming-fall-2008/assignments/pset5.pdf thanks Baba -- http://mail.python.org/mailman/listinfo/python-list
Re: basic 2 player wordgame
On Sep 21, 1:39 pm, Mel mwil...@the-wire.com wrote: Baba wrote: I am working on a simple wordgame exercise: 2 players form a word by alternating turns saying a letter, which is added on to the end of the word fragment. I am familiar with loops, iterations etc but i need a hint as to how to approach alternating turns when writing this code? One way (not tested): thisplayer = Player() otherplayer = Player() while not_won: thisplayer.take_turn() thisplayer, otherplayer = otherplayer, thisplayer Mel. Hi Mel, Thank you very much. Your suggestion works like a charm :) def alternating_turns(): hand = [] thisPlayer = 'player1' otherPlayer = 'player2' while len(hand) 3: print 'turn %s: ' %(thisPlayer) letter = raw_input('enter letter: ') hand.append(letter) thisPlayer, otherPlayer = otherPlayer, thisPlayer print hand alternating_turns() thanks again! much appreciated. this was a first for me where i have learned a practical way to apply mutation. Baba -- http://mail.python.org/mailman/listinfo/python-list
lists and list item matches (ghost wodgame)
Hi query level: beginner as part of a learning exercise i have written code that: a) asks for a single letter input (assumption: only 1 letter wil be entered) b) adds that letter to list1 and then goes through list2 and checks: 1) if any item in list2 starts with list1 if False: break 2) if list1 == any item in list2 if True: break c) start again until 2) is True wordlist = ['hello', 'bye'] handlist = [] letter = raw_input('enter letter: ') handlist.append(letter) hand = .join(handlist) for item in wordlist: if item.startswith(hand): while item.startswith(hand): if hand not in wordlist: letter = raw_input('enter letter: ') handlist.append(letter) hand = .join(handlist) else: break else: break print 'you loose' this code works but can it be optimised? i have the feeling that my nesting of IF, WHILE and FOR statements is overkill? inspired by part IV of http://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-00-introduction-to-computer-science-and-programming-fall-2008/assignments/pset5.pdf thanks Baba -- http://mail.python.org/mailman/listinfo/python-list
Re: accessing a text file
On Sep 9, 10:09 pm, Nobody nob...@nowhere.com wrote: On Wed, 08 Sep 2010 03:30:00 -0700, Baba wrote: Who is licensed to judge what can and cannot be posted as a question? Exactly the same set of people who are licensed to judge what can and cannot be posted as an answer. If you don't like the responses you get here, you could try posting your questions on 4chan. If nothing else, that will give you a whole new perspective on what an unfriendly response really looks like. I would to apologise to anyone who might have been upset or offended by my reaction. I am new to forums (as i am new to programming) so i hope i might be forgiven for not appreciating the true value of the support one can receive on this forum. I wish to reiterate that i underatand that experts provide help free of charge and in their spare time so there's no point for me to like or dislike the style of an answer. Baba -- http://mail.python.org/mailman/listinfo/python-list
Re: analysis of algoritms
On Sep 9, 11:22 pm, Alain Ketterlin al...@dpt-info.u-strasbg.fr wrote: Baba raoul...@gmail.com writes: In below code the outer loop test in step 4 will execute ( n + 1 ) times (note that an extra step is required to terminate the for loop, hence n + 1 and not n executions), which will consume T4( n + 1 ) time. (fromhttp://en.wikipedia.org/wiki/Analysis_of_algorithms) 1 get a positive integer from input 2 if n 10 3 print This might take a while... 4 for i = 1 to n 5 for j = 1 to i 6 print i * j 7 print Done! Why does step 4 execute n+1 times? what is the exta step mentioned above In the outer loop test [...], the important word is _test_. Line 4 has to test the value of i against n, which results in true n times and in false once (where it jumps to instruction 7). Note that this would be true even with python loops using range(n) or xrange(n), where the test is not an integer comparison. (Note also how this last remark tries to avoid complete off-topic-ness of this discussion in this group :-) -- Alain. Hi Alain Thanks for the explanation! Baba -- http://mail.python.org/mailman/listinfo/python-list
analysis of algoritms
Hi In below code the outer loop test in step 4 will execute ( n + 1 ) times (note that an extra step is required to terminate the for loop, hence n + 1 and not n executions), which will consume T4( n + 1 ) time. (from http://en.wikipedia.org/wiki/Analysis_of_algorithms) 1get a positive integer from input 2if n 10 3print This might take a while... 4for i = 1 to n 5for j = 1 to i 6print i * j 7print Done! Why does step 4 execute n+1 times? what is the exta step mentioned above tnx Baba -- http://mail.python.org/mailman/listinfo/python-list
Re: mutate dictionary or list
On 7 sep, 16:46, Ben Finney ben+pyt...@benfinney.id.au wrote: de...@web.de writes: Objects can be mutable or immutable. For example, in Python, integers, strings, floats and tuples are immutable. That means that you can't change their value. Yes. Importantly, wherever you see code that you *think* is changing the value of an immutable object, you're thinking incorrectly. (There's no shame in that; other languages give us preconceptions that can be hard to shake off.) The only way to get a different value from an integer object is to ask Python for a different integer object; the original is unchanged. The same goes for tuples, strings, and all the other immutable types. Mutable objects OTOH can be changed. […] Some good articles to explain Python's object model: URL:http://effbot.org/zone/python-objects.htm URL:http://docs.python.org/reference/datamodel.html#objects-values-and-types -- \ “We can't depend for the long run on distinguishing one | `\ bitstream from another in order to figure out which rules | _o__) apply.” —Eben Moglen, _Anarchism Triumphant_, 1999 | Ben Finney Thanks all for feedback! Baba -- http://mail.python.org/mailman/listinfo/python-list
Re: accessing a text file
On 8 sep, 02:07, Ben Finney ben+pyt...@benfinney.id.au wrote: Baba raoul...@gmail.com writes: However the following Wiki excerpt seems to go in my direction: No, it doesn't. It advises that people show kindness; as I've been arguing, that's exactly what you were shown. You haven't shown how the information being imparted could have been fully imparted in a way that's kinder, nor that it would be reasonable to do so. To put it another way: if you feel offended by an utterance, then insufficient kindness on the part of the speaker is not the only explanation. -- \ “Software patents provide one more means of controlling access | `\ to information. They are the tool of choice for the internet | _o__) highwayman.” —Anthony Taylor | Ben Finney Hi Ben, Thanks for your feedback. My question is: Who owns this forum? If we all do then we are allowed to post questions that are simple and that could otherwise be answered by doing research. It is just unfriendly to tell someone to go and look it up by themselves. Who is licensed to judge what can and cannot be posted as a question? A teacher of mine used to say: There are no stupid questions, there are only stupid answers. It is arrogant to tell someone in a Forum to look it up yourself ,this question is too basic. Can you not understand that accessing a file can seem daunting at first? Believe me, documentation can be offputting too when you only start with programming. Per se the beauty of forums like these is that there are human beings willing to make such tasks as finding out how to access a text file less 'scary'. Whoever thinks he or she has a license to tell someone to look up the answer by themselves should think again. I reckon the only license we have is not to answer at all. I acknowledge that Benjamin pointed me to the right place to find an answer but somehow the Please do us a favour sounded bit arrogant, as if he owned the place (same goes for all those who sided against me here: do you own this forum?)...i'd be glad if there was a python for beginners forum but in the meantime i have to say i find it awesome to have this forum to get help. It makes a BIG difference. So sorry if i upset anyone, we all have our opinions and get carried away and can be stubborn, i DO respect everyone in this forum and i think it goes bothways. I've learned a few things in this post... So now, to use Benjamin words: Please do me a favour and let's move on :) Baba Baba -- http://mail.python.org/mailman/listinfo/python-list
Re: accessing a text file
On 8 sep, 12:46, Paul Rubin no.em...@nospam.invalid wrote: Baba raoul...@gmail.com writes: It is just unfriendly to tell someone to go and look it up by themselves. Someone seeing too many unthoughtful questions from you might tell you to look it up yourself, in the hopes of getting you to change your questioning style, so that your future questions will be more thoughtful and worth answering. But according to you that would be unfriendly. Another thing they could do is say nothing, but quietly configure their news-reading software to ignore your questions completely. Then none of your future questions would have any hope of being answered. Would that be less unfriendly, or more unfriendly? Hi Paul I would support option 1 but phrased more thoughtfully than Benjamin did (that way no feelings will be hurt): Dear xyz, Your question can easily be researched online. We suggest you give it a try and to look it up yourself. This will be beneficial both to you and to us. We do encourage to ask questions only when they have been researched first. We care about the quality of posts but we also understand that as a beginner one can tend to look for an easy or quick way to find answers. So in the meantime here's something to get you started: link But where do you draw the line? Can we not just let people ask questions regardless? And let those answer who want to and those who don't just ignore the question? That seems so much easier to me. -- http://mail.python.org/mailman/listinfo/python-list
Re: accessing a text file
On 8 sep, 14:39, Paul Rubin no.em...@nospam.invalid wrote: Baba raoul...@gmail.com writes: But where do you draw the line? Can we not just let people ask questions regardless? And let those answer who want to and those who don't just ignore the question? That seems so much easier to me. The first few times, it's easy to ignore the questions. After a few more times, it becomes easier to ignore the person asking the questions, and not even look at the questions. The answer to many of your questions also is not research it online, but rather, figure it out with your own creativity. That's what being a programmer is about--figuring out solutions that don't already exist elsewhere. Hi Paul If i look where i was 4 weeks ago and the progress i made in learning Python i am quite delighted. This forum has helped me and i appreciate it. I don't think i will ever tell a beginner to do me a favour and to look things up by himself nor will i use the RTFM line (refering to Bruno's post), i'd just be nice and helpful as everyone here is. Didn't realise ego's were that big but so is mine i suppose... kind regards Baba -- http://mail.python.org/mailman/listinfo/python-list
Re: accessing a text file
On 7 sep, 02:18, Ben Finney ben+pyt...@benfinney.id.au wrote: Ben Finney ben+pyt...@benfinney.id.au writes: We value respect for people here, and that's what you've been shown consistently. But respect for opinions, or for delicacy about learning, is not welcome here. Sloppy wording, I apologise. This should say “… is not respect for a person”. In other words, we treat people as adults by default. I hope you'll continue to participate in that spirit. This is the main thrust of the message. -- \ “What if the Hokey Pokey IS what it's all about?” —anonymous | `\ | _o__) | Ben Finney Yes Master :) -- http://mail.python.org/mailman/listinfo/python-list
Re: accessing a text file
On 7 sep, 13:39, Baba raoul...@gmail.com wrote: On 7 sep, 02:18, Ben Finney ben+pyt...@benfinney.id.au wrote: Ben Finney ben+pyt...@benfinney.id.au writes: We value respect for people here, and that's what you've been shown consistently. But respect for opinions, or for delicacy about learning, is not welcome here. Sloppy wording, I apologise. This should say “… is not respect for a person”. In other words, we treat people as adults by default. I hope you'll continue to participate in that spirit. This is the main thrust of the message. -- \ “What if the Hokey Pokey IS what it's all about?” —anonymous | `\ | _o__) | Ben Finney Yes Master :) Sloppy wording, I apologise. This should say: If you find the question you're reading too easy then just don't answer. Noone is the owner of a democratic forum where freedom to ask the question one likes is paramount (as long of course as it is related to the group)...so let me repeat that, to say Please do us a favour and at least try to figure things out on your own is in my view inappropriate. To me it sounds Do me a favur and get lost. Can you not understand that? I accept that it might not have been meant that way but see, misunderstandings happen easily so a more subtle approach is a wothwhile effort. My point: i always encourage people to get down from their ivory towers and to connect to the people...yes they will sometimes be lazy but they are genuine and very respectful (unlike what you think)... no offence now ok, it's not all that serious...open your mind, let lose all that righteousness and let's enjoy life :) Baba -- http://mail.python.org/mailman/listinfo/python-list
mutate dictionary or list
Hi I am working on an exercise which requires me to write a funtion that will check if a given word can be found in a given dictionary (the hand). def is_valid_word(word, hand, word_list): Returns True if word is in the word_list and is entirely composed of letters in the hand. Otherwise, returns False. Does not mutate hand or word_list. I don't understand this part: Does not mutate hand or word_list I tried to google python mutate list input but to no avail It would be great if someone could give me a brief explanantion of the mutation concept. I know that a ditionary is unordered. How Can i however avoid 'acidental' mutation? Thanks Baba -- http://mail.python.org/mailman/listinfo/python-list
Re: accessing a text file
On 7 sep, 16:50, Grant Edwards inva...@invalid.invalid wrote: On 2010-09-07, Baba raoul...@gmail.com wrote: Sloppy wording, I apologise. This should say: If you find the question you're reading too easy then just don't answer. Noone is the owner of a democratic forum where freedom to ask the question one likes is paramount (as long of course as it is related to the group)...so let me repeat that, to say Please do us a favour and at least try to figure things out on your own is in my view inappropriate. You need to read this: http://www.catb.org/esr/faqs/smart-questions.html To me it sounds Do me a favur and get lost. No, it means Do yourself a favor, learn how to do things yourself. Remember: you're then one asking people to give you something for free. It's not up to them to conform to your expectations, rather you need to conform to theirs. Otherwise, they'll just ignore you. -- Grant Edwards grant.b.edwards Yow! FOOLED you! Absorb at EGO SHATTERING impulse gmail.com rays, polyester poltroon!! Please do us a favour sounds condescending to me at least but maybe we Europeans are a bit touchy... However the following Wiki excerpt seems to go in my direction: When someone makes a mistake -- whether it's a spelling error or a spelling flame, a stupid question or an unnecessarily long answer -- be kind about it. If it's a minor error, you may not need to say anything. Even if you feel strongly about it, think twice before reacting. Having good manners yourself doesn't give you license to correct everyone else. If you do decide to inform someone of a mistake, point it out politely, and preferably by private email rather than in public. Give people the benefit of the doubt; assume they just don't know any better. And never be arrogant or self-righteous about it. http://en.wikipedia.org/wiki/Netiquette Baba -- http://mail.python.org/mailman/listinfo/python-list
compare dictionaries
level: beginner word= 'even' dict2 = {'i': 1, 'n': 1, 'e': 1, 'l': 2, 'v': 2} i want to know if word is entirely composed of letters in dict2 my approach: step 1 : convert word to dictionary(dict1) step2: for k in dict1.keys(): if k in dict2: if dict1[k] != dict2[k]: return False return True return False return True by adding a print statement i can see that this simply ends too early e.g. as soon as the first IF condition is met the loop exits i think this is easy but google and python doc didn't return any good hints so i'm trying here. Thanks Baba -- http://mail.python.org/mailman/listinfo/python-list
Re: compare dictionaries
On 7 sep, 22:08, Gary Herron gher...@digipen.edu wrote: On 09/07/2010 12:46 PM, Baba wrote: word= 'even' dict2 = {'i': 1, 'n': 1, 'e': 1, 'l': 2, 'v': 2} Just go through each letter of word checking for its existence in dict2. Return False if one misses, and True if you get through the whole word: def ...(): for c in word: if c not in dict2: return False #if any character is not in dict return True # otherwise If you know of generator expressions, and remember that True and False are 1 and 0 respectively, then this works def ...(): return sum(c in dict2 for c in word) == len(word) Gary Herron -- Gary Herron, PhD. Department of Computer Science DigiPen Institute of Technology (425) 895-4418 ok but how do we address the fact that letter e needs to have the value 2 in the dictionary if it was to be True? in my example this condition is not met so the check would return False. Word is not entirely composed of letters in dict2, one of the letter is not in dict2 i.e. the 2nd e So finding a matching key seems to be the easy part, checking if the number of ocurrences of letter in 'word' == letter.value seems to be the tricky part -- http://mail.python.org/mailman/listinfo/python-list
Re: compare dictionaries
On 7 sep, 22:37, MRAB pyt...@mrabarnett.plus.com wrote: On 07/09/2010 21:06, Paul Rubin wrote: Babaraoul...@gmail.com writes: word= 'even' dict2 = {'i': 1, 'n': 1, 'e': 1, 'l': 2, 'v': 2} i want to know if word is entirely composed of letters in dict2 set(word)= set(dict2.keys()) Do the numbers in dict2 represent the maximum number of times that the letter can be used? If yes, then build a similar dict for the word with the number of times that each letter occurs in the word and then check for every pair in the dict whether the key (ie, letter) occurs in dict2 and that the value (number of occurrences) isn't too many. Hi MRAB Thanks for the hint. In my case i need to do the opposite: the number of times that each letter ocurs in the word needs to be smaller or equal to the number of times it apears in dict2. That way i am guaranteed that word is entirely made up of elements of dict2. Your hint pointed me in the right direction. for k in word.keys(): if k not in hand: return False elif k in hand: if word[k] hand[k]: return False return True Baba -- http://mail.python.org/mailman/listinfo/python-list
Re: accessing a text file
On 6 sep, 00:01, Benjamin Kaplan benjamin.kap...@case.edu wrote: On Sun, Sep 5, 2010 at 5:47 PM, Baba raoul...@gmail.com wrote: level: beginner how can i access the contents of a text file in Python? i would like to compare a string (word) with the content of a text file (word_list). i want to see if word is in word_list. let's assume the TXT file is stored in the same directory as the PY file. def is_valid_word(word, word_list) thanks Baba -- http://mail.python.org/mailman/listinfo/python-list Please do us a favor and at least try to figure things out on your own, rather than coming here every time you have a question. The very first result when you try searching python read text file is the section in the Python tutorial that explains how to do this. http://docs.python.org/tutorial/inputoutput.html#reading-and-writing-... Hi Benjamin I did find that page prior to posting the question but i still wanted to have a second opinion to complement that info so as to make things easier The first line of my post clearly states that i am a beginner. It's nice to provide links which can help answer the question but please be so polite and keep personal comments for yourself. To all other respondants: thank you for your kind instructions and directions. Thanks Baba -- http://mail.python.org/mailman/listinfo/python-list
Re: accessing a text file
On 6 sep, 00:04, Seth Rees s...@sthrs.me wrote: On 09/05/10 16:47, Baba wrote: level: beginner how can i access the contents of a text file in Python? i would like to compare a string (word) with the content of a text file (word_list). i want to see if word is in word_list. let's assume the TXT file is stored in the same directory as the PY file. def is_valid_word(word, word_list) thanks Baba f = open('text.txt') data = f.read() # You may want to convert it to a list data = data.split() # Returns true if word is in data, false otherwise word in data Thanks Seth! -- http://mail.python.org/mailman/listinfo/python-list
Re: accessing a text file
On 6 sep, 16:58, Thomas Jollans tho...@jollybox.de wrote: On Monday 06 September 2010, it occurred to Baba to exclaim: On 6 sep, 00:01, Benjamin Kaplan benjamin.kap...@case.edu wrote: On Sun, Sep 5, 2010 at 5:47 PM, Baba raoul...@gmail.com wrote: level: beginner how can i access the contents of a text file in Python? i would like to compare a string (word) with the content of a text file (word_list). i want to see if word is in word_list. let's assume the TXT file is stored in the same directory as the PY file. def is_valid_word(word, word_list) thanks Baba -- http://mail.python.org/mailman/listinfo/python-list Please do us a favor and at least try to figure things out on your own, rather than coming here every time you have a question. The very first result when you try searching python read text file is the section in the Python tutorial that explains how to do this. http://docs.python.org/tutorial/inputoutput.html#reading-and-writing-... Hi Benjamin I did find that page prior to posting the question but i still wanted to have a second opinion to complement that info so as to make things easier The first line of my post clearly states that i am a beginner. It's nice to provide links which can help answer the question but please be so polite and keep personal comments for yourself. That is of course perfectly legitimate. It would however have been polite to state that in the question. Show us that you're doing your homework, and not just using the list as a cheap path to having to think less yourself. Phrasing your post as I would like to compare a ... I found the open() function here: [link]. Is this what I should use of is there any other/better way? makes a completely different impression. Also, keeping personal comments to one's self is just not how it works. On a list like this especially, answers along the lines of That's the way to do what you were asking for, but are you sure the question went into the right direction? Have you thought of [...]? can often be very helpful. To all other respondants: thank you for your kind instructions and directions. Thanks Thomas. Look up some of my questions this group and read through them and come back to tell me if a) i use this forum to learn without making any efforts myself or b) i use this forum to get started using the expertise of more knowledgeable programmers while at the same time particiapting. Anyway having this discussion is beside the point. Any Expert out there who thinks we beginners are some dumb idiots who are too stupid to think for themselves and are lucky to have a bunch of geniuses like you to help, get lost or make yourself a cup of tea but please give me a break from teaching me lessons... There's lots of nice people out there who are being awsemome by dedicating a bit of their time to some of our easy questions and it is them that i wish to send a BIG thanks! Much appreciated. I have made some good progress since starting to learn Python and this group has been great help! tnx Raoul -- http://mail.python.org/mailman/listinfo/python-list
Re: accessing a text file
On 6 sep, 18:14, geremy condra debat...@gmail.com wrote: On Mon, Sep 6, 2010 at 8:53 AM, Baba raoul...@gmail.com wrote: On 6 sep, 16:58, Thomas Jollans tho...@jollybox.de wrote: On Monday 06 September 2010, it occurred to Baba to exclaim: On 6 sep, 00:01, Benjamin Kaplan benjamin.kap...@case.edu wrote: On Sun, Sep 5, 2010 at 5:47 PM, Baba raoul...@gmail.com wrote: level: beginner how can i access the contents of a text file in Python? i would like to compare a string (word) with the content of a text file (word_list). i want to see if word is in word_list. let's assume the TXT file is stored in the same directory as the PY file. def is_valid_word(word, word_list) thanks Baba -- http://mail.python.org/mailman/listinfo/python-list Please do us a favor and at least try to figure things out on your own, rather than coming here every time you have a question. The very first result when you try searching python read text file is the section in the Python tutorial that explains how to do this. http://docs.python.org/tutorial/inputoutput.html#reading-and-writing-... Hi Benjamin I did find that page prior to posting the question but i still wanted to have a second opinion to complement that info so as to make things easier The first line of my post clearly states that i am a beginner. It's nice to provide links which can help answer the question but please be so polite and keep personal comments for yourself. That is of course perfectly legitimate. It would however have been polite to state that in the question. Show us that you're doing your homework, and not just using the list as a cheap path to having to think less yourself. Phrasing your post as I would like to compare a ... I found the open() function here: [link]. Is this what I should use of is there any other/better way? makes a completely different impression. Also, keeping personal comments to one's self is just not how it works. On a list like this especially, answers along the lines of That's the way to do what you were asking for, but are you sure the question went into the right direction? Have you thought of [...]? can often be very helpful. To all other respondants: thank you for your kind instructions and directions. Thanks Thomas. Look up some of my questions this group and read through them and come back to tell me if a) i use this forum to learn without making any efforts myself Just a quick point- when you ask someone for help, it's considered impolite to tell them what to do. I'd also point out that you gave no indication that you'd worked on this at all before posting it. In that regard, Thomas's concern seems completely justified to me. or b) i use this forum to get started using the expertise of more knowledgeable programmers while at the same time particiapting. Again, Thomas's concern seems justified to me. Things would probably go more smoothly if you gave a better indication of what you had done so far on the problem in the future. Anyway having this discussion is beside the point. Any Expert out there who thinks we beginners are some dumb idiots who are too stupid to think for themselves and are lucky to have a bunch of geniuses like you to help, get lost or make yourself a cup of tea but please give me a break from teaching me lessons... I don't think all beginners are idiots, or even most of them- but this isn't the right attitude to be taking. Both Thomas and myself thought that this was inappropriate enough to mention it, and if two people spoke up you can bet a lot more were thinking it quietly. My suggestion would be to moderate your approach and demonstrate what you've done so far (if only to increase the signal-to-noise ratio as your problems become more challenging) when posting. I'd also refrain from telling people to get lost; it doesn't make people happy to help you, you know? Geremy Condra Thanks Jeremy, i will take your advice on board! Noone likes to be taught lessons i think so it is only normal that i reacted. If i had received a friendly response from Benjamin (as opposed to Please do us a favor and at least try to figure things out on your own) making me aware of the etiquette that my post should also show that i have researched my question somehow and if his tone would have been mannered then we would not be having this discussion now. Ok now i need to go back to actual Pythoon learning, i'm getting distracted. Kind regards, Baba -- http://mail.python.org/mailman/listinfo/python-list
accessing a text file
level: beginner how can i access the contents of a text file in Python? i would like to compare a string (word) with the content of a text file (word_list). i want to see if word is in word_list. let's assume the TXT file is stored in the same directory as the PY file. def is_valid_word(word, word_list) thanks Baba -- http://mail.python.org/mailman/listinfo/python-list
Re: bisection method: Simulating a retirement fund
On Sep 2, 11:10 pm, MRAB pyt...@mrabarnett.plus.com wrote: Why are you saving 'fund' in SavingsRecord if you're returning just the last and discarding others? Basically you're returning the final value of fund. Hi MRAB ok i agree that this is not be ideal. I should shorten this to ONLY return SavingsRecord[-1] When performing this type of 'search' make sure that the interval (high - low) reduces at every step. (integer division) and if the 'if' condition happens to be false then the value of 'low' won't change for the next iteration, leading to an infinite loop. If you look at the output you will see that the interval DOES seem to reduce at each interval as expenses and fundsize reduce gradually. The computation does not lead to an infinite loop. tnx Baba -- http://mail.python.org/mailman/listinfo/python-list
bisection method: Simulating a retirement fund
level: beginner exercise source: http://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-00-introduction-to-computer-science-and-programming-fall-2008/assignments/pset4.pdf Problem 4 Can my code be optimised? I think my approach is correct but i am hesitant about the initial max value. def nestEgVariable(salary, save, preRetireGrowthRates): SavingsRecord = [] fund = 0 depositPerYear = salary * save * 0.01 for i in preRetireGrowthRates: fund = fund * (1 + 0.01 * i) + depositPerYear SavingsRecord += [fund,] startingPot = SavingsRecord[-1] return startingPot def expenseCalculator(postRetireGrowthRates,fundsize,epsilon,yearsOfretirement ): low = 0 high = fundsize guess = (low + high) /2 while abs(guess * yearsOfretirement - fundsize) epsilon: if guess * yearsOfretirement fundsize : high = guess else: low = guess guess = (low + high) /2 return guess def findMaxExpenses(salary,save,preRetireGrowthRates, postRetireGrowthRates,epsilon): yearsOfretirement = len(postRetireGrowthRates) fundsize = nestEgVariable(salary, save, preRetireGrowthRates) for growthRate in postRetireGrowthRates: expenses = expenseCalculator(postRetireGrowthRates, fundsize ,epsilon,yearsOfretirement ) fundsize = (fundsize * (1 + 0.01 * growthRate)) - expenses print 'fundsize', fundsize print 'expenses', expenses yearsOfretirement -=1 return fundsize findMaxExpenses(1,10,[3, 4, 5, 0, 3],[10, 5, 0, 5, 1],0.01) thanks Baba -- http://mail.python.org/mailman/listinfo/python-list
Re: Fibonacci: returning a selection of the series
On Aug 29, 7:18 pm, Alain Ketterlin al...@dpt-info.u-strasbg.fr wrote: In general, if you have a program that produces something just to remove/ignore it five lines later, you have a problem. In your case: 1) are you sure you need to append to list(*) at every iteration? When do you *really* need to? And... 2) your loop runs up to n (the index of the fib number), but you want to stop on some fib number value (not index). So, why not pass start and end to i_fib, and use them where appropriate? Hi Alain Thank you for your (pragmatic) suggestions! Based on your input i was able to considerably optimise my approach: def fib_range(start, end): fib_1 = 0 fib_2 = 1 range = [] while fib_2 end: fib_1, fib_2 = fib_2, fib_1 + fib_2 if fib_2 = start and fib_2 = end: range.append(fib_2) return range print fib_range(4,76) Thanks Baba -- http://mail.python.org/mailman/listinfo/python-list
Re: Fibonacci: How to think recursively
On Aug 29, 3:25 am, Steven D'Aprano st...@remove-this- cybersource.com.au wrote: Mathematically, there is nothing wrong with overlapping recursion. It will work, and Python can handle it easily. Based on the advice by Steven and Mel i tried my initial 'guess' and it does seem to work fine. When looking at it using pencil and paper i thought well, each recursive call will call 2 new ones and if n is large i will have a huge overlap, so it probably is the wrong approach. However it turns out to be fine in principle. It can be handled, as Steven pointed out. But in practical terms, it can lead to great inefficiency. In this example, it should be avoided because it is slow. Very slow. To calculate the nth Fibonacci number using naive recursion requires *many* calls: You can make it even more efficient by giving fib() a long-term cache, so that each call to fib(5) requires one cache lookup rather than six (or fifteen) recursive calls. Other than the first time, obviously. This is called memoisation, but again I digress. I looked memoisation up and decided that for now i will not go near it. First i will try to build up some bacic skills but thank you very much for the hint. Memoisation will certainly be on the list of future exercises. However, the idea that memoisation is needed to make the computation more efficient confirms my initial feeling that a 'simple' recursive approach is somewhat not ideal. So here's my code. It does still cause me one headache. If i use f(0)=0 and f(1)=1 as base cases the result will be 144. I was expecting the result to be the next value in the series (233)... If i use f(1)=1 and f(2)=2 as base cases them i get my expected result. I assume this has to do with our understanding/defining the start of the Fibonacci series? def r_fib(n): if n == 1: return 1 elif n == 2: return 2 else: return r_fib(n-2) + r_fib(n-1) print r_fib(12) Thanks Baba -- http://mail.python.org/mailman/listinfo/python-list
Fibonacci: returning a selection of the series
level: beginner i would like to return a selection of the Fibonacci series. example: start = 5 ; end = 55 the function should then return [5, 8, 13, 21, 34, 55] it seems that this is best resolved using an iterative approach to generate the series. In another post (http://groups.google.ie/group/ comp.lang.python/browse_thread/thread/aa85ac893fd89c4a/ d3803a93baf1bdd0#d3803a93baf1bdd0) i looked at the recursive approach which seems best to compute the nth number but it seems to me that the recursive code is not suited for generating the actual list. my questios: - would you agree that recursive is not ideal for generating a list? (in this particular case and in general) - can my code below be optimised? - how to deal with 'start' and 'end' values that are not in the list e.g. 4,76 ? def i_fib(n): a = 0 b = 1 list = [] counter = 0 while counter n: a, b = b, a+b counter += 1 list = list + [b,] return list def fib_range(start,end): list = i_fib(12) if start in list and end in list: start = list.index(start) end = list.index(end) print list[start:end+1] else: print 'not in list' fib_range(5,55) thanks Baba -- http://mail.python.org/mailman/listinfo/python-list
Re: Fibonacci: How to think recursively
Thanks to All for your kind help! Baba -- http://mail.python.org/mailman/listinfo/python-list
Fibonacci: How to think recursively
Level: beginner I would like to know how to approach the following Fibonacci problem: How may rabbits do i have after n months? I'm not looking for the code as i could Google that very easily. I'm looking for a hint to put me on the right track to solve this myself without looking it up. my brainstorming so far brought me to a stand still as i can't seem to imagine a recursive way to code this: my attempted rough code: def fibonacci(n): # base case: result = fibonacci (n-1) + fibonacci (n-2) this will end up in a mess as it will create overlapping recursions OR def fibonacci(n): # base case: fibonacci(n+2) - fibonacci(n+1) - n = 0 this too would create overlapping recursions How to go about this? Thanks Baba -- http://mail.python.org/mailman/listinfo/python-list
palindrome iteration
level: beginner the following code looks ok to me but it doesn't work. I would like some hints as to where my reasoning / thought goes wrong def i_palindrome(pal): while len(pal)1: if pal[0] == pal[-1]: pal=pal[1:-1] return True print i_palindrome('annab') my reasoning: - i check the length of the string: if 1 continue - i check first and last char: if they are equal continue - create a new, shorter string starting at index 1 and ending at second last index (up to but not including index-1 -restart the while loop as long as length of string is 1 - exiting this loop means all compared chars were identical hence it is a palindrome and i return True tnx Baba -- http://mail.python.org/mailman/listinfo/python-list
comparing tuples
level: beginners I was trying to write simple code that compares 2 tuples and returns any element in the second tuple that is not in the first tuple. def tuples(t1, t2): result = [] for b in t2: for a in t1: if b == a: break else: result=result+[b,] return result print tuples([0,5,6], [0,5,6,3,7]) the code works but i was surprised by the following: my understanding was that an ELSE clause is part of an IF statement. Therefore it comes at the same indentation as the IF statement. However the above example only works if the ELSE clause is positioned under the second FOR loop. As if it was an ELSE clause without an IF statement!? Why/How does this work? tnx Baba -- http://mail.python.org/mailman/listinfo/python-list
Re: comparing tuples
On Aug 22, 7:12 pm, Tim Chase python.l...@tim.thechases.com wrote: On 08/22/10 12:50, Baba wrote: level: beginners I was trying to write simple code that compares 2 tuples and returns any element in the second tuple that is not in the first tuple. def tuples(t1, t2): result = [] for b in t2: for a in t1: if b == a: break else: result=result+[b,] return result print tuples([0,5,6], [0,5,6,3,7]) the code works but i was surprised by the following: my understanding was that an ELSE clause is part of an IF statement. Therefore it comes at the same indentation as the IF statement. The ELSE clause can be used either with an IF (as you know) or with a FOR loop, which is interpreted as if this loop reached the end naturally instead of exiting via a BREAK statement, execute this block of code. If you reach the end of t1 without having found a value (and then issuing a break), then the current value of t2 (b) should be appended to the result. That said, unless order matters, I'd just use sets: def tuples(t1, t2): return list(set(t2)-set(t1)) which should have better performance characteristics for large inputs. -tkc Thanks Tim! -- http://mail.python.org/mailman/listinfo/python-list
Re: Iterative vs. Recursive coding
On Aug 21, 7:37 am, John Nagle na...@animats.com wrote: On 8/20/2010 1:17 PM, John Bokma wrote: I think you mean tail recursion optimization / elimination. Python does tail recursion: Not very well. def cnt(n) : if n 0 : cnt(n-1) Hi John I'm intrigued by this example. Is there something missing in the code? When i run it i get: function cnt at 0x02B2FE70 I suppose it is meant to print a sequence of numbers from n down to zero? re tail recursion, on wiki i found: With tail recursion, there is no need to remember the place we are calling from—instead, we can leave the stack alone, and the newly called function will return its result directly to the original caller. Converting a call to a branch or jump in such a case is called a tail call optimization. not sure i understand that... is this bit of theory applicable to your cnt function above? tnx Baba -- http://mail.python.org/mailman/listinfo/python-list
Re: Iterative vs. Recursive coding
Hi Martin Thanks for your post. This basic but fundamental computation is a great example when trying to understand the concept of recursion for the first time. Also thanks to John for the stackoverflow link where i found a very good summarised definition completing some of the posts left here. For future readers of this post who want to learn to programm (just like myself) let me re-state the basics i have learned now: - a procedure is said to be recursive when it contains a statement that calls itself - there must be a condition where the recursion has to stop otherwise the routine will continue to call itself infinitely. This is called the Base Case - every time the procedure calls itself the memory gradually fills up with the copies until the whole thing winds down again as the return statements start being executed. - the above point means that a recursive approach is expensive on resources so in the practical world it should be avoided. (Thanks John for giving me a real life example where recursion is recommended) For the purposes of learning programming i think it's a must to understand Recursion so thanks all for your help! Ok so now i hope you all agree that my code is also correct :) def r_countSubStringMatch(target,key): counter=0 if len(key)len(target): fsi=target.find(key) if fsi!=-1: # BASE CASE counter=1+r_countSubStringMatch(target[fsi+1:],key) return counter else: return counter elif len(key)==len(target): if key==target: counter+=1 return counter else: return counter return counter print r_countSubStringMatch(atgacatgcacaagtatgcat,atgc) tnx Baba -- http://mail.python.org/mailman/listinfo/python-list
Re: Iterative vs. Recursive coding
On Aug 19, 11:00 pm, Martin Gregorie mar...@address-in-sig.invalid wrote: By way of a hint, here are two versions of the classic example of recursion: calculating factorials. Recursion can be quite a trick to get your mind round at first, so compare the two and follow through their operation step by step... Hi Martin Thanks for your post. This basic but fundamental computation (calculating factorials) is a great example when trying to understand the concept of recursion for the first time. Also thanks to John for the stackoverflow link where i found a very good summarised definition completing some of the posts left here. For future readers of this post who want to learn to programm (just like myself) let me re-state the basics i have learned now: - a procedure is said to be recursive when it contains a statement that calls itself - there must be a condition where the recursion has to stop otherwise the routine will continue to call itself infinitely. This is called the Base Case - every time the procedure calls itself the memory gradually fills up with the copies until the whole thing winds down again as the return statements start being executed. - the above point means that a recursive approach is expensive on resources so in the practical world it should be avoided. (Thanks John for giving me a real life example where recursion is recommended) For the purposes of learning programming i think it's a must to understand Recursion so thanks all for your help! Ok so now i hope you all agree that my code is also correct :) def r_countSubStringMatch(target,key): counter=0 if len(key)len(target): fsi=target.find(key) if fsi!=-1: # BASE CASE counter=1+r_countSubStringMatch(target[fsi+1:],key) return counter else: return counter elif len(key)==len(target): if key==target: counter+=1 return counter else: return counter return counter print r_countSubStringMatch(atgacatgcacaagtatgcat,atgc) tnx Baba -- http://mail.python.org/mailman/listinfo/python-list
Iterative vs. Recursive coding
Level: Beginner exercise source: http://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-00-introduction-to-computer-science-and-programming-fall-2008/assignments/pset3.pdf I am looking at the first problem in the above assignment. The assignemnt deals, amongst others, with the ideas of iterative vs. recursive coding approaches and i was wondering what are the advantages of each and how to best chose between both options? I had a go at the first part of the exercise and it seems that i can handle it. However i think my Recursive version can be improved. By the way, is my code actually proper recursive code? part 1 iterative approach: from string import * def countSubStringMatch(target,key): counter=0 fsi=0 #fsi=find string index while fsilen(target): fsi=target.find(key,fsi) #print fsi if fsi!=-1: counter+=1 else: break fsi=fsi+1 print '%s is %d times in the target string' %(key,counter) countSubStringMatch(atgacatgcacaagtatgcat,zzz) part 2 recursive approach: def countSubStringMatchRecursive(target,key): counter=0 fsi=0 #fsi=find string index if len(key)==len(target): #base case if key==target: counter+=1 elif len(key)len(target): while fsilen(target): fsi=target.find(key,fsi) if fsi!=-1: counter+=1 else: break fsi=fsi+1 else: print 'key is longer than target...' print '%s is %d times in the target string' %(key,counter) countSubStringMatchRecursive(atgacatgcacaagtatgcat,atgacatgcacaagtatgcatatgc) tnx Baba -- http://mail.python.org/mailman/listinfo/python-list
Re: looping through possible combinations of McNuggets packs of 6, 9 and 20
Hi Chas Thanks for that and i agree on your last remark :) re the number of required consecutive passes required: The number of required consecutive passes is equal to the smallest number because after that you can get any amount of nuggets by just adding the smallest nugget pack to some other number. This is only true if gcd(a,b,c)=1. Thanks to all for the help in getting to the bottom of the exercise. I have truly enjoyed this and most importantly i have learned some new things. Hadn't really done any mathematics in a long time and only starting programming so this was good to get up to speed. kind regards to everyone! Baba -- http://mail.python.org/mailman/listinfo/python-list
Re: looping through possible combinations of McNuggets packs of 6, 9 and 20
On Aug 16, 6:28 pm, cbr...@cbrownsystems.com cbr...@cbrownsystems.com wrote: First, suppose d = gcd(x, y, z); then for some x', y', z' we have that x = d*x', y = d*y', z = d*z'; and so for any a, b, c: could you explain the notation? what is the difference btw x and x' ? what is x = d*x', y supposed to say? To go the other way, if d = 1, then there exists integers (not neccessarily positive) such that a*x + b*y + c*z = 1 what's the link with 6*a+9*b+20*c=n except the similarity? furthermore i came across this: For k = 3, efficient algorithms have been given by Greenberg and Davison ; if x1 x2 x3, these algorithms run in time bounded by a polynomial in log x3. Kannan gave a very complicated algorithm that runs in polynomial time in log xk if k is fixed, but is wildly exponential in k. However, Ram´ırez Alfons´ın proved that the general problem is NP-hard, under Turing reductions, by reducing from the integer knapsack problem. So it seems very likely that there is no simple formula for computing g(x1, x2, . . . , xk) for arbitrary k. source: http://arxiv.org/PS_cache/arxiv/pdf/0708/0708.3224v1.pdf i would be interested in the answer to problem 3: explain in English why the theorem is true @Giacomo: when you say that i have not read the text of the assignment i tend to disagree. Therefore could you point out what it is i overlooked that should help me prove my assumption for the generalisation? Enjoy the sausages btw :) tnx Baba -- http://mail.python.org/mailman/listinfo/python-list
Re: looping through possible combinations of McNuggets packs of 6, 9 and 20
Hi Chas, Roald, These are all complicated formula that i believe are not expected at this level. If you look at the source (see my first submission) you will see that this exercise is only the second in a series called Introduction to Programming. Therefore i am convinced that there is a much simpler solution. Now, i believe that the number of consecutive passes required to make this work is equal to the smallest number of pack sizes. So if we have packs of (9,12,21) the number of passes needed would be 9 and the theorem would read If it is possible to buy n,n+1,n+2,...n+8 nuggets it is possible to buy any number of nuggets = 9 given that they come in packs of 9,12,21 However i turn in circles because i don't seem to get any results for some random pack combinations like (9,12,21) or (10,20,30). The must always be a solution i'm thinking, be it the smallest pack - 1 Thoughts? tnx Raoul -- http://mail.python.org/mailman/listinfo/python-list
Re: looping through possible combinations of McNuggets packs of 6, 9 and 20
well i still believe that the key is the smallest sized pack and there's no need to go into higher mathematics to solve this problem. I think below code works within the limits of the exercise which states to look at a maximum range of 200 in order not to search forever. packages=[2,103,105] min_size=min(packages[0],packages[1],packages[2]) cbc=0 #cbc=can_buy counter for n_nuggets in range(1,200): if cbc=min_size: break can_buy=False for a in range (n_nuggets/packages[0]+1): for b in range (n_nuggets/packages[1]+1): for c in range (n_nuggets/packages[2]+1): #print trying for %d: %d %d %d % (n_nuggets,a,b,c) if packages[0]*a+packages[1]*b+packages[2]*c==n_nuggets: can_buy=True break if can_buy==True: cbc+=1 else: cbc=0 sol=n_nuggets print sol Baba -- http://mail.python.org/mailman/listinfo/python-list
Re: looping through possible combinations of McNuggets packs of 6, 9 and 20
Hi John, Thanks for your submission! I've improved a lot and everone's help so far has been thrilling amd is very good for my self-study motivation :) ok so i think i'm clear on how to approach this problem and on how to write basic but clean Python code to solve it. The next step is to generalise this code so that other pack quantities could be tested: generalize this idea to work with any size packages of McNuggets, not just 6, 9, and 20. For simplicity, however, we will assume that nuggets are provided in three different sized packages I thought this should be relatively straightforward and it does work if i test it for the values 6,920 but if i test for 2,3,4 i would expect the result to be 1 but it returns nothing def can_buy(n_nuggets,packages): for a in range (0,n_nuggets/6+1): for b in range (0,n_nuggets/9+1): for c in range (0,n_nuggets/20+1): #print trying for %d: %d %d %d % (n_nuggets,a,b,c) if packages[0]*a+packages[1]*b +packages[2]*c==n_nuggets: return True return False def diophantine_nuggets(x,y,z): cbc=0 #cbc=can_buy counter packages =[x,y,z] for n_nuggets in range(50): result=can_buy(n_nuggets,packages) if result: cbc+=1 else: cbc=0 if cbc==6: solution=n_nuggets-6 print Largest number of McNuggets that cannot be bought in exact quantity: %d %(solution) diophantine_nuggets(2,3,4) -- http://mail.python.org/mailman/listinfo/python-list
Re: looping through possible combinations of McNuggets packs of 6, 9 and 20
Hi John, Thanks for your submission! I've improved a lot and everone's help so far has been thrilling and is very good for my self-study motivation :) ok so i think i'm clear on how to approach this problem and on how to write basic but clean Python code to solve it. The next step is to generalise this code so that other pack quantities could be tested: generalize this idea to work with any size packages of McNuggets, not just 6, 9, and 20. For simplicity, however, we will assume that nuggets are provided in three different sized packages I thought this should be relatively straightforward and it does work if i test it for the values 6,920 but if i test for 2,3,4 i would expect the result to be 1 but it returns nothing def can_buy(n_nuggets,packages): for a in range (0,n_nuggets/6+1): for b in range (0,n_nuggets/9+1): for c in range (0,n_nuggets/20+1): #print trying for %d: %d %d %d % (n_nuggets,a,b,c) if packages[0]*a+packages[1]*b +packages[2]*c==n_nuggets: return True return False def diophantine_nuggets(x,y,z): cbc=0 #cbc=can_buy counter packages =[x,y,z] for n_nuggets in range(50): result=can_buy(n_nuggets,packages) if result: cbc+=1 else: cbc=0 if cbc==6: solution=n_nuggets-6 print Largest number of McNuggets that cannot be bought in exact quantity: %d %(solution) diophantine_nuggets(2,3,4) -- http://mail.python.org/mailman/listinfo/python-list
Re: looping through possible combinations of McNuggets packs of 6, 9 and 20
Hi All, @Emile tnx for spotting the mistake. Should have seen it myself. @John Ian i had a look around but couldn't find a general version of below theorem If it is possible to buy x, x+1,…, x+5 sets of McNuggets, for some x, then it is possible to buy any number of McNuggets = x, given that McNuggets come in 6, 9 and 20 packs. I must admit that i'm not keen on spending too much time on purely mathematical questions. It seems that this has to do with Frobenius Number? re range the exercise seems to suggest to limit it to 200 so feel free to enlighten me on this last part. In the meantime the almost complete code is: def can_buy(n_nuggets,packages): for a in range (0,n_nuggets/packages[0]+1): for b in range (0,n_nuggets/packages[1]+1): for c in range (0,n_nuggets/packages[2]+1): #print trying for %d: %d %d %d % (n_nuggets,a,b,c) if packages[0]*a+packages[1]*b +packages[2]*c==n_nuggets: return True return False def diophantine_nuggets(*packages): cbc=0 #cbc=can_buy counter #packages =[x,y,z] for n_nuggets in range(200): result=can_buy(n_nuggets,packages) if result: cbc+=1 else: cbc=0 if cbc==6: solution=n_nuggets-6 print Largest number of McNuggets that cannot be bought in exact quantity: %d %(solution) break diophantine_nuggets(2,3,4) -- http://mail.python.org/mailman/listinfo/python-list
Re: looping through possible combinations of McNuggets packs of 6, 9 and 20
Hi Mel, indeed i thought of generalising the theorem as follows: If it is possible to buy n, n+1,…, n+(x-1) sets of McNuggets, for some x, then it is possible to buy any number of McNuggets = x, given that McNuggets come in x, y and z packs. so with diophantine_nuggets(7,10,21) i would need 7 passes result:53 but with (10,20,30) and 10 passes i get no result so i'm not sure i'm on the right path... -- http://mail.python.org/mailman/listinfo/python-list
Re: looping through possible combinations of McNuggets packs of 6, 9 and 20
On Aug 13, 8:25 pm, Ian Kelly ian.g.ke...@gmail.com wrote: It's not. You're not just trying to find the sixth value that can be bought in exact quantity, but a sequence of six values that can all be bought in exact quantity. The integers [6, 9, 12, 15, 18, 20] are not sequential. Hi Ian, Thanks for stating the obvious. I obviously hadn't understood a fundamental part of the theorem which states that 6 SEQUENTIAL passes must be found! That's a good lesson learned and will help me in future exercises to make sure i understand the theory first. Thanks again! Ok so with your and News123's help (no offence to all others but i need to keep it simple at this stage)i was able to find the solution: 43 my code is probably not elegant but a huge step forward from where i started: def can_buy(n_nuggets): for a in range (0,n_nuggets): for b in range (0,n_nuggets): for c in range (0,n_nuggets): #print trying for %d: %d %d %d % (n_nuggets,a,b,c) if 6*a+9*b+20*c==n_nuggets: return [a,b,c] return [] for n_nuggets in range(50): result1 = can_buy(n_nuggets) result2 = can_buy(n_nuggets+1) result3 = can_buy(n_nuggets+2) result4 = can_buy(n_nuggets+3) result5 = can_buy(n_nuggets+4) result6 = can_buy(n_nuggets+5) if result1!=[] and result2!=[] and result3!=[] and result4!=[] and result5!=[] and result6!=[]: if (n_nuggets+5)-n_nuggets==5: print n_nuggets-1 break i suppose this can be tweaked to make it shorter? For instance i wonder if i can do the same with less variable to be defined? tnx Baba -- http://mail.python.org/mailman/listinfo/python-list
Re: looping through possible combinations of McNuggets packs of 6, 9 and 20
Hi News 123, Ok i'm getting closer. I am able to write code that will output values that can be bought in exact quantity (truelist) and values that cannot be bought in exact quantities. For a range up to 29 i get this: true [6, 9, 12, 15, 18, 20, 21, 24, 26, 27, 29] false [0, 1, 2, 3, 4, 5, 7, 8, 10, 11, 13, 14, 16, 17, 19, 22, 23, 25, 28] the sixth value that passes the test of having an exact solution is 20 so that would mean that the last number i got that cannot be bought in exact quantity is 19 that doesn't seem quite right, does it? def can_buy(n_nuggets): for a in range (0,n_nuggets): for b in range (0,n_nuggets): for c in range (0,n_nuggets): #print trying for %d: %d %d %d % (n_nuggets,a,b,c) if 6*a+9*b+20*c==n_nuggets: return True return False truelist=[] falselist=[] for n_nuggets in range(30): result = can_buy(n_nuggets) if result==True: truelist=truelist+[n_nuggets,] else: falselist=falselist+[n_nuggets,] print 'true',truelist print 'false',falselist tnx Baba -- http://mail.python.org/mailman/listinfo/python-list
Re: looping through possible combinations of McNuggets packs of 6, 9 and 20
Hi News 123, Ok i'm getting closer. I am able to write code that will output values that can be bought in exact quantity (truelist) and values that cannot be bought in exact quantities. For a range up to 29 i get this: true [6, 9, 12, 15, 18, 20, 21, 24, 26, 27, 29] false [0, 1, 2, 3, 4, 5, 7, 8, 10, 11, 13, 14, 16, 17, 19, 22, 23, 25, 28] the sixth value that passes the test of having an exact solution is 20 so that would mean that the last number i got that cannot be bought in exact quantity is 19 that doesn't seem quite right, does it? def can_buy(n_nuggets): for a in range (0,n_nuggets): for b in range (0,n_nuggets): for c in range (0,n_nuggets): #print trying for %d: %d %d %d % (n_nuggets,a,b,c) if 6*a+9*b+20*c==n_nuggets: return True return False truelist=[] falselist=[] for n_nuggets in range(30): result = can_buy(n_nuggets) if result==True: truelist=truelist+[n_nuggets,] else: falselist=falselist+[n_nuggets,] print 'true',truelist print 'false',falselist tnx Baba -- http://mail.python.org/mailman/listinfo/python-list
Re: looping through possible combinations of McNuggets packs of 6,9 and 20
Hi News123 Thank You for helping me out. Indeed i am not looking for the code but rather for hints that direct my reasoning as well as hints as to how to write basic programs like this. You have broken down the approach into 2 parts. I have tried to solve part 1 but i'm not quite there yet. Here's my code: def can_buy(n_nuggets): for a in range (1,n_nuggets): for b in range (1,n_nuggets): for c in range (1,n_nuggets): if 6*a+9*b+20*c==n_nuggets: #print a,b,c,'n_nuggets=',n_nuggets return True else: return False can_buy(55) as you can see i am trying to loop through all combinations of values bewtween 1 and n_nuggets and when the equation resolves it should return True, else it should return False. I was hoping that when i then call my function and ask it to test a value nothing happens. What is wrong? My syntax? My semantic? Both? tnx Baba -- http://mail.python.org/mailman/listinfo/python-list
looping through possible combinations of McNuggets packs of 6, 9 and 20
level: beginner exercise: given that packs of McNuggets can only be bought in 6, 9 or 20 packs, write an exhaustive search to find the largest number of McNuggets that cannot be bought in exact quantity. exercise source: http://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-00-introduction-to-computer-science-and-programming-fall-2008/assignments/pset2.pdf please help me write this code i believe it's something along the lines of this: c=0 sol=[] for n in range (0,10): for a in range (0,10): for b in range (0,10): for c in range (0,10): sol=6*a+9*b+20*c if sol!=n: c+=1 if c==6: print sol -- http://mail.python.org/mailman/listinfo/python-list
Ping and ARP on both Win and Linux in Python
Hi, this is my question: I want to know if several switch (about 50) in a big lan are up and then know their MAC addresses to do a list that contains host name, ip and mac. I know only the range of their IP addresses (the host name it's simply to know using socket.gethostn. The first idea it's to ping all ip, parse the response and then execute the command arp -a and parse the response. However this way depends on the operating system and the ping response depends too from the language. Another way it's to open the main page of the switch and parse the HTML code where i can find the MAC address. However this way depends on the particular brand's switch. I know (or better i think) that there is a third way: make ping and arp building the packets with socket and so on (but i dont have understand in what way do this). Any suggestion? (i've already search in google, found many sources but a lot of them don't works or don't do what im trying to do...) Regards, Mauretto. -- http://mail.python.org/mailman/listinfo/python-list