[Tutor] Help with if-elif-else structure
I've written a function that rolls (standard) dice. There are a few special cases though: Any sixes rolled are removed and 2*number of sixes new dice are rolled in their place. Initial roll is important to keep track of. I've solved it with the following function: from random import randint def roll_dice(count, sides=6): """Rolls specified number of dice, returns a tuple with the format (result, number of 1's rolled, number of 6's rolled).""" initial_mins = None initial_max = None result = 0 while count: dice = [randint(1, sides) for die in range(count)] if initial_mins == None: initial_mins = dice.count(1) if initial_max == None: initial_max = dice.count(sides) result += sum(result for result in dice if result != sides) count = 2 * dice.count(sides) # number to roll the next time through. return (result, initial_mins, initial_max) Now, when I test against a target number (this is from a Swedish RPG system, btw -- I just wanted to see if I could write it), several things can happen: If I roll two sixes (on the initial roll) and below the target number (in total), it's a failure. If I roll two sixes (on the initial roll) and above the target number (in total), it's a critical failure. If I roll two ones (on the initial roll) and above the target number (in total), it's a success. If I roll two ones (on the initial roll) and below the target number (in total), it's a critical success. If I roll below the target number (in total), it's a success. If I roll above the target number (in total), it's a failure. I've written a horrible-looking piece of code to solve this, but I'm sure there are better ways to structure it: #assuming target number 15 roll = (result, initial_mins, initial_max) if roll[0] > 15: if roll[1] >= 2: print("Success") elif roll[2] >= 2: print("Critical failure!") else: print("Failure.") elif roll[0] <= 15: if roll[1] >= 2: print("Critical success!") elif roll[2] >= 2: print("Failure") else: print("Success") This handles all the test cases I've come up with, but it feels very ugly. Is there a better way to do this? -- best regards, Robert S. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Confirmation if command worked
On 25/08/11 07:25, Christian Witts wrote: Once you call child.close() the exit and signal status will be stored in .exitstatus and .signalstatus, for a normal exit of the program .exitstatus will store the return code from SCP as per [1] [2] [3] and .signalstatus will be None. If SCP was terminated with a signal then .exitstatus will be None and .signalstatus will contain the signal value. Info found in the docs [4]. data = child.read() child.close() if child.exitstatus and child.exitstatus == 0: success = True else: success = False Won't that if statement always evaluate to false? If exitstatus is 0 the first part of the and will be false and so the entire and expression is false. If exitstatus is not 0 then the second part of the and will be false and again the and result will be false. Did you mean to use exitstatus for both tests? Or am I missing something subtle here? -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] understanding **kwargs syntax
Just a quick question, is it wrong to use the *args and **kwargs ( the latter in particular) when DEFINING a function? def fest(**kwargs): """ a function test """ keys = sorted(kwargs.keys()) print("You provided {0} keywords::\n".format(len(keys))) for kw in keys: print("{0} => {1}".format(kw, kwargs[kw])) Are there some good examples of when this would be a good idea to implement? --john ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Confirmation if command worked
On 2011/08/25 10:19 AM, Alan Gauld wrote: On 25/08/11 07:25, Christian Witts wrote: Once you call child.close() the exit and signal status will be stored in .exitstatus and .signalstatus, for a normal exit of the program .exitstatus will store the return code from SCP as per [1] [2] [3] and .signalstatus will be None. If SCP was terminated with a signal then .exitstatus will be None and .signalstatus will contain the signal value. Info found in the docs [4]. data = child.read() child.close() if child.exitstatus and child.exitstatus == 0: success = True else: success = False Won't that if statement always evaluate to false? If exitstatus is 0 the first part of the and will be false and so the entire and expression is false. If exitstatus is not 0 then the second part of the and will be false and again the and result will be false. Did you mean to use exitstatus for both tests? Or am I missing something subtle here? Good catch, it should be `if child.exitstatus != None and child.exitstatus == 0:` or removing the first part entirely. The zero-evaluating-as-False has bitten me before and for some reason I still on occasion forget it even though I use it often for data extracts. -- Christian Witts Python Developer // ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] help with a class
Thanks for the feedback. I wasn't aware about the assert usage not being intended for production code. On Wed, Aug 24, 2011 at 11:37 PM, Alan Gauld wrote: > On 24/08/11 21:03, Prasad, Ramit wrote: >> >> I was under the impression that asserts are more for testing > >> than for production code > > That's true. > >> def overide_options(self, options, run_id=None): >> >> if not isinstance(options, dict): >> raise TypeError("override options requires a dict") > > This is good if you want to keep the check in for production. > But using an assert here while testing then removing it from production > would be a valid use too. The typecheck is not required for the function to > work if you are confident of the data being passed in. assert checks the > data while you are gaining that confidence. > > So either approach is valid. > It all depends on how variable your input data is going to be. > > > -- > Alan G > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > > ___ > Tutor maillist - Tutor@python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -- Configuration `` Plone 2.5.3-final, CMF-1.6.4, Zope (Zope 2.9.7-final, python 2.4.4, linux2), Python 2.6 PIL 1.1.6 Mailman 2.1.9 Postfix 2.4.5 Procmail v3.22 2001/09/10 Basemap: 1.0 Matplotlib: 1.0.0 ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Help with if-elif-else structure
On 25/08/11 08:51, Robert Sjoblom wrote: If I roll two sixes (on the initial roll) and below the target number (in total), it's a failure. If I roll two sixes (on the initial roll) and above the target number (in total), it's a critical failure. If I roll two ones (on the initial roll) and above the target number (in total), it's a success. If I roll two ones (on the initial roll) and below the target number (in total), it's a critical success. If I roll below the target number (in total), it's a success. If I roll above the target number (in total), it's a failure. I've written a horrible-looking piece of code to solve this, but I'm sure there are better ways to structure it: #assuming target number 15 roll = (result, initial_mins, initial_max) I'd forget the tuple and just use the names, it is more readable that way... if roll[0]> 15: if roll[1]>= 2: print("Success") elif roll[2]>= 2: print("Critical failure!") if result > 15: if initial_mins >= 2:... elif initial_max >=2:... But otherwise it seems to reflect the rules as you've written them... -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] understanding **kwargs syntax
On 25/08/11 09:27, John wrote: Just a quick question, is it wrong to use the *args and **kwargs ( the latter in particular) when DEFINING a function? No, in fact it's essential if you don't know in advance what arguments are going to be passed to the function. This is very common if you are wrapping another function that itself takes variable arguments. def fest(**kwargs): """ a function test """ keys = sorted(kwargs.keys()) print("You provided {0} keywords::\n".format(len(keys))) for kw in keys: print("{0} => {1}".format(kw, kwargs[kw])) Are there some good examples of when this would be a good idea to implement? GUI frameworks like Tkinter often take variable numbers of configuration values. If you want to wrap that with a function of your own you can do something like(pseudocode): def myfunc(**kwargs): if some interesting arg exists do something with it return wrappedFunc(kwargs) There are plenty other cases, try grepping the standard library code for lines with def and **kwargs for some examples... -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Help with if-elif-else structure
>> #assuming target number 15 >> roll = (result, initial_mins, initial_max) > I'd forget the tuple and just use the names, > it is more readable that way... >if result > 15: >if initial_mins >= 2:... >elif initial_max >=2:... > But otherwise it seems to reflect the rules as you've written them... Oh, that's a good idea, that's definitely more readable. But the issue isn't if it reflects the rules (although it's good that it does!), but whether there's a better way to structure the if-elif-else part, or even if there's a better way to handle it. I'll probably send it through a function, something like (pseudocode): def check_result(diceroll_result, initial_mins, initial_max): check for success/failure and so on return result But even so, is my if-elif-else structure the best way to go about it? -- best regards, Robert S. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Confirmation if command worked
On 25-Aug-11 01:37, Christian Witts wrote: Good catch, it should be `if child.exitstatus != None and child.exitstatus == 0:` It's better form to say if child.exitstatus is not None instead of comparing for equality to None with the != operator. -- Steve Willoughby / st...@alchemy.com "A ship in harbor is safe, but that is not what ships are built for." PGP Fingerprint 4615 3CCE 0F29 AE6C 8FF4 CA01 73FE 997A 765D 696C ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] Raw input query (?)
I copied and ran the following script: multiplier = 12 for j in range(1,13): print "%d x %d = %d" %(j, multiplier, j*multiplier) That ran perfectly and gave me the 12 times table. I then decided that it would be fun to branch out and make teh script "universal", so I wrote and ran: print "Which times table do you want?" multiplier = raw_input () for j in range(1,13): print "%d x %d = %d" %(j, multiplier, j*multiplier) The j in range section of code is identical, but I now get: lisi@Tux:~/Python$ python multiplier.py Which times table do you want? 4 Traceback (most recent call last): File "multiplier.py", line 8, in print "%d x %d = %d" %(j, multiplier, j*multiplier) TypeError: int argument required lisi@Tux:~/Python$ What extra should I have done because the variable value came from the keyboard, and why is it different from the first example? Lisi ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Raw input query (?)
On 08/25/2011 05:46 AM, Lisi wrote: I copied and ran the following script: multiplier = 12 for j in range(1,13): print "%d x %d = %d" %(j, multiplier, j*multiplier) That ran perfectly and gave me the 12 times table. I then decided that it would be fun to branch out and make teh script "universal", so I wrote and ran: print "Which times table do you want?" multiplier = raw_input () for j in range(1,13): print "%d x %d = %d" %(j, multiplier, j*multiplier) The j in range section of code is identical, but I now get: lisi@Tux:~/Python$ python multiplier.py Which times table do you want? 4 Traceback (most recent call last): File "multiplier.py", line 8, in print "%d x %d = %d" %(j, multiplier, j*multiplier) TypeError: int argument required lisi@Tux:~/Python$ What extra should I have done because the variable value came from the keyboard, and why is it different from the first example? Lisi If you get an error with that specific a wording, use the system to tell you what's wrong. Add a print statement immediately before the offending line, and print thorough information about each of the variables used. In this case, the obvious candidate is multiplier. So print repr(multiplier) and type(multiplier) and see if that shows you anything different from what the error message asked for, or different from the repr() and type() of your first script. Now that you know what the type of variable multiplier is, can you guess how to convert it to the one you need? DaveA -- DaveA ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Confirmation if command worked
Christian Witts wrote: if child.exitstatus and child.exitstatus == 0: success = True else: success = False There is never any need to write Python code that looks like that. (Or in any other language I'm familiar with either.) Anything of the form: if some_condition: flag = True else: flag = False is better written as: flag = some_condition In the above example, you should write: success = child.exitstatus and child.exitstatus == 0 except that I think you have the condition wrong... if exitstatus is zero, you get False and True => False, but if exitstatus is non-zero, you get True and False => False. So you will always get success = False. -- Steven ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] help with a class
John wrote: Thanks for the feedback. I wasn't aware about the assert usage not being intended for production code. That's not quite true. There is nothing wrong with using asserts in production code. The important thing is to use them *properly*. Asserts are for checking your internal program logic, and should never be used for validating data. The reason is that asserts can be turned off. If the user calls Python with the optimize -O switch, all assertions are silently dropped from the code when it is compiled. Obviously this is disastrous if you are using assert to check input arguments and user data, since now those checks won't happen. But assertions can still be useful in production code. When and why? For testing *your* logic about the program. The sad truth is that programmers are merely human, and we make mistakes. Sometimes we reason that our code does one thing, when in fact we've forgotten a case or misunderstood it, and the code does something different from what we expected. Or we fear that some function we rely on has a bug. As they say, beware of any situation which you are sure can't possibly happen, because it surely will. To program defensively, you might write something like this: n = some_function(arg) if n > 0: do_something(n) else: # This can never happen! But just in case it does... raise RuntimeError("unexpected internal error") What does this tell us? It tells us that some_function promises to always return a positive number (this is sometimes called a contract), but we don't *quite* believe it. If we trusted it completely, we would just write this: n = some_function(arg) do_something(n) and that's perfectly fine. 99.999% of your code should look like that: you trust the function to do what you expect. But perhaps you have a little nagging doubt: "some_function is really complicated, I'm pretty sure it works correctly, but maybe I made a subtle mistake". Hey, you're only human. So you leave the test in *just in case*. Assertions are for those "just in case" tests. If you're sure that the "else" clause will never happen, why do the test every time? Because you're cautious. But maybe you don't need to be cautious all the time. Perhaps you'd like an option to run your code faster by skipping all those tests that you're sure will never fail. So you might start with a global variable: __debug__ = True and write code like this: n = some_function(arg) if __debug__: # Just in case... if n <= 0: # note we swap the test around. # This can never happen! But just in case it does... raise RuntimeError("unexpected internal error") do_something(n) That gives you the best of both worlds: if __debug__ is True (the default), you have the extra safety of the debugging test. And if it's False, you skip the test, and so your code is a little bit faster. That's what Python *automatically* does for you. Just write your code like this instead n = some_function(arg) assert n <= 0, "unexpected internal error" do_something(n) and the Python compiler will automatically handle everything for you, according to whether or not you are running in standard "debug mode" or with the -O optimize switch. -- Steven ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Raw input query (?)
Lisi wrote: I copied and ran the following script: [...] What extra should I have done because the variable value came from the keyboard, and why is it different from the first example? You can investigate this yourself: >>> a = 12 >>> a = raw_input("please type 12") please type 12 12 >>> a = 12 >>> b = raw_input("please type 12: ") please type 12: 12 >>> a 12 >>> b '12' See the difference? Here's more of a clue: >>> type(a) >>> type(b) -- Steven ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Confirmation if command worked
Steven D'Aprano wrote: if some_condition: flag = True else: flag = False is better written as: flag = some_condition Actually, that's a slight over-simplification. some_condition may not actually be a bool. If you don't mind flag also being a non-bool, that's fine, but if you want to ensure that it is one of True/False, then you can call: flag = bool(some_condition) to force flag to be one of True or False. But that's generally not necessary unless you care about what flag looks like when printed. -- Steven ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Raw input query (?)
On 25/08/11 10:46, Lisi wrote: I copied and ran the following script: multiplier = 12 for j in range(1,13): print "%d x %d = %d" %(j, multiplier, j*multiplier) That ran perfectly and gave me the 12 times table. I then decided that it would be fun to branch out and make teh script "universal", so I wrote and ran: print "Which times table do you want?" multiplier = raw_input () I seem to recognise that code :-) You will find if you fast-forward to the "talking to the user" topic that we revisit the multiplication table doing exactly this. You will find out what is missing there. :-) HTH, -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] String encoding
I have a string question for Python2. Basically I have two strings with non-ASCII characters and I would like to have a better understanding of what the escapes are from and how to possibly remove/convert/encode the string to something else. If the description of my intended action is vague it is because my intent at this point is vague until I understand the situation better. ' M\xc9XICO' and ' M\311XICO' Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Help with if-elif-else structure
Looks good, although I would add one or two things. > #assuming target number 15 > Put that in a variable for the target number > roll = (result, initial_mins, initial_max) > if roll[0] > 15: >if roll[1] >= 2: You could even put all the constants in variables > print("Success") >elif roll[2] >= 2: >print("Critical failure!") >else: >print("Failure.") > elif roll[0] <= 15: >if roll[1] >= 2: >print("Critical success!") >elif roll[2] >= 2: >print("Failure") >else: >print("Success") > Also need a couple comments, plus everything from the other emails. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Python Speech
It wasn't on the repo. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] largest palindrome number
Hi, I'm doing a puzzle where it asked me to find the largest palindrome number formed by the product of two three-digit numbers. They mentioned an example saying that 9009 is the largest palindrome number formed by two two-digit numbers (99 * 91). I've written my code this way.. and I tested it with the given example and I got it right! *Logic I used :* largest two digit number is 99 and three digit number is 999.. so largest product of two two-digit numbers is < 100*100 and for three-digit numbers is < 1000*1000. So, I used a for loop and it assigns a palindromic value to *PNum* till it is < 100*100 (for 2 digit number) and < 1000*1000 (for three-digit number).. Thus it stops at the max possible palindromic value, which is what we want. def palindrome (n) : TempN = n rev = 0 while n != 0 : k = n % 10 rev = (rev * 10) + k n = n / 10 if TempN == rev : return TempN # Palindrome else : return 0 # not Palindrome for i in range (1,100) : for j in range (i,100) : Temp = palindrome(i*j) if Temp < 1 and Temp != 0 : PNum = Temp print PNum So, for getting the largest palindrome number formed by two three-digit numbers, I changed 100 to 1000 and 1,00,00 to 1,000,000 in the highlighted area. Thus I got the answer to be 88. When I submitted the answer, its saying wrong! Where I'm going wrong ? help me, please ! ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] String encoding
On 25/08/11 15:36, Prasad, Ramit wrote: I have a string question for Python2. Basically I have two strings with > non-ASCII characters and I would like to have a better understanding > of what the escapes are from ' M\xc9XICO' and ' M\311XICO' I don't know what they are from but they are both the same value, one in hex and one in octal. 0xC9 == 0311 As for the encoding mechanisms I'm afraid I can't help there! HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] largest palindrome number
On Thu, Aug 25, 2011 at 6:49 PM, surya k wrote: > Hi, > I'm doing a puzzle where it asked me to find the largest palindrome number > formed by the product of two three-digit numbers. They mentioned an example > saying that 9009 is the largest palindrome number formed by two two-digit > numbers (99 * 91). > I've written my code this way.. and I tested it with the given example and I > got it right! > Logic I used : > largest two digit number is 99 and three digit number is 999.. so largest > product of two two-digit numbers is < 100*100 and for three-digit numbers is > < 1000*1000. > So, I used a for loop and it assigns a palindromic value to PNum till it is > < 100*100 (for 2 digit number) and < 1000*1000 (for three-digit number).. > Thus it stops at the max possible palindromic value, which is what we want. > > def palindrome (n) : > > TempN = n > rev = 0 > while n != 0 : > k = n % 10 > rev = (rev * 10) + k > n = n / 10 > if TempN == rev : > return TempN # Palindrome > else : > return 0 # not Palindrome > > for i in range (1,100) : > for j in range (i,100) : > Temp = palindrome(i*j) > if Temp < 1 and Temp != 0 : > PNum = Temp > print PNum > > > So, for getting the largest palindrome number formed by two three-digit > numbers, I changed 100 to 1000 and 1,00,00 to 1,000,000 in the highlighted > area. Thus I got the answer to be 88. When I submitted the answer, its > saying wrong! > Where I'm going wrong ? > help me, please ! > When you get a new palindrome, you should make sure it's bigger than the one you already have before you replace the old one. 88 is the last palindrome you find, but it is not the the biggest. You cannot assume the biggest one will be found last. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Raw input query (?)
On Thursday 25 August 2011 15:17:04 Alan Gauld wrote: > On 25/08/11 10:46, Lisi wrote: > > I copied and ran the following script: > > > > multiplier = 12 > > > > for j in range(1,13): > > print "%d x %d = %d" %(j, multiplier, j*multiplier) > > > > That ran perfectly and gave me the 12 times table. > > > > I then decided that it would be fun to branch out and make teh > > script "universal", so I wrote and ran: > > > > print "Which times table do you want?" > > > > multiplier = raw_input () > > I seem to recognise that code :-) > > You will find if you fast-forward to the "talking to the user" topic > that we revisit the multiplication table doing exactly this. You will > find out what is missing there. :-) Thanks to all three of you for your input. I do now understand what is wrong, but can't work out how to put it right. I did as you suggested, Dave. But by the time I was able to get to my computer and read it, the others' replies had come in. So I ran it mainly to learn how to do it. And I am not entirely sure that I would have understood the result if I hadn't already known what it was meant to be saying!! I started to say that I would just have to wait, but on second thoughts I'll fast forward as suggested, and then go back to do the missing sections. Lisi ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] help with 'organization'
Hello, I am writing a module that will have two classes ('runners') I am calling them, as they will ultimately use subprocess to run a command line program, so they are basically option parsers, etc... As I wrote the second 'runner', I realized many of the methods are going to be the same as the first, so I would actually like to create a third class that has the methods which are mutual between the two. The problem are the 'self' calls I know a code example might help, so I try to show it here (my code I'm afraid is too complex and ugly at the moment). You can see the it fails because MyTools doesn't have 'this' attribute... class MyTools: def f(self, this): print(this) def foo(self): this = self.this print(this) class MyProcess: def __init__(self): self.tools = MyTools() self.this = 'My Process, this' self.tools.f(self.this) self.tools.foo() if __name__ == "__main__": mp = MyProcess() ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] Finding the differences between two lists
Hello, Bare with me, as I am new to Python and a beginner programmer. I am trying to compare two lists (not of the same length), and create a new list of items that are -not- found in both lists. Scenario: I have a list of MAC addresses that are known and good, and am comparing it to a list of MACs found in a scan. I want to weed out the those which are unknown. I am using IDLE (Python 2.7) on Windows, and all files are in the same directory. Code: scanResults = open('scanResults.txt', 'r') verifiedList = open('verifiedList.txt', 'r') badMacs = [] for mac in scanResults: if mac not in verifiedList: print mac badMacs.append(mac) else: break When I print 'badMacs', the results come up empty: [] Any help would be greatly appreciated! Regards, Justin ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Finding the differences between two lists
Not entirely sure, but I think it is as simple as: scanResults = open('scanResults.txt', 'r').readlines() verifiedList = open('verifiedList.txt', 'r').readlines() Now both are lists. I assume each mac address is on it's own line? -john On Thu, Aug 25, 2011 at 8:56 PM, Justin Wendl wrote: > Hello, > > Bare with me, as I am new to Python and a beginner programmer. > I am trying to compare two lists (not of the same length), and create a new > list of items that are -not- found in both lists. > > Scenario: I have a list of MAC addresses that are known and good, and am > comparing it to a list of MACs found in a scan. I want to weed out the > those which are unknown. I am using IDLE (Python 2.7) on Windows, and all > files are in the same directory. > > Code: > > scanResults = open('scanResults.txt', 'r') > verifiedList = open('verifiedList.txt', 'r') > badMacs = [] > > for mac in scanResults: > if mac not in verifiedList: > print mac > badMacs.append(mac) > else: > break > > > When I print 'badMacs', the results come up empty: > [] > > > Any help would be greatly appreciated! > > Regards, > Justin > > ___ > Tutor maillist - Tutor@python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > -- Configuration `` Plone 2.5.3-final, CMF-1.6.4, Zope (Zope 2.9.7-final, python 2.4.4, linux2), Python 2.6 PIL 1.1.6 Mailman 2.1.9 Postfix 2.4.5 Procmail v3.22 2001/09/10 Basemap: 1.0 Matplotlib: 1.0.0 ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Finding the differences between two lists
Hi John, Thanks for the quick response. Unfortunately it is returning the same result.. - Justin On Thu, Aug 25, 2011 at 2:59 PM, John wrote: > Not entirely sure, but I think it is as simple as: > > scanResults = open('scanResults.txt', 'r').readlines() > verifiedList = open('verifiedList.txt', 'r').readlines() > > Now both are lists. I assume each mac address is on it's own line? > > -john > > > On Thu, Aug 25, 2011 at 8:56 PM, Justin Wendl > wrote: > > Hello, > > > > Bare with me, as I am new to Python and a beginner programmer. > > I am trying to compare two lists (not of the same length), and create a > new > > list of items that are -not- found in both lists. > > > > Scenario: I have a list of MAC addresses that are known and good, and am > > comparing it to a list of MACs found in a scan. I want to weed out the > > those which are unknown. I am using IDLE (Python 2.7) on Windows, and > all > > files are in the same directory. > > > > Code: > > > > scanResults = open('scanResults.txt', 'r') > > verifiedList = open('verifiedList.txt', 'r') > > badMacs = [] > > > > for mac in scanResults: > > if mac not in verifiedList: > > print mac > > badMacs.append(mac) > > else: > > break > > > > > > When I print 'badMacs', the results come up empty: > > [] > > > > > > Any help would be greatly appreciated! > > > > Regards, > > Justin > > > > ___ > > Tutor maillist - Tutor@python.org > > To unsubscribe or change subscription options: > > http://mail.python.org/mailman/listinfo/tutor > > > > > > > > -- > Configuration > `` > Plone 2.5.3-final, > CMF-1.6.4, > Zope (Zope 2.9.7-final, python 2.4.4, linux2), > Python 2.6 > PIL 1.1.6 > Mailman 2.1.9 > Postfix 2.4.5 > Procmail v3.22 2001/09/10 > Basemap: 1.0 > Matplotlib: 1.0.0 > ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] help with 'organization'
Ha! Inheritance! On Thu, Aug 25, 2011 at 7:51 PM, John wrote: > Hello, I am writing a module that will have two classes ('runners') I > am calling them, as they will ultimately use subprocess to run a > command line program, so they are basically option parsers, etc... > > As I wrote the second 'runner', I realized many of the methods are > going to be the same as the first, so I would actually like to create > a third class that has the methods which are mutual between the two. > The problem are the 'self' calls > > I know a code example might help, so I try to show it here (my code > I'm afraid is too complex and ugly at the moment). You can see the it > fails because MyTools doesn't have 'this' attribute... > > class MyTools: > def f(self, this): > print(this) > > def foo(self): > this = self.this > print(this) > > class MyProcess: > def __init__(self): > self.tools = MyTools() > > self.this = 'My Process, this' > > self.tools.f(self.this) > > self.tools.foo() > > if __name__ == "__main__": > mp = MyProcess() > -- Configuration `` Plone 2.5.3-final, CMF-1.6.4, Zope (Zope 2.9.7-final, python 2.4.4, linux2), Python 2.6 PIL 1.1.6 Mailman 2.1.9 Postfix 2.4.5 Procmail v3.22 2001/09/10 Basemap: 1.0 Matplotlib: 1.0.0 ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] help with 'organization'
On Thu, Aug 25, 2011 at 1:51 PM, John wrote: > Hello, I am writing a module that will have two classes ('runners') I > am calling them, as they will ultimately use subprocess to run a > command line program, so they are basically option parsers, etc... > > As I wrote the second 'runner', I realized many of the methods are > going to be the same as the first, so I would actually like to create > a third class that has the methods which are mutual between the two. > The problem are the 'self' calls > > I know a code example might help, so I try to show it here (my code > I'm afraid is too complex and ugly at the moment). You can see the it > fails because MyTools doesn't have 'this' attribute... > > class MyTools: >def f(self, this): >print(this) > >def foo(self): >this = self.this >print(this) > > class MyProcess: >def __init__(self): >self.tools = MyTools() > >self.this = 'My Process, this' > >self.tools.f(self.this) > >self.tools.foo() > > if __name__ == "__main__": >mp = MyProcess() > ___ > Tutor maillist - Tutor@python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > I am having a very difficult time following what you are trying to do, but then, i'm not that bright, so it's probably me. But, I will say this: class MyTools: def f(self, this): print(this) def foo(self): this = self.this print(this) In the second method (foo) you have it creating a local variable called this, which is equal to the class variable self.this. Why not just use the class variable throughout that method? So, print(self.this). My second thing, and this is just a personal pet peeve, why not create descriptive names for your variables? Creating things called this or that (and in this case, literally this or that) is hyper confusing. My third thing. I think you are going to end up with an attribute error because I don't see where the class has ever created a class variable called this. Maybe you meant to do something like this instead: class MyTools: def __init__(self, this): self.this = this def f(self): print(self.this) def foo(self): print(self.this) so in your other object, it would then look something like this: class MyProcess: def __init__(self): self.this = 'My Process, this' self.tools = MyTools(self.this) self.tools.f() self.tools.foo() But, every time you instantiate MyProcess (not call it) you are going to call the two methods of Tools class. If you want to seperate this, so you can do something like tools.foo() and then later on go tools.f() you can do that in a few ways: One, you can just get rid of self.tools.f() self.tools.foo() and once you create a MyProcess object you are free to call tools methods at your leisure. For example m = MyProcess() m.tools.foo() m.tools.f() Unless you really do want those methods once you create the instance because it's relevent to the creation of the object, then leave them where they are. Lastly, I don't understand what you mean by "self" calls. This seems rather academic to me, do you have a real example? I also don't understand what a Runner is. Maybe its some compsci term or something. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Finding the differences between two lists
You may try using set instead of list. >>> verifiedList = {[1,2,3} >>> scanResults = {1,2,3,4,5} >>> badMacs = scanResults - verifiedList >>> badMacs set([4, 5]) >>> verifiedList = {1,2,3,7,8,9} >>> badMacs = scanResults - verifiedList >>> badMacs set([4, 5]) -- shantanoo On 26-Aug-2011, at 12:26 AM, Justin Wendl wrote: > Hello, > > Bare with me, as I am new to Python and a beginner programmer. > I am trying to compare two lists (not of the same length), and create a new > list of items that are -not- found in both lists. > > Scenario: I have a list of MAC addresses that are known and good, and am > comparing it to a list of MACs found in a scan. I want to weed out the those > which are unknown. I am using IDLE (Python 2.7) on Windows, and all files > are in the same directory. > > Code: > > scanResults = open('scanResults.txt', 'r') > verifiedList = open('verifiedList.txt', 'r') > badMacs = [] > > for mac in scanResults: > if mac not in verifiedList: > print mac > badMacs.append(mac) > else: > break > > > When I print 'badMacs', the results come up empty: > [] > > > Any help would be greatly appreciated! > > Regards, > Justin > ___ > Tutor maillist - Tutor@python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Finding the differences between two lists
On Thu, Aug 25, 2011 at 4:08 PM, Justin Wendl wrote: > Hi John, > > Thanks for the quick response. Unfortunately it is returning the same > result.. Please send a small example of the contents in each file. -- Giovanni Tirloni sysdroid.com ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Finding the differences between two lists
Giovanni, scanResults.txt: 00:16:3E:D0:26:25 00:16:3E:43:7D:24 00:16:3E:2D:6D:F8 00:16:3E:EB:04:D9 00:16:3E:FD:85:0B 00:1C:14:AF:04:39 00:1C:14:E3:D6:CA 00:1C:14:15:B2:C8 00:1C:14:47:5A:A0 00:1C:14:BA:D9:E9 verifiedList: 00:1C:14:BA:D9:E9 00:16:3E:D0:26:25 00:1C:14:AF:04:39 00:16:3E:EB:04:D9 - Justin On Thu, Aug 25, 2011 at 3:29 PM, Giovanni Tirloni wrote: > On Thu, Aug 25, 2011 at 4:08 PM, Justin Wendl > wrote: > > Hi John, > > > > Thanks for the quick response. Unfortunately it is returning the same > > result.. > > Please send a small example of the contents in each file. > > -- > Giovanni Tirloni > sysdroid.com > ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Finding the differences between two lists
On Thu, Aug 25, 2011 at 9:08 PM, Justin Wendl wrote: > Hi John, > > Thanks for the quick response. Unfortunately it is returning the same > result.. > > This is caused by the else: break part of the the code. Break breaks out of the loop, thus you skip all following elements if you go through the 'else' part once. What you probably meant was: else: continue This skips only the remainder of the current traversion of the loop, and goes on with the next one. In this case it's even simpler: There is no remainder of the current run of the loop to skip, so you should be allright if you remove the else part altogether. -- André Engels, andreeng...@gmail.com ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Finding the differences between two lists
> Scenario: I have a list of MAC addresses that are known and good, and am > comparing it to a list of MACs found in a scan. I want to weed out the > those which are unknown. I am using IDLE (Python 2.7) on Windows, and all > files are in the same directory. > > Code: > > scanResults = open('scanResults.txt', 'r') > verifiedList = open('verifiedList.txt', 'r') You don't close the files after you open them, which is bad practice. "with" is a great keyword, because it closes the file once it's run its block of code. We'll use that: with open("scanResults.txt", "r") as f: #open scanResults.txt and put the file object in variable f scanResults = f.readlines() #once this finishes scanResults.txt is closed with open("verifiedList.txt", "r") as f: verifiedList = f.readlines() > badMacs = [] > for mac in scanResults: > if mac not in verifiedList: > print mac > badMacs.append(mac) > else: > break I can't say for sure, since I don't know how your logs look, but this loop will break at the first match (I think!). You could try changing the break statement to a continue statement (or just ignoring it altogether -- if it's in verifiedList you don't need to do anything). Anyway, list comprehensions are something I've been experimenting with lately, because I need the practice, so I'm going to suggest that instead: badMacs = [item for item in scanResults if item not in verifiedList] Other than that, there's not much to say; the standard is 4 spaces indentation, personally I feel that 1 space is too little, since it's hard to see where one block ends and another begins. best regards, Robert S. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Finding the differences between two lists
shantanoo, Andre, and Robert: All of your solutions seem to work (and thank you for the tips!), however, with each solution there seems to be 2 MACs that should not be in the results. 00:1C:14:BA:D9:E9 and 00:16:3E:EB:04:D9 should not be be turning up in the results because they are in the 'verified' list. These lists are not sorted - do you think that could be the issue? - Justin On Thu, Aug 25, 2011 at 3:48 PM, Robert Sjoblom wrote: > > Scenario: I have a list of MAC addresses that are known and good, and am > > comparing it to a list of MACs found in a scan. I want to weed out the > > those which are unknown. I am using IDLE (Python 2.7) on Windows, and > all > > files are in the same directory. > > > > Code: > > > > scanResults = open('scanResults.txt', 'r') > > verifiedList = open('verifiedList.txt', 'r') > > You don't close the files after you open them, which is bad practice. > "with" is a great keyword, because it closes the file once it's run > its block of code. We'll use that: > > with open("scanResults.txt", "r") as f: #open scanResults.txt and > put the file object in variable f >scanResults = f.readlines() #once this finishes > scanResults.txt is closed > with open("verifiedList.txt", "r") as f: >verifiedList = f.readlines() > > > badMacs = [] > > for mac in scanResults: > > if mac not in verifiedList: > >print mac > >badMacs.append(mac) > > else: > >break > > I can't say for sure, since I don't know how your logs look, but this > loop will break at the first match (I think!). You could try changing > the break statement to a continue statement (or just ignoring it > altogether -- if it's in verifiedList you don't need to do anything). > Anyway, list comprehensions are something I've been experimenting with > lately, because I need the practice, so I'm going to suggest that > instead: > badMacs = [item for item in scanResults if item not in verifiedList] > > Other than that, there's not much to say; the standard is 4 spaces > indentation, personally I feel that 1 space is too little, since it's > hard to see where one block ends and another begins. > > best regards, > Robert S. > ___ > Tutor maillist - Tutor@python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Finding the differences between two lists
> shantanoo, Andre, and Robert: > > All of your solutions seem to work (and thank you for the tips!), however, > with each solution there seems to be 2 MACs that should not be in the > results. > > 00:1C:14:BA:D9:E9 and > 00:16:3E:EB:04:D9 > > should not be be turning up in the results because they are in the > 'verified' list. These lists are not sorted - do you think that could be > the issue? Definitely not, it doesn't matter if they're sorted no matter what way you solve it. What matters is how the logfile looks to Python. Take this fake list I've made consisting of your two MAC addresses: scanResults = ['00:1C:14:BA:D9:E9\n', '00:16:3E:EB:04:D9\n'] verifiedList = ['00:1C:14:BA:D9:E9\n', '00:16:3E:EB:04:D9'] >>> scanResults == verifiedList False The difference, obviously, is that 00:16:3E:EB:04:D9 contains a newline \n in one of the files but not the other. As such, they're not identical. We can solve this (probably) by adding some more list comprehension when we open the files initially: with open("scanResults.txt", "r") as f: scanResults = [line.strip() for line in f.readlines()] with open("verifiedList.txt", "r") as f: verifiedList = [line.strip() for line in f.readlines()] badMacs = [item for item in scanResults if item not in verifiedList] I suspect that it's the newlines that are messing with you, but if it's something else I can't tell without the actual files. -- best regards, Robert S. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Finding the differences between two lists
Robert, The lists were created using MS Notepad, and I forgot about the newlines - so you were absolutely right! So, is it possible to use strip() immediately when reading a file into a list to avoid confusion down the road, and is this common? Thank you everyone who contributed to this thread :-) - Justin On Thu, Aug 25, 2011 at 5:21 PM, Robert Sjoblom wrote: > > shantanoo, Andre, and Robert: > > > > All of your solutions seem to work (and thank you for the tips!), > however, > > with each solution there seems to be 2 MACs that should not be in the > > results. > > > > 00:1C:14:BA:D9:E9 and > > 00:16:3E:EB:04:D9 > > > > should not be be turning up in the results because they are in the > > 'verified' list. These lists are not sorted - do you think that could be > > the issue? > > Definitely not, it doesn't matter if they're sorted no matter what way > you solve it. What matters is how the logfile looks to Python. Take > this fake list I've made consisting of your two MAC addresses: > > scanResults = ['00:1C:14:BA:D9:E9\n', '00:16:3E:EB:04:D9\n'] > verifiedList = ['00:1C:14:BA:D9:E9\n', '00:16:3E:EB:04:D9'] > >>> scanResults == verifiedList > False > > The difference, obviously, is that 00:16:3E:EB:04:D9 contains a > newline \n in one of the files but not the other. As such, they're not > identical. We can solve this (probably) by adding some more list > comprehension when we open the files initially: > with open("scanResults.txt", "r") as f: > scanResults = [line.strip() for line in f.readlines()] > with open("verifiedList.txt", "r") as f: > verifiedList = [line.strip() for line in f.readlines()] > > badMacs = [item for item in scanResults if item not in verifiedList] > > I suspect that it's the newlines that are messing with you, but if > it's something else I can't tell without the actual files. > -- > best regards, > Robert S. > ___ > Tutor maillist - Tutor@python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] finalizing code
Hello! I recently started programming in python (I use IDLE with python 2.7 on ubuntu 11.04, by the way) and recently made a program (no interface) that launches other programs. The problem I'm having is that when I gave my friend the code, he had to get an editor to use the code. How do I make it so that when you open the program, it starts the code (so anyone can use it, not just those who have idle and know ow to program python)? Sorry if this is unclear. I basically want to make a stand- alone command line application (or one that boots in terminal). It's very basic and runs like so (except longer and slightly more complex): loop = 1 > while loop == 1: > choice = raw_input(">") > if choice == "prog1": > print "Launching Prog1" > os.system("prog1") > loop = 0 > else: > print "invalid program. Try again." God Bless, Ben Schwabe ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] finalizing code
Hello! I recently started programming in python (I use IDLE with python 2.7 on ubuntu 11.04, by the way) and recently made a program (no interface) that launches other programs. The problem I'm having is that when I gave my friend the code, he had to get an editor to use the code. How do I make it so that when you open the program, it starts the code (so anyone can use it, not just those who have idle and know ow to program python)? Sorry if this is unclear. I basically want to make a stand- alone command line application (or one that boots in terminal). It's very basic and runs like so (except longer and slightly more complex): loop = 1 > while loop == 1: > choice = raw_input(">") > if choice == "prog1": > print "Launching Prog1" > os.system("prog1") > loop = 0 > else: > print "invalid program. Try again." God Bless, Ben Schwabe ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] finalizing code
From: tutor-bounces+ramit.prasad=jpmorgan@python.org [mailto:tutor-bounces+ramit.prasad=jpmorgan@python.org] On Behalf Of Bspymaster Sent: Thursday, August 25, 2011 5:54 PM To: tutor@python.org Subject: [Tutor] finalizing code Hello! I recently started programming in python (I use IDLE with python 2.7 on ubuntu 11.04, by the way) and recently made a program (no interface) that launches other programs. The problem I'm having is that when I gave my friend the code, he had to get an editor to use the code. How do I make it so that when you open the program, it starts the code (so anyone can use it, not just those who have idle and know ow to program python)? Sorry if this is unclear. I basically want to make a stand- alone command line application (or one that boots in terminal). It's very basic and runs like so (except longer and slightly more complex): loop = 1 while loop == 1: choice = raw_input(">") if choice == "prog1": print "Launching Prog1" os.system("prog1") loop = 0 else: print "invalid program. Try again." God Bless, Ben Schwabe = If it is just in the module directly, you can probably just say 'python file.py' It is usually recommended to stick everything into different functions then at the end say If __name__=="__main__": function() Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] String encoding
>I don't know what they are from but they are both the same value, one in >hex and one in octal. > >0xC9 == 0311 > >As for the encoding mechanisms I'm afraid I can't help there! Nice catch! Yeah, I am stuck on the encoding mechanism as well. I know how to encode/decode...but not what encoding to use. Is there a reference that I can look up to find what encoding that would correspond to? I know what the character looks like if that helps. I know that Python does display the correct character sometimes, but not sure when or why. Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] finalizing code
On 25 August 2011 23:54, Bspymaster wrote: > How do I make it so that when you open the program, it starts the code (so > anyone can use it, not just those who have idle and know ow to program > python)? > To add to what Ramit's said: On Linux/Ubuntu it's customary to add as the top line of a script file a "shebang" or "hashbang" header ( http://en.wikipedia.org/wiki/Shebang_%28Unix%29), which typically looks like this for Python scripts: #!/usr/bin/env python This then allows the operating system to know which interpreter to use to run the script (Python in this case), when you directly try to execute the script. In order to be able to run the script like any other command on the operating system, you also need to actually mark the file as executable. This may be done via the GUI by right clicking and clicing on "Permssions" or more easily by executing the command: chmod +x file.py This tells the system to make the file executable by anyone on the system. If the current working folder is the location of the script, you dan then run it by entering: ./file.py Additionally it's useful to know that under Ubuntu (and likely some other Linux variants), if you create a folder called "bin" inside the your home folder and the the script in there, then you can run the script directly from any location since your home/bin folder will be automatically searched when you issue commands without specifying their path/location explicitly. Hope all that makes sense and helps you. Walter ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] String encoding
Prasad, Ramit wrote: I don't know what they are from but they are both the same value, one in hex and one in octal. 0xC9 == 0311 As for the encoding mechanisms I'm afraid I can't help there! Nice catch! Yeah, I am stuck on the encoding mechanism as well. I know how to encode/decode...but not what encoding to use. Is there a reference that I can look up to find what encoding that would correspond to? I know what the character looks like if that helps. I know that Python does display the correct character sometimes, but not sure when or why. In general, no. The same byte value (0xC9) could correspond to many different encodings. In general, you *must* know what the encoding is in order to tell how to decode the bytes. Think about it this way... if I gave you a block of data as hex bytes: 240F91BC03...FF90120078CD45 and then asked you whether that was a bitmap image or a sound file or something else, how could you tell? It's just *bytes*, it could be anything. All is not quite lost though. You could try decoding the bytes and see what you get, and see if it makes sense. Start with ASCII, Latin-1, UTF-8, UTF-16 and any other encodings in common use. (This would be like pretending the bytes were a bitmap, and looking at it, and trying to decide whether it looked like an actual picture or like a bunch of random pixels. Hopefully it wasn't meant to look like a bunch of random pixels.) Web browsers such as Internet Explorer and Mozilla will try to guess the encoding by doing frequency analysis of the bytes. Mozilla's encoding guesser has been ported to Python: http://chardet.feedparser.org/ But any sort of guessing algorithm is just a nasty hack. You are always better off ensuring that you accurately know the encoding. -- Steven ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] help with 'organization'
John wrote: I know a code example might help, so I try to show it here (my code I'm afraid is too complex and ugly at the moment). You can see the it fails because MyTools doesn't have 'this' attribute... Then give it one. class MyTools: Add an initialisation method: def __init__(self, this): self.this = this def f(self, this): print(this) def foo(self): this = self.this print(this) class MyProcess: def __init__(self): self.tools = MyTools() self.this = 'My Process, this' self.tools.f(self.this) self.tools.foo() And change this to: def __init__(self): self.this = 'My Process, this' self.tools = MyTools(self.this) self.tools.f(self.this) self.tools.foo() There are probably better, or at least other, ways to organise the code which will do the job. An abstract base class with just the shared methods might work. (I'm not sure if that's best described as a mixin or not...) class SharedMethods(object): # shared methods go here class FirstRunner(SharedMethods): # methods unique to FirstRunner class SecondRunner(SharedMethods): # methods unique to SecondRunner -- Steven ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor