Re: [Tutor] look back comprehensively
On Mon, Dec 24, 2018 at 5:16 AM Mats Wichmann wrote: > On 11/14/18 3:01 PM, Steven D'Aprano wrote: > > On Tue, Nov 13, 2018 at 11:59:24PM -0500, Avi Gross wrote: > >> I have been thinking about the thread we have had where the job seemed > to be > >> to read in a log file and if some string was found, process the line > before > >> it and generate some report. Is that generally correct? > > > > If that description is correct, then the solution is trivial: iterate > > over the file, line by line, keeping the previous line: > > > > previous_line = None > > for current_line in file: > > process(current_line, previous_line) > > previous_line = current_line > > > The classic COBOL programmers idiom :-) That said, sometimes text processing at the shell can precede or even replace some of these. Of course that assumes Unix/Linux OS. In this speciic case grep with its -B option can be used to generate a file that contains only the lines of interest. HTH Asokan Pichai ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] A required question
On Sat, Nov 24, 2018, 14:33 Avi Gross David, > > As I suspected. Yes, I am aware how to do those things. Just wondered if > anyone automated the process so a fairly simple interface worked. > Does the requirements.txt file (associated with pip IIRC) does most of what you want? > > I am dropping the request. > > Avi > > -Original Message- > From: Tutor On Behalf Of > David Rock > Sent: Friday, November 23, 2018 9:28 PM > To: Tutor Python > Subject: Re: [Tutor] A required question > > > > On Nov 23, 2018, at 09:35, Alan Gauld via Tutor > wrote: > > > > On 23/11/2018 05:34, Avi Gross wrote: > >> What I was thinking was the ability to do something like this: > >> > >> import ReChoir as require > >> > >> require.version(condition, before=True, after=False) > >> require.modules(module list, recursive=True) require.os([“Eunuchs”, > >> “Windblows”]) > >> require.functionality(“print3”) > > > > I can see the logic but suspect discussion of new features is probably > > the preserve of the main Python list. If you can get traction there > > somebody might actually go ahead and write one! > > discussion of a “require” library probably isn’t necessary. It’s pretty > straightforward to include the logic using existing methods. > > For the version of python, test against sys.version_info For the modules, > put your import calls in a try block and handle exceptions For the OS > version, test against os.name or sys.platform The last one, > “functionality,” is a bit vague. Probably another candidate for a try > block. > > > — > David Rock > da...@graniteweb.com > > > > > ___ > Tutor maillist - Tutor@python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > > ___ > Tutor maillist - Tutor@python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Recommended Python Compiler
For a simple beginners editor -- geany is a great choice. It can be used with minimal or no configuration/set up; and once you know your way around you can tweak it as much as you want. It is easily installable on Debian/Ubuntu -- Asokan Pichai *---* We will find a way. Or, make one. (Hannibal) ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] noob python question
Can you retype the question and your code? On 26 October 2015 at 04:46, bob5487 <evolution5...@gmail.com> wrote: > Howdy! > > Reading *Learn Python the Hard Way* Zed Shaw > > All good so far but got to Ex 42 dealing with classes... > > I get a TypeError: getattr(): attribute name must be a string when I run > the > program... > > I looked online, python reference manual 3rd edition, etc... > > I was wondering if anyone has experience with this book because I hit a > road > block > > > > > > -- > View this message in context: > http://python.6.x6.nabble.com/noob-python-question-tp5174789.html > Sent from the Python - tutor mailing list archive at Nabble.com. > ___ > Tutor maillist - Tutor@python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > -- Asokan Pichai *---* We will find a way. Or, make one. (Hannibal) *To find everything profound — that is an inconvenient trait.* It makes one strain one's eyes all the time, and in the end one finds more than one might have wished. -- Nietzsche ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] list comprehension with else
On Sun, Jan 18, 2015 at 6:50 PM, Sydney Shall s.sh...@virginmedia.com wrote: I am a beginner and I have a question of syntax. Welcome! I am just learning to use list comprehension, which oc course, I find very helpful indeed. However, I am stuck with a specific problem of how to incorporate an else in a list comp-rehension. I cannot do it. The following snippet of code does what I need. But, perhaps I am solving this math error problem incorrectly. The problem is I am occasionally getting exactly zeros when I need to obtain the logarithm of the number. for i in range(len(cap)): Using a for loop like this is generally a poor idea. for aCap in cap: is the more pythonic way. And also will help you translate to a list comprehension easily if cap[i] == 0.0: tmp = math.log(1.0) lncap.append(tmp) Possibly lncap.append(math.log(1.0)) or even lncap.append(0) is simpler else: lncap.append(math.log(cap[i])) Having said that above your present code, let me try to explain the thought process behind constructing the list comprehension for your purpose. It is possible that what you need is not an else in the list comprehension lncap = [ f(aCap) for aCap in cap] will be the starting point; where f() will need to provide either math.log(aCap) or 0 as we saw earlier. You can actually write an auxiliary function f that does just that; like say def f(p): if p == 0.0: return 0.0 return math.log(p) Or write the list comprehension as: lncap = [ (math.log(aCap) if aCap 0 else 0.0) for aCap in cap] Hope this helps ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] most useful ide
On Sun, Feb 2, 2014 at 1:55 PM, Ian D dux...@hotmail.com wrote: Hi Are there any recommendations for python ide's currently I am using idle, which seems pretty decent but am open to any suggestions cheers While not an IDE in the usual sense I have found IPython a great addition to my toolkit. YMMV Asokan Pichai ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Fwd: What's in a name?
On Fri, Jan 03, 2014 at 02:45:04AM -0500, Keith Winston wrote: And to beat that poor horse in the same example, my current way of doing that would be: for alist in lista, listb: print(alist, eval(alist)) Since you know both pieces, namely the name of the entity alist and its actual symbol aka alist, why not do something like: Lists = {lista: lista, listb: lisb} and use Lists[x] ... HTH Asokan Pichai ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Converting integers into digit sum (Python 3.3.0)
On Tue, Dec 10, 2013 at 3:09 PM, Rafael Knuth rafael.kn...@gmail.comwrote: Hej there, I don't know if everyone would consider this more elegant but it's certainly shorter: Thanks! def DigitSum(YourNumber): ... return sum(map(int, YourNumber)) ... DigitSum('55') 10 I don't understand yet what the map function does - can you explain? I read the Python 3.3.0 documentation on that topic but I frankly didn't really understand it http://docs.python.org/3/library/functions.html#map. My search for simple code examples using map wasn't really fruitful either. Other than that, I went through each of the 7 alternatives to my Integer to Digit Sum program you guys sent me, I understand what each of those programs does. My favorite one is: def DigSum (integer): s = 0 while integer != 0: integer, remainder = divmod(integer, 10) s += remainder print(s) DigSum(537) It's really a beautiful, elegant solution IMHO and way better than my original code (convert int to string, store each digit in an empty list, then convert them back to int and sum them). If you liked it, I will give you one that uses one less variable :-) def digitSum(n): dsum = 0 while n 0: dsum += n % 10 n /= 10 return dsum Again, thank you all! You are welcome. Asokan Pichai So, if I look into my foggy crystal ball at the future of computing science education, I overwhelmingly see the depressing picture of Business as usual. The universities will continue to lack the courage to teach hard science, they will continue to misguide the students, and each next stage of infantilization of the curriculum will be hailed as educational progress. Edsger W Dijkstra in Dec 1988, in an article titled on the cruelty of really teaching Computer Science Link: http://www.cs.utexas.edu/~EWD/transcriptions/EWD10xx/EWD1036.html ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Converting integers into digit sum (Python 3.3.0)
On Tue, Dec 10, 2013 at 4:06 PM, Asokan Pichai paso...@talentsprint.comwrote: On Tue, Dec 10, 2013 at 3:09 PM, Rafael Knuth rafael.kn...@gmail.comwrote: Hej there, I don't know if everyone would consider this more elegant but it's certainly shorter: Thanks! def DigitSum(YourNumber): ... return sum(map(int, YourNumber)) ... DigitSum('55') 10 I don't understand yet what the map function does - can you explain? I read the Python 3.3.0 documentation on that topic but I frankly didn't really understand it http://docs.python.org/3/library/functions.html#map. My search for simple code examples using map wasn't really fruitful either. Other than that, I went through each of the 7 alternatives to my Integer to Digit Sum program you guys sent me, I understand what each of those programs does. My favorite one is: def DigSum (integer): s = 0 while integer != 0: integer, remainder = divmod(integer, 10) s += remainder print(s) DigSum(537) It's really a beautiful, elegant solution IMHO and way better than my original code (convert int to string, store each digit in an empty list, then convert them back to int and sum them). If you liked it, I will give you one that uses one less variable :-) def digitSum(n): dsum = 0 while n 0: dsum += n % 10 n /= 10 return dsum Again, thank you all! You are welcome. Asokan Pichai So, if I look into my foggy crystal ball at the future of computing science education, I overwhelmingly see the depressing picture of Business as usual. The universities will continue to lack the courage to teach hard science, they will continue to misguide the students, and each next stage of infantilization of the curriculum will be hailed as educational progress. Edsger W Dijkstra in Dec 1988, in an article titled on the cruelty of really teaching Computer Science Link: http://www.cs.utexas.edu/~EWD/transcriptions/EWD10xx/EWD1036.html Stupid of me not to have mentioned that this Python 2.x only. Sorry ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Converting integers into digit sum (Python 3.3.0)
On Mon, Dec 9, 2013 at 1:38 PM, Rafael Knuth rafael.kn...@gmail.com wrote: Hej there, I wrote a program that converts an integer into a digit sum: def DigitSum(YourNumber): DigitList = [] YourNumber = str(YourNumber) for i in YourNumber: DigitList.append(int(i)) print(sum(DigitList)) DigitSum(55) 10 It actually works but I was wondering if that's the only way to solve the task of converting an integer into a digit sum? I learned from past conversations on this mailing list that often times there is a better, more elegant and shorter way to write a program, and I was wondering if that's the case here. Why extract the digit and then store it and then sum it? def digitSum(n): return sum([int(digit) for digit in str(n)]) Or def num2Digits(n): return [int(ch) for ch in str(n)] def digitSum(n): return sum(num2Digits(n)) Asokan Pichai So, if I look into my foggy crystal ball at the future of computing science education, I overwhelmingly see the depressing picture of Business as usual. The universities will continue to lack the courage to teach hard science, they will continue to misguide the students, and each next stage of infantilization of the curriculum will be hailed as educational progress. Edsger W Dijkstra in Dec 1988, in an article titled on the cruelty of really teaching Computer Science Link: http://www.cs.utexas.edu/~EWD/transcriptions/EWD10xx/EWD1036.html ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] how to iterate through a dictionary and assign list values?
On Thu, Dec 5, 2013 at 9:43 AM, Jared Nielsen nielsen.ja...@gmail.comwrote: I want to create a dictionary, assign it keys, then iterate through a for loop and assign the dictionary values from a list. I'm trying this, but it's not working: dictionary = {one, two, three} This creates a set. and NOT a dictionary. Please remember that a dictionary is (unordered) iterable collection of key-value pairs. To initialise a dictionary and give it values you have to do dictionary = { key1:value1, key2:value2} . list = [1,2,3] for key in dictionary: for value in list: dictionary[key] = value I get this error: TypeError: 'set' object does not support item assignment Now I hope the error message makes sense. What am I doing wrong? Any help is greatly appreciated. I am not trying to tell you what to do as that would greatly depend on what you are trying to do. But d = {key:value for key, value in zip(keys, values)} and d = dict(zip(keys, values)) are worth studying. Asokan Pichai So, if I look into my foggy crystal ball at the future of computing science education, I overwhelmingly see the depressing picture of Business as usual. The universities will continue to lack the courage to teach hard science, they will continue to misguide the students, and each next stage of infantilization of the curriculum will be hailed as educational progress. Edsger W Dijkstra in Dec 1988, in an article titled on the cruelty of really teaching Computer Science Link: http://www.cs.utexas.edu/~EWD/transcriptions/EWD10xx/EWD1036.html ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Off Topic re: unichr not working as expected
On Wed, Jul 24, 2013 at 1:50 AM, Steven D'Aprano st...@pearwood.infowrote: On 24/07/13 04:53, Jim Mooney wrote: On 23 July 2013 07:28, Steven D'Aprano st...@pearwood.info wrote: (I trust that everyone remembers enough high school chemistry to understand why Mercurial is called hg? Hg is the chemical symbol for Mercury.) And I recall my high school chemistry teacher claiming the noble gases could never combine, until someone just decided to cook up some Xenon Tetraflouride. Always fun when you get to contradict your teacher in class, and you're right - wel it was then. I'm a tad more mature, now - sometimes ;') Way offtopic: It is Xenon Hexa Flouride IIRC. LOve that book 107 stories about CHemistry Asokan Pichai Expecting the world to treat you fairly because you are a good person is a little like expecting the bull to not attack you because you are a vegetarian ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Regarding python function arguments
On Tue, Jun 11, 2013 at 2:24 PM, Arijit Ukil arijit.u...@tcs.com wrote: i am writing following python function: def my_func (arg1, arg2, arg3): however, I am not always going to pass all the arguments. sometimes only arg1 is passed, sometimes arg1 and arg2 are passed; sometimes arg1, arg2, arg3 are passed. How can i manage this? Look at keyword arguments: http://docs.python.org/release/1.5.1p1/tut/keywordArgs.html BTW, don't you think that the signature attached by your organization is rather unsuitable for this list. For example, do I need an explicit disclaimer from you that you are not sharing company confidential information, if you post a solution? Asokan Pichai Expecting the world to treat you fairly because you are a good person is a little like expecting the bull to not attack you because you are a vegetarian ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] producing PDF files
On Tue, Jun 11, 2013 at 3:23 PM, Khalid Al-Ghamdi emailkg...@gmail.comwrote: Hi, Do you know of a python module for converting text files to PDF format? thanks Reportlab http://www.reportlab.com/software/opensource/ sphinx http://sphinx-doc.org/ is a great choice too. Asokan Pichai Expecting the world to treat you fairly because you are a good person is a little like expecting the bull to not attack you because you are a vegetarian ___ 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] Issue w/ program: Flip a coin and count heads and tails
On Fri, May 24, 2013 at 4:31 PM, Rafael Knuth rafael.kn...@gmail.comwrote: Hello, I am writing a program in Python 3.3.0 which flips a coin 10 x times and then counts the number of heads and tails. It obviously does something else than I intended, and I am wondering what I did wrong: What is that you intended? Please explain that. import random print ( This program flips a coin 10 times. Actually this is wrong. The program does something else. It then counts the number of heads and tails. ) flips = 0 heads = 0 tails = 0 while flips 10: flips = flips + 1 if random.randint(1,2) == 1: heads = heads + 1 print(We've got + str(heads) + heads here. if random.randint(1,2) == 2: tails = tails + 1 print(We've got + str(tails) + tails here.) This is what I get as output: This program flips a coin 10 times. It then counts the number of heads and tails. We've got 1 tails here. We've got 1 heads here. We've got 2 tails here. We've got 2 heads here. We've got 3 tails here. We've got 3 heads here. We've got 4 tails here. We've got 5 tails here. We've got 4 heads here. We've got 6 tails here. We've got 7 tails here. We've got 5 heads here. Is this an actual output??? Did the program stop here at 5 heads and 7 tails? Can anyone help? Thank you so much! All the best, Rafael Asokan Pichai Expecting the world to treat you fairly because you are a good person is a little like expecting the bull to not attack you because you are a vegetarian ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Issue w/ program: Flip a coin and count heads and tails
On Fri, May 24, 2013 at 4:54 PM, Rafael Knuth rafael.kn...@gmail.comwrote: I am writing a program in Python 3.3.0 which flips a coin 10 x times and then counts the number of heads and tails. It obviously does something else than I intended, and I am wondering what I did wrong: What is that you intended? Please explain that. I want that program to flip a coin 10 x times and then count the number of heads and tails. That's very much it. Then you have set up the while loop right. It loops 10 times. But if it is a head you are counting heads. Now if it is a tail you are discarding and tossing again! That is the effect of while flips 10: flips = flips + 1 if random.randint(1,2) == 1: - if it is not head? heads = heads + 1 print(We've got + str(heads) + heads here. if random.randint(1,2) == 2: - this is the second toss I am talking about tails = tails + 1 Now if you replace the second toss by an else and count it as a tail you should go towards the code you are looking for. Try it and tell us how it goes. All the best Asokan Pichai ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Running python from windows command prompt
On Thu, Apr 11, 2013 at 11:38 AM, Arijit Ukil arijit.u...@tcs.com wrote: Thanks for the help. Now I have modifed the code as: import sys def main(argv): data = int(sys.argv[1]) avg = average (data) print Average:, avg def average(num_list): return sum(num_list)/len(num_list) if __name__ == __main__: main(sys.argv[1:]) Two major problems: One: The __main__ methods processes (correctly) the args and drops argv[0] But your main() function is calling sys.argv again Two: sum() and len() expect a list -- more accurately an iterable. when you say data = argv[1] data is a scalar. If you know of list comprehensions, it can be easier or else, think of a function to convert a list of strings (argv[1:] to a list of floats; more general than int) def arg2list(arg): args = [] for a in arg: args.append(float(a)) return args Now replace the data = line with data = arg2list(argv) # NOT sys.argv HTH Asokan Pichai Expecting the world to treat you fairly because you are a good person is a little like expecting the bull to not attack you because you are a vegetarian ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Please Help
On Fri, Mar 22, 2013 at 6:07 PM, Arijit Ukil arijit.u...@tcs.com wrote: I have the following data points. data = [1,2,0,9,0,1,4] I like to store in an array and print the odd-indexed points, i.e. 2, 9,1 (considering index starts at 0) *I have written the following code which is** not **running:* import math number_list = [1,2,0,9,0,1,4] number_list_1 = [] for k in range(math.floor(float(len(number_list)/2))): if (k math.floor(float(len(number_list)/2))): number_list_1[k] = number_list[k*2 + 1] print *'data: '*, number_list_1 Please help Regards, I would suggest that your roblems have more to do with insufficient understanding of basic constructs, and that you should work on them, Learn Python the hard way a book by Zed Shaw is a good one. Why do I say that? Among other things, k math.floor(float(len(number_list)/2)) is very poor in any language. Asokan Pichai The root of all superstition is that men observe when a thing hits, but not when it misses. -- Francis Bacon ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] How to change the char in string for Python
On Feb 24, 2013 4:27 PM, Sudo Nohup sudo.no...@gmail.com wrote: Dear all, I want to change the value of a char in a string for Python. However, It seems that = does not work. Could you help me? Thanks! str = abcd result = [char = 'a' for char in str if char == 'c'] OR: str = 'abcd' for char in str: if char == 'a': char = 'c' OR: str = 'abcd' for i in range(len(str)): if str[i] == 'a': str[i] = 'c' ( Traceback (most recent call last): File stdin, line 3, in module TypeError: 'str' object does not support item assignment ) Look up string replace function. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Please help
I saw the code; I see too many formatting errors: Line No 24 starts a function definition and the next few lines are indented by two spaces, but Line 29 is a print statement that is in line with the def; IOW it completes the function. It is very likely wrong. You are defining functions within functions; again it is very likely to be wrong. My advice, look at PEP 8 and also some sample python code in the tutorial to understand how to format code. Remember: Leading whitespace is syntactically significant HTH Asokan Pichai Religion offers hope against all the strife and misery of the world caused by religions. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Beginner's question
How about this? # Assumption x, y, z are all 0 x, y, z = a = x * (x % 2) b = y * (y % 2) c = z * (z % 2) big = a if big b: big = b if big c big = c if big == 0: print No odd number else: print big, is biggest odd number Asokan Pichai If a language is designed for non-programmers, soon only non-programs get written in it. --- Anonymouse ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] help with homework
[SNIPPED] Always use a while loop in this situation, This is excellent advice. Use a for loop in two situations: 1. Iterating a fixed(known) number of times 2. Iterating through the contents of any container Use a while loop to iterate as long as a condition applies. regardless of whether or not teachers put stupid artificial constraints on your code, such as banning the use of len(). There may be legitimate learning outcomes for a teacher to specify such conditions. In this case, learning to use a counter that is incremented under certain conditions. I would hesitate to condemn in such strong terms without knowing more background. Asokan Pichai ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] help with homework
On Mon, Oct 29, 2012 at 2:28 PM, Alan Gauld alan.ga...@btinternet.com wrote: On 29/10/12 08:37, Asokan Pichai wrote: teachers put stupid artificial constraints on your code, such as banning the use of len(). There may be legitimate learning outcomes for a teacher to specify such conditions. In that case they should think up a scenario that requires the use of the construct that is most appropriate. Teachers should never encourage bad practice(*) and that's what this example does. It's valid to put constraints such as do not use any external modules or to use a specific construct if that's what's being taught. But it's never right to leave the student the freedom to use any solution *except* the one that is most logical and readily available. In this case, learning to use a counter that is incremented under certain conditions. But there are many better cases where that solution is needed rather than using len(). This one just sounds like lazy teaching. (*) Actually enforcing bad practice one to demonstrate the problems can be valid provided its followed immediately by the best practice alternative. As a trainer, I believe using a bad example is WRONG; even to teach how not to write. Better to critique the suggested bad answers and explain why that is bad, rather than enforce a constraint that leads to a bad way and then call it out as bad explain why. That said, it *is* preferable IMO, not use such strong condemnation without knowing full background. Probably by now this is OT, so I should stop now. Asokan Pichai If a language is designed for non-programmers, soon only non-programs get written in it. --- Anonymouse ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] For - if - else loop; print selective output
On Wed, Oct 24, 2012 at 09:27:30PM +0500, Saad Javed wrote: Hi, a = [['jimmy', '25', 'pancakes'], ['tom', '23', 'brownies'], ['harry', '21', 'cookies']] for i in a: if (i[1] == '25' or i[1] == '26'): print 'yes' else: print 'Not found' This prints: yes not found I want it to print yes for each positive match but nothing for a negative match. However if all matches are negative, I want it to print Not found once (That bit the code already does). I do I get it to print yes only in a mix result situation? Saad I am sure you have some answer(s) already. I wanted to add a different solution a = [['jimmy', '25', 'pancakes'], ['tom', '23', 'brownies'], ['harry', '21', 'cookies']] matches = [ i[1] in ('25', '26') for i in a ] ] if not any(matches): print Not found else: for match in matches: if match: print Yes Asokan Pichai -- ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] rounding up to the nearest multiple of 8
If you are doing so many times, it may be worth precomputing the padding for a given length and adding it by a look up on the length. For example: SPACE = ' ' MAX = 1000 TAB = 8 paddding = [ SPACE * (n % TAB) for n in range(MAX) ] . s = padding[len(s)] + s . -- where s is string to be padded Asokan Pichai If a language is designed for non-programmers, soon only non-programs get written in it.--- Anonymouse ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] list comprehension, testing for multiple conditions
On Thu, Aug 23, 2012 at 2:57 AM, Pete O'Connell pedrooconn...@gmail.com wrote: On Thu, Aug 23, 2012 at 4:16 AM, Alan Gauld alan.ga...@btinternet.com wrote: theTextAsListNoVnOrVtOrEmptyLine = [x for x in theTextAsListStripped if vn not in x if vt not in x if x!= ] It's slightly more verbose but it makes the rules more explicit, IMHO. I agree, it seems easier to read when written on multiple lines. I'll do it that way, Thanks Pete You can look at the option of writing a function to do the selection part. If the function is named well and also corresponds to some domain operation or concept it can be very useful. def select(p): if p == : return False return vt In p or vn in p .. selectedLines = [ x for x in TextAsListStripped if select(x) ] .. Asokan Pichai If a language is designed for non-programmers, soon only non-programs get written in it. --- Anonymouse ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Recursive assignment in nested lists
On Sat, Aug 4, 2012 at 12:28 PM, Alonzo Quijote alonzo.quij...@gmail.com wrote: Is there a way to define a function which takes a list (of lists), a position specified by a list of integers [i0,i1,...,in], and a value and returns the result of setting list[i0][i1]...[in]=value The following function works for positions up to length 3 only. Is it possible to write a general function that does this? def setValueAtPosition(list,pos,value): if len(pos)==1: list[pos[0]]=value elif len(pos)==2: list[pos[0]][pos[1]]=value elif len(pos)==3: list[pos[0]][pos[1]][pos[2]]=value return list For example aa=[1,2,[3,4]] setValueAtPosition(aa,[2,0],5) [1, 2, [5, 4]] aa [1, 2, [5, 4]] ___ Seems very odd requirement. Anyway here is one way: --- def setValue(NestedList, pos, value): nl = NestedList for p in pos[:-1]: nl = nl[p] nl[pos[-1]] = value return NestedList - Asokan Pichai If a language is designed for non-programmers, soon only non-programs get written in it. --- Anonymouse ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] group txt files by month
On Tue, Apr 3, 2012 at 9:29 AM, questions anon questions.a...@gmail.com wrote: I think what I am trying to do is relatively easy but can't get my head around how to do it. I have a list of txt files that contain daily rainfall for many years. I would like to produce a list that contains the year-month and the max, min and mean of rainfall for each month. My main question at this stage is how to group the files by each month for each year? They are set out like: r20110101.txt r20110102.txt r20110103.txt r20110104.txt r20110105.txt r20110106.txt r20110107.txt r20110108.txt r20110109.txt r20110110.txt r20110111.txt r20110112.txt r20110113.txt r20110114.txt r20110115.txt r20110116.txt r20110117.txt r20110118.txt and so on for each day for many years. so far I am able to open each file and calculate the max, min and mean for each file (see below) but not sure about grouping to monthly for each year. # - Monthwise = {} # -- MainFolder=rE:/Rainfalldata/ outputFolder=rE:/test/ for (path, dirs, files) in os.walk(MainFolder): path=path+'/' for fname in files: if fname.endswith('.txt'): filename=path+fname f=np.genfromtxt(filename, skip_header=6) print f.max(), f.min(), f.mean() Replace the last two lines with # -- Monthwise[fname[1:7]] = .np.genfromtxt(filename, skip_header=6) # - Now at the end you have a dictionary whose keys are the strings of type '201012' and the values are the f. You can now iterate over the sorted keys of Monthwise and print appropriately [Ideal output etc SNIPPED] HTH Asokan Pichai I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth. -- Umberto Eco ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] New to this list ....
On Fri, Mar 30, 2012 at 9:12 PM, Barry Drake bdr...@crosswire.org wrote: On 30/03/12 16:19, Evert Rol wrote: Not sure. In the sense that you can optimise (refactor) it in the same way you could do with C. Eg: results = [0, 0, 0] flags = [0, 1, 2, 3] for flag in flags: results = getflag(flag, results) That's exactly what I hoped for. I hadn't realised I can initialise a list in one go - it seems that lists work a lot like the arrays I was used to in c. Thanks to the others who took the time to answer. Just now, Asokan's solution is a bit obscure to me - I'll work on that one, but the above is lovely and elegant; and easy to understand. Someone asked about the getflag function - it is: def getflag(thisflag, results): if (thisflag == 2): results[0] += 1 elif (thisflag == 1): In c, I would have used switch and case, but I gather there is no direct equivalent in Python ... But it works as is. -- From Barry Drake - a member of the Ubuntu advertising team. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor and directly index on thisflag results[1] += 1 elif (thisflag == 0): results[2] += 1 return(results) For the specific values it may be simpler to write: def getflag(thisflag, results): results[2- thisflag] += 1 return results Or you may rearrange the meaning of results and write results[thisflag] += 1 HTH Asokan Pichai ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Reading/dealing/matching with truly huge (ascii) files
Did you try loadtxt() from numpy? http://mail.scipy.org/pipermail/scipy-user/2010-August/026431.html the poster above notes that 2.5 million lines and 10 columns takes 3 minutes to load. Asokan Pichai ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] How to convert seconds to hh:mm:ss format
On Fri, Feb 17, 2012 at 3:16 AM, alain Delon racg...@yahoo.com wrote: userName = raw_input(Enter your name ) print hi + userName + . \n seconds = input(Enter the number of seconds since midnight:) hours = seconds/3600 hoursRemain = hours%60 Here is your error minutes = hoursReamain/60 secondsRemain = minutes%60 print hours: + minutes: + seconds I'm going to be crazy. Please give me a hand. Thank you very much. ___ 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] Character Buffer Object Error
Dear Michael Overall I see a few problems. 0. Functions should return values. Not print them 1. Why use enumerate? The code is not using the index anyway 2. The following line appears wrong. new_output = ' '.join(user_input) 3. This line has a very buggy possibility. new_output.replace(char, new_char) Let us say you have 234. First time you will replace 2 with 3, getting 334. And then you will replace the first 3 with 4 getting 434 and finally end up with 534. Of course due to other coding errors this does not come to pass. But your basic idea of using str.replace() is prone to this problem. 4. How are you supposed to treat 9? Anyway back to your problem: I want to find all digits in a string and then increment those digits by 1 and then return the same string with the incremented digits. Pseudocode -- Initialise and outstring (empty) Read the instring character by character if the current character is not a digit append it to outstring else append the transform(current char) to outstring If you can organize your code like this it may be easier HTH Regards Asokan Pichai ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] ploting of a square well
Try changing plot(x, v) to plot(x, v(x)) Asokan Pichai We are all atheists about most of the gods that societies have ever believed in. Some of us just go one god further. – Richard Dawkins ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] ploting of a square well
On Sun, Feb 5, 2012 at 11:16 PM, Asokan Pichai paso...@talentsprint.com wrote: Try changing plot(x, v) to plot(x, v(x)) Asokan Pichai But your v(x) is probably in need of changing. I am answering from a machine with a small screen and no python Hence no definite statements. Asokan Pichai ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] something relevant to array
On Fri, Dec 23, 2011 at 3:31 PM, lina lina.lastn...@gmail.com wrote: Hi, [SNIPPED] 2] I want to combine a series of files like a.txt 1 a 2 a 3 a b.txt 1 b 2 b 3 b into one as: a b a b a b Is this ok? a = [line.split()[1] for line in open('a.txt') if len(line.strip()) == 26] b = [line.split()[1] for line in open('b.txt') if len(line.strip()) == 26] both = zip(a, b) Asokan Pichai ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Need Explanation...
On Sat, Dec 10, 2011 at 1:11 PM, sunil tech sunil.tech...@gmail.com wrote: hi, Consider a list: a = [1,2,3] a simple function, which when called it will append 100 to the list. def app(x): return x.append(100) p = app(a) now list holds appended value [1,2,3,100] but p is empty... why it is? please teach. append() Method is a mutator; it modifies the list. DOES NOT return the modified list; returns None to be exact HTH Asokan Pichai ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] plotting in python
On Thu, Dec 1, 2011 at 2:38 AM, stm atoc stm.at...@googlemail.com wrote: Hi there, I have a question regarding plotting with Python. I have the following python script: [SNIPPED] plot(Conc[0],z) [SNIPPED] ---So, What would you suggest? What is the output of print len(Conc[0]), len(z) You may insert that line above the plot and see Asokan Pichai ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Python code trouble!
Okay! I wrote some code. It is below so that you can avoid scrolling down and seeing it if you do not want to see any code! HTH Asokan people = list( ABCDEFGHIJKLMN) COUNT = len(people) remove = 3 SPACE = ' ' def survivorCount(a): return len(a) - a.count(SPACE) pos = 0 men = 0 while survivorCount(people) != 1: if people[pos] != SPACE: men += 1 if men % remove == 0: print removed, people[pos], at, pos people[pos] = SPACE pos = (pos + 1) % COUNT print ''.join(people).strip() ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Shortening the code
On Wed, Nov 23, 2011 at 2:47 AM, Mic o0m...@hotmail.se wrote: [LOTS OF STUFF SNIPPED] self.chair1.configure(bg=green) os.remove (Hamburg_Dortmund20_00) And now you delete that file you created without having done anything with it? The meaning is that when the button is pressed once, it changes color and creates the file. That means you have booked the chair. If you click the button once more, the button removes the file, and changes color to green which indicates that you have un booked your chair. I hope you understand now why I delete the file :) Often if you [name things]/[write code] in terms of WHAT you want to do, rather than HOW you want to do, you will find the going easier For example, a function that is named *bookChair(chairId)*, inside which you change color to green or whatever is worth considering. HTH Asokan Pichai ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] IndexError: list index out of range
On Tue, Nov 22, 2011 at 4:32 AM, Steven D'Aprano st...@pearwood.infowrote: John wrote: Hi all, I have wriiten the following code: [Segment] def survivor(names, step): index = step - 1 next = names while len(next) 1: next.remove (next[index]) What is the intention of this function? The name given doesn't mean anything to me. The parameters names and step don't seem meaningful. I guess he is trying the Josephus problem. I am guessing from the name! If so, you have to remember that when you delete an item you change the positions of subsequent items. For example, in a 11-element list, say A, if you want to delete every third, the index numbers you *should* delete are 2, 5, 8. But if you delete A[2], then you will delete the original A[6] and then the original A[10]. So you have to think in terms of 'marking' for deletion and later deleting or deleting from the other end. A more interesting possibility is to replicate the original list and append it to itself and delete all occurrences. About 25 years back thats what I did in BASIC and won an honorable mention in a coding contest in a magazine :-) I replaced the cell contents with a space and in subsequent rounds counted non-space items. The first prize was won by a circular(linked-)list in Pascal, with the same repace by Space idea HTH Asokan ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] A recursion question
Another way to do that is to avoid any intermediate variables altogether That may be easier to understand YMMV def counter(mylist, val): if len(mylist == 0): return 0 if mylist[0] == val: return 1 + counter(mylist[1:], val) else: return counter(mylist[1:]) Asokan Pichai ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Clock in tkinter?
On Wed, Nov 16, 2011 at 1:30 AM, Mic o0m...@hotmail.se wrote: Hi! I am new to programming WELCOME! and I hop this question isn’t stupid. A teacher of mine said, The only stupid question is the one you thought of asking but did not ask! Happy learning Asokan Pichai ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] how to remove the coming duplication
I was so miffed at not reading the OP's mail carefully that I wrote a one liner. Ok. Here it goes: def no_adjacent_dup(lst): return [ x for x, y in zip(lst, lst[1:]) if x != y] + [lst[-1]] :-) Enjoyed working that one out; but whether it is a good solution Asokan Pichai ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] how to remove the coming duplication
Bad to reply to my own post. Failed to understand the just remove the coming duplication, not unique the list. Sorry; ignore my ideas Asokan Pichai ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] regexp
IMO the regex is not too bad; I will not use it for this job -- typing a 50+ character string is more painful (and more error prone) than writing 5--10 lines of code. That said, if it made you look at regexes deeply and beyond the simple explanation of what each character (*, ., +) does I think the teacher ended up making you learn something. FInally, the simplest NON-REGEX method is probably isAlphaOrder(s): return sorted(s) == list(s) It is useful learning to add default parameters to this to improve the functionality to case-dependent or case independent modes. Happy learning Asokan Pichai ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Tutor Digest, Vol 92, Issue 127
From: Joel Montes de Oca joelmonte...@gmail.com To: Tutor Python tutor@python.org Subject: [Tutor] Paper Rock Scissors game - User's choice not returned properly Message-ID: 4eaec191.3060...@gmail.com Content-Type: text/plain; charset=iso-8859-1; Format=flowed Hello everyone, The function: ( http://dpaste.com/644857/) def UserChoice ():# The function that returns the choice from the user print 'Please select (P) for paper, (R) for Rock, or (S) for Scissors.' choice = raw_input('What is your selection?:') if choice.lower() not in ('p', 'r','s'): # Converts the user's choice to lowercase and confirms the choice is valid print 'I am sorry, you entered\'' + choice.upper() + '\' which is an invalid response. Please try again.' raw_input('Press Enter to try again.') UserChoice () # If the choice is not valid, run the function over You should use return UserChoice() else: return choice Asokan Pichai SVP - Learning and Development “Faith consists in believing when it is beyond the power of reason to believe. Voltaire http://www.brainyquote.com/quotes/quotes/v/voltaire163832.html ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Tutor Digest, Vol 92, Issue 128
Hugo's explanation is nice and clear. You may also want to look at this way Consider the most simplified form of the issue def alpha(): if X: beta() else: return q Here in the* if branch* nothing is returned while in the *else branch *something is being returned. That is whenever X is True nothing is returned from alpha(). Even if beta() returns something that is not being used. But when X is False something (q in this simplistic example) is being returned So this is a bug. HTH Asokan Pichai SVP - Learning and Development “Faith consists in believing when it is beyond the power of reason to believe. Voltaire http://www.brainyquote.com/quotes/quotes/v/voltaire163832.html ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor