Re: [Tutor] Dictionary get method
Hello Phil, On Wed, Mar 20, 2013 at 12:54 PM, Phil wrote: > Thank you for reading this. > > I'm working my way through a series of exercises where the author only > provides a few solutions. > > The reader is asked to modify the histogram example so that it uses the get > method thereby eliminating the if and else statements. Histogram2 is my > effort. > > The resulting dictionary only contains the default value provided by "get" > and I cannot see how the value can be incremented without an if statement. You are almost there. Note that all you have to do is increment 1 to the current 'value' for the key denoted by c. If you change the line with get() to the following, it works as you want it to: d[c]= 1 + d.get(c, 0) Output: {'a': 1, 'b': 1, 'o': 2, 'n': 1, 's': 2, 'r': 2, 'u': 1, 't': 1} histogram2 {'a': 1, 'b': 1, 'o': 2, 'n': 1, 's': 2, 'r': 2, 'u': 1, 't': 1} You were almost there. Good Luck. -Amit. -- http://amitsaha.github.com/ ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Please Help
Hi Arijit, On Thu, Mar 21, 2013 at 8:42 PM, Arijit Ukil wrote: > > I am new to python. I like to calculate average of the numbers by reading > the file 'digi_2.txt'. I have written the following code: > > def average(s): return sum(s) * 1.0 / len(s) > > f = open ("digi_2.txt", "r+") > > list_of_lists1 = f.readlines() > > > for index in range(len(list_of_lists1)): > > > tt = list_of_lists1[index] > > print 'Current value :', tt > > avg =average (tt) > > > This gives an error: > > def average(s): return sum(s) * 1.0 / len(s) > TypeError: unsupported operand type(s) for +: 'int' and 'str' > > I also attach the file i am reading. > > > > Please help to rectify. The main issue here is that when you are reading from a file, to Python, its all strings. And although, 'abc' + 'def' is valid, 'abc' + 5 isn't (for example). Hence, besides the fact that your average calculation is not right, you will have to 'convert' the string to an integer/float to do any arithmetic operation on them. (If you know C, this is similar to typecasting). So, coming back to your program, I will first demonstrate you a few things and then you can write the program yourself. If you were to break down this program into simple steps, they would be: 1. Read the lines from a file (Assume a generic case, where you have more than one line in the file, and you have to calculate the average for each such row) 2. Create a list of floating point numbers for each of those lines 3. And call your average function on each of these lists You could of course do 2 & 3 together, so you create the list and call the average function. So, here is step 1: with open('digi.txt','r') as f: lines = f.readlines() Please refer to http://docs.python.org/2/tutorial/inputoutput.html#methods-of-file-objects for an explanation of the advantage of using 'with'. Now, you have *all* the lines of the file in 'lines'. Now, you want to perform step 2 for each line in this file. Here you go: for line in lines: number_list = [] for number in line.split(','): number_list.append(float(number)) (To learn more about Python lists, see http://effbot.org/zone/python-list.htm). It is certainly possible to use the index of an element to access elements from a list, but this is more Pythonic way of doing it. To understand this better, in the variable 'line', you will have a list of numbers on a single line. For example: 1350696461, 448.0, 538660.0, 1350696466, 448.0. Note how they are separated by a ',' ? To get each element, we use the split( ) function, which returns a list of the individual numbers. (See: http://docs.python.org/2/library/stdtypes.html#str.split). And then, we use the .append() method to create the list. Now, you have a number_list which is a list of floating point numbers for each line. Now, step 2 & 3 combined: for line in lines: number_list = [] for number in line.split(','): number_list.append(float(number)) print average(number_list) Where average( ) is defined as: def average(num_list): return sum(num_list)/len(num_list) There may be a number of unknown things I may have talked about, but i hope the links will help you learn more and write your program now. Good Luck. -Amit. -- http://amitsaha.github.com/ ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Importing data from a file.
On Thu, Mar 21, 2013 at 11:43 PM, Shall, Sydney wrote: > I have an elementary question provoked by another post today. > > 1. Is it the case that ALL imported data from a file is a string? > 2. Does this therefor imply that said data has to be processed appropriately > to generate the data in the form required by the program? To the best of my knowledge, yes to both of your queries. Once you have the element you want to process, you can make use of the type converting functions (int(), float().. ) and use them appropriately. > 3. Are there defined procedures for doing the required processing? If you meant conversion functions, int() and float() are examples of those. You of course (most of the times) have to make use of string manipulation functions (strip(), rstrip(), etc) to extract the exact data item you might be looking for. So, they would be the building blocks for your processing functions. I hope that makes some things clear. -Amit. -- http://amitsaha.github.com/ ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Building Python 2.7.3 on RHEL 5.8 x86_64 -- Syntax Error
On Wed, Mar 27, 2013 at 12:55 AM, Sean Carolan wrote: > I'm attempting to use setup.py to build an RPM, but ran into this error: > > [scarolan@cobbler:~/rpmbuild/BUILD/Python-2.7.3]$ python27 setup.py > bdist_rpm > > File "setup.py", line 361 > with open(tmpfile) as fp: > ^ > SyntaxError: invalid syntax > error: Bad exit status from /var/tmp/rpm-tmp.8897 (%build) > > It appears the syntax error is striggered when "python setup.py build" is > run from that temporary bash script (/var/tmp/rpm-tmp.8897): Could it be that it is taking the system python executable which is probably 2.4? -Amit. -- http://amitsaha.github.com/ ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Building Python 2.7.3 on RHEL 5.8 x86_64 -- Syntax Error
On Wed, Mar 27, 2013 at 7:32 AM, Sean Carolan wrote: > >> Given that most folks on this list are only learning Python its pretty >> unlikely that they are building bespoke RPMs... >> >> You might find more experience of RPM building on the general Python >> mailing list/newsgroup. > > > Sorry 'bout that. I'll follow up with the bug report and possibly the > general list as well. I am going to try doing this sometime today. I shall let you know if I find a solution or my observations. Best, Amit. -- http://amitsaha.github.com/ ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Building Python 2.7.3 on RHEL 5.8 x86_64 -- Syntax Error
On Wed, Mar 27, 2013 at 7:32 AM, Sean Carolan wrote: > >> Given that most folks on this list are only learning Python its pretty >> unlikely that they are building bespoke RPMs... >> >> You might find more experience of RPM building on the general Python >> mailing list/newsgroup. > > > Sorry 'bout that. I'll follow up with the bug report and possibly the > general list as well. FWIW, I tried the same thing with Python 3 sources on Fedora 18, and got the same error as you. But, where did you get the idea that you could build Python RPMs using $python setup.py bdist_rpm ? I thought that was only limited to building RPMs for python packages (including extensions), but not the Python interpreter itself. Please correct me if i am wrong. Okay, here is something for you to try in the meantime. Download the Python 2.7 SRPM (source RPM) from http://koji.fedoraproject.org/koji/packageinfo?packageID=130. May be the F17 version. Extract it to get the source files, patches and the SPEC file. If you are familiar with building RPM packages by hand, please try building it like any other package. That is, by copying the .spec file to SPECS and the .patch, .xz and other files in SOURCES and then doing rpmbuild -ba python.spec from the SPECS directory. Oh yes, please install the dependencies for building the package first by doing, yum-builddep before doing the build. It seems like it built the RPMs alright on my laptop. See if that helps. Best, Amit. -- http://amitsaha.github.com/ ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] HELP: Creating animation from multiple plots
Hi Sayan, On Wed, Mar 27, 2013 at 4:14 PM, Sayan Chatterjee wrote: > Dear All, > > I am a newbie to Python but have a fair know how of other languages i.e C > etc. > > I want to run an astrophysical simulation in Python. All I have to do it to > generate a set of 'plots' depending on a varying parameter and then stitch > them up. > > 1) Is it possible to automatically generate different data files( say in the > orders of 1000) with different names depending on a parameter? It certainly is. Are you talking about the file names being file_1001.txt, file_1002.txt and so on? If yes, let's say your parameter values are stored in param. Then something like this would do the trick: param_values = [1000,1001, 1005, 2001] for param in param_values: fname = 'file_' + str(param) # write to file fname # # Sorry if its different from what you are looking for. But yes, its certainly possible. > > 2) Is it possible to plot the data sets right from Python itself and save > the plots in different jpeg files to stitched upon later on. It is possible to generate plots and save each as JPEGs. [1]. What do you mean by stitching together? [1] http://stackoverflow.com/questions/8827016/matplotlib-savefig-in-jpeg-format Best, Amit -- http://amitsaha.github.com/ ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] HELP: Creating animation from multiple plots
On Wed, Mar 27, 2013 at 4:23 PM, Amit Saha wrote: > Hi Sayan, > > On Wed, Mar 27, 2013 at 4:14 PM, Sayan Chatterjee > wrote: >> Dear All, >> >> I am a newbie to Python but have a fair know how of other languages i.e C >> etc. >> >> I want to run an astrophysical simulation in Python. All I have to do it to >> generate a set of 'plots' depending on a varying parameter and then stitch >> them up. >> >> 1) Is it possible to automatically generate different data files( say in the >> orders of 1000) with different names depending on a parameter? > > It certainly is. Are you talking about the file names being > file_1001.txt, file_1002.txt and so on? If yes, let's say your > parameter values are stored in param. Then something like this would > do the trick: > > param_values = [1000,1001, 1005, 2001] > > for param in param_values: > fname = 'file_' + str(param) > > ># write to file fname ># ># > > > Sorry if its different from what you are looking for. But yes, its > certainly possible. > > >> >> 2) Is it possible to plot the data sets right from Python itself and save >> the plots in different jpeg files to stitched upon later on. > > It is possible to generate plots and save each as JPEGs. [1]. > > What do you mean by stitching together? You probably meant creating an animation from them. Yes, it is certainly possible. I will try to find a link which makes it really easy to create an animation out of a bunch of images. Which operating system are you on? -Amit. -- http://amitsaha.github.com/ ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] HELP: Creating animation from multiple plots
On Wed, Mar 27, 2013 at 4:36 PM, Sayan Chatterjee wrote: > Thanks a lot for your prompt reply. > > 1. Yes. This is exactly what I wanted. Creating a bunch of data sets and > then writing script to plot them using gnuplot, but if something can produce > directly 'plots' it will certainly be helpful. Yes, indeed it is possible. You may want to explore matplotlib a bit. You can start with this tutorial [1]. [1] http://www.loria.fr/~rougier/teaching/matplotlib/ > > 2. Yes. By stitching them up I meant an animation.Sorry for the ambiguity. > Exactly how we can do it Octave. > > Pls see this link: > http://www.krizka.net/2009/11/06/creating-animations-with-octave/ Right, yes, if you see it uses mencoder/ffmpeg to create the animation. So, if you save your individual plots and then use one of these tools, you should be able to get the animation done. Matplotlib itself seems to have some Animated plotting capabilities, but I haven't had any experience with them. Best, Amit. -- http://amitsaha.github.com/ ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Building Python 2.7.3 on RHEL 5.8 x86_64 -- Syntax Error
On Wed, Mar 27, 2013 at 11:05 PM, Sean Carolan wrote: > >> But, where did you get the idea that you could build Python RPMs using >> $python setup.py bdist_rpm ? I thought that was only limited to >> building RPMs for python packages (including extensions), but not the >> Python interpreter itself. Please correct me if i am wrong. > > > Ok, so it's only for module distributions? I assumed it could package > Python itself as well, because it creates a *.spec file that reads like > this: > > %define name Python > %define version 2.7.3 > %define unmangled_version 2.7.3 > %define release 1 > > Summary: A high-level object-oriented programming language Hmm. Let's see, it was a guess on my part as well. > >> >> Okay, here is something for you to try in the meantime. Download the >> Python 2.7 SRPM (source RPM) from >> http://koji.fedoraproject.org/koji/packageinfo?packageID=130. May be >> the F17 version. >> Extract it to get the source files, patches and the SPEC file. > > > Thank you, I will try this today. In the meantime I have started a thread > on the "distutils" mailing list, so as not to spam "Tutor" with my build > woes. I will follow the thread there and see what comes out of it. This is interesting! FWIW, I tried to get the SRPM and build Python 2.7 on RHEL 5. Quickly realized that it lacks, yum-builddep, yumdownloader, etc :-/ So, just left it there for then. I will have to try again the manual way. -Amit. -- http://amitsaha.github.com/ ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] How to check if user input is an integer
On Fri, Mar 29, 2013 at 9:33 PM, Ghadir Ghasemi wrote: > Hi guys I am trying to create part of a vending machine. The section below is > if the user wants to insert 50p coins. It works but when I entered a non > integer like 'dfsdf', the program just broke. Is there a way that the program > can check if the input is an integer, and if it is, then the program does all > the calculations, but if it isn't the program just keeps asking for an input? > Thanks. Here is the section. > > fiftypencecoins = int(input("how many 50p coins do you want to insert or > press 'e' to exit : ")) > if fiftypencecoins == 'e': > break > else: > currentmoney += fiftypencecoins * 5/10 > print("your newly updated credit is £" + str(currentmoney) + "0") Is this Python 3 or Python 2 ? -Amit. -- http://amitsaha.github.com/ ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] How to check if user input is an integer
On Fri, Mar 29, 2013 at 9:39 PM, Amit Saha wrote: > On Fri, Mar 29, 2013 at 9:35 PM, Amit Saha wrote: >> On Fri, Mar 29, 2013 at 9:33 PM, Ghadir Ghasemi >> wrote: >>> Hi guys I am trying to create part of a vending machine. The section below >>> is if the user wants to insert 50p coins. It works but when I entered a non >>> integer like 'dfsdf', the program just broke. Is there a way that the >>> program can check if the input is an integer, and if it is, then the >>> program does all the calculations, but if it isn't the program just keeps >>> asking for an input? Thanks. Here is the section. >>> >>> fiftypencecoins = int(input("how many 50p coins do you want to insert or >>> press 'e' to exit : ")) >>> if fiftypencecoins == 'e': >>> break >>> else: >>> currentmoney += fiftypencecoins * 5/10 >>> print("your newly updated credit is £" + str(currentmoney) + "0") >> >> Is this Python 3 or Python 2 ? > > May be that's not relevant. So anyway, if you want to see whether the > int() function will be successful on your input, you need to check > whether the input constitutes of only digits. > > I can think of two ways: > > 1. Easy and naive way: for each character in the input, check whether > it is between [0-1] Oh lord. That should be [0-9]. Sorry. -- http://amitsaha.github.com/ ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] How to check if user input is an integer
On Fri, Mar 29, 2013 at 9:35 PM, Amit Saha wrote: > On Fri, Mar 29, 2013 at 9:33 PM, Ghadir Ghasemi > wrote: >> Hi guys I am trying to create part of a vending machine. The section below >> is if the user wants to insert 50p coins. It works but when I entered a non >> integer like 'dfsdf', the program just broke. Is there a way that the >> program can check if the input is an integer, and if it is, then the program >> does all the calculations, but if it isn't the program just keeps asking for >> an input? Thanks. Here is the section. >> >> fiftypencecoins = int(input("how many 50p coins do you want to insert or >> press 'e' to exit : ")) >> if fiftypencecoins == 'e': >> break >> else: >> currentmoney += fiftypencecoins * 5/10 >> print("your newly updated credit is £" + str(currentmoney) + "0") > > Is this Python 3 or Python 2 ? May be that's not relevant. So anyway, if you want to see whether the int() function will be successful on your input, you need to check whether the input constitutes of only digits. I can think of two ways: 1. Easy and naive way: for each character in the input, check whether it is between [0-1] 2. Use regular expressions: http://docs.python.org/2/library/re.html -Amit. -- http://amitsaha.github.com/ ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] (no subject)
On Sun, Mar 31, 2013 at 11:49 AM, Soliman, Yasmin wrote: > Hello everyone. How can I get a program to stop only when the user enters > 'Quit'? You would need an "infinite" loop in your program, where you take user input. Check if the input entered was 'Quit', and only exit/break out of your loop then, else continue doing something else. HTH, -Amit. -- http://amitsaha.github.com/ ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] Fwd: (no subject)
Sorry, forgot to have tutor in the CC. On Sun, Mar 31, 2013 at 12:08 PM, Soliman, Yasmin wrote: > Sure here it is: > > import weekday_string1 > while True: > ryear = raw_input("year= ") > print ryear > if not ryear.isdigit(): > print '\nThank you for using this program! Bye.' > break if ryear == 'Quit': print '\nThank you for using this program! Bye.' break This will exit out of the While loop. So, if you have code after the while loop, they will be executed. If you want to completely exit the program, use the sys.exit() function from the sys module. Does that help? -Amit. -- http://amitsaha.github.com/ ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] FW: Fwd: (no subject)
On Sun, Mar 31, 2013 at 12:51 PM, Soliman, Yasmin wrote: > yes, your program does work. The problem is if I run that similar statment in > my program, say I enter the year and for month I write Quit, it says quit is > not defined. I suppose in this senerio I would have to use the sys.exit()? Do you mean that you want to quit if *any* of your inputs is given as 'Quit' ? The something like this should work: import weekday_string1 while True: ryear = raw_input("year= ") print ryear if ryear=='Quit': print '\nThank you for using this program! Bye.' break else: year = int(ryear) month = raw_input("month= ") day = raw_input("day= ") if month=='Quit' or day == 'Quit': break wd = weekday_string1.weekday_string(year, int(month), int(day)) print "The given date: %2d/%2d/%4d is a %s." % (month, day, year, wd) print "==" Couple of things here: 1. I have used raw_input() to take the input for month and day as well (Why? See the differences between input() and raw_input(): http://echorand.me/2012/10/11/input-and-raw_input-in-python/) 2. Since raw_input() returns its input as a string, I use the int() function when I call your weekday_string() function with month and date. Does that help? -Amit. -- http://amitsaha.github.com/ ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] FW: Fwd: (no subject)
On Sun, Mar 31, 2013 at 12:39 PM, Soliman, Yasmin wrote: > So if it should look like this, it gives error that says Quit is not defined, > also why does it not recognize the sys import when I run it? > > import weekday_string1 > import sys > while True: > ryear = raw_input("year= ") > print ryear > > if ryear == 'Quit': > print '\nThank you for using this program! Bye.' > break Okay, here is a small program: while True: ryear = raw_input("year= ") print ryear if ryear == 'Quit': print '\nThank you for using this program! Bye.' break else: print 'Not quitting' When I run this, I see: year= 10 10 Not quitting year= 10 10 Not quitting year= 20 20 Not quitting year= Quit Quit Thank you for using this program! Bye. As you can see, when I enter "Quit", it exists. Can you try and see if that works for you? Best, Amit. -- http://amitsaha.github.com/ ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] FW: Fwd: (no subject)
On Sun, Mar 31, 2013 at 1:14 PM, Soliman, Yasmin wrote: > Yes this does help. I'm going to play around with it a bit, thank you so much > for your patience and time! Great. Good Luck! ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] building a website with python
On Wed, Apr 10, 2013 at 12:03 PM, Don Jennings wrote: > > On Apr 9, 2013, at 5:31 PM, Benjamin Fishbein wrote: > >> Hello. I learned Python this past year (with help from many of you) and >> wrote many programs for my small business. Now I want to build a website. I >> acquired the domain name through godaddy.com (bookchicken.com) but have not >> found hosting yet. >> I learned html, css, and javascript via codeacademy.org, but have never >> built a website. >> I would like to build it with Python, > > So, are you really just wanting to use python to build a static site? If so, > you can run a python web framework on your local machine and then deploy the > static files to any decent host you find. For example, there are instructions > for setting up this scenario using flask, jinja2 and markdown[1]. If you have > experience with ReStructuredText (here's a comparison of the two markups > [2]), it's fairly easy to use docutils to produce the html files. Good suggestion. I wrote this article showing how you can do that using Sphinx. Please take a look [1]. The advantage of using something like Sphinx is that it gives you static HTML, which you can simply copy and paste. As you will see in the article, it is also very easy to upload your HTML to GitHub pages. [1] http://amitsaha.github.io/site/notes/articles/sphinx/static_html.html Hope it is a solution which suits you. Also, getting familiar with Sphinx may also help you in your future Python projects - since it is *the* de-facto standard for documenting Python projects. Best, Amit. -- http://amitsaha.github.com/ ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] building a website with python
On Wed, Apr 10, 2013 at 7:31 AM, Benjamin Fishbein wrote: > Hello. I learned Python this past year (with help from many of you) and wrote > many programs for my small business. Now I want to build a website. I > acquired the domain name through godaddy.com (bookchicken.com) but have not > found hosting yet. > I learned html, css, and javascript via codeacademy.org, but have never built > a website. > I would like to build it with Python, and was wondering if you could give me > some pointers about what I need to learn first: Django is the thing to use? > And do I need specific hosting to use python or are all hosts basically the > same. Django is great, but like others have suggested, so called "micro" frameworks may be a good start. I personally would suggest Flask [1]. The documentation is extensive and excellent. [1] http://flask.pocoo.org/docs/ -Amit. -- http://amitsaha.github.com/ ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] building a website with python
On Wed, Apr 10, 2013 at 12:47 PM, Amit Saha wrote: > On Wed, Apr 10, 2013 at 7:31 AM, Benjamin Fishbein > wrote: >> Hello. I learned Python this past year (with help from many of you) and >> wrote many programs for my small business. Now I want to build a website. I >> acquired the domain name through godaddy.com (bookchicken.com) but have not >> found hosting yet. >> I learned html, css, and javascript via codeacademy.org, but have never >> built a website. >> I would like to build it with Python, and was wondering if you could give me >> some pointers about what I need to learn first: Django is the thing to use? >> And do I need specific hosting to use python or are all hosts basically the >> same. > > Django is great, but like others have suggested, so called "micro" > frameworks may be a good start. I personally would suggest Flask [1]. > The documentation is extensive and excellent. > > > [1] http://flask.pocoo.org/docs/ And, I will add Frozen-Flask (http://pythonhosted.org/Frozen-Flask/), which basically gives you a set of static files, which you can just dump on any host with no "special" features. I haven't tried it myself, though. -Amit. -- http://amitsaha.github.com/ ___ 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 Wed, Apr 10, 2013 at 10:32 PM, Arijit Ukil wrote: > I like to run a python program "my_python.py" from windows command prompt. > This program ( a function called testing) takes input as block data (say > data = [1,2,3,4] and outputs processed single data. > > import math > > def avrg(data): >return sum(data)/len(data) > > def testing (data): >val = avrg(data) >out = pow(val,2) >return out > > I am using python 2.6. My intention is to run from windows command prompt as Why not Python 2.7 or Python 3.3 ? > > python my_python.py 1 3 2 > > However I am getting error: No such file in the directory, Errno 21 Have you set the Windows Path variable correctly? Do you see IDLE in your programs menu? -Amit. -- http://amitsaha.github.com/ ___ 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 Wed, Apr 10, 2013 at 10:32 PM, Arijit Ukil wrote: > I like to run a python program "my_python.py" from windows command prompt. > This program ( a function called testing) takes input as block data (say > data = [1,2,3,4] and outputs processed single data. > > import math > > def avrg(data): >return sum(data)/len(data) > > def testing (data): >val = avrg(data) >out = pow(val,2) >return out > > I am using python 2.6. My intention is to run from windows command prompt as > > python my_python.py 1 3 2 I am hoping this is not your complete program. What tutorial are you following? Can you please paste complete programs? -Amit. -- http://amitsaha.github.com/ ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] Sharing Code Snippets
Hello everyone, I am not sure if this has been shared on this list. However, to help both those seeking help and those wanting to help, may I suggest that for all of you posting your programs, how about using a service such as GitHub's Gists [1]. It allows you to post entire programs with advantages such as intact code formatting, syntax highlighting and perhaps others such as version control. I hope that's a useful suggestion. [1] https://gist.github.com/ Best, Amit. -- http://amitsaha.github.com/ ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Sharing Code Snippets
On Thu, Apr 11, 2013 at 9:33 PM, Albert-Jan Roskam wrote: >> Subject: [Tutor] Sharing Code Snippets >> >> Hello everyone, >> >> I am not sure if this has been shared on this list. However, to help >> both those seeking help and those wanting to help, may I suggest that >> for all of you posting your programs, how about using a service such >> as GitHub's Gists [1]. It allows you to post entire programs with >> advantages such as intact code formatting, syntax highlighting and >> perhaps others such as version control. >> >> I hope that's a useful suggestion. >> >> [1] https://gist.github.com/ > > Hi, > > Is this better than e.g. http://www.pastebin.com/? I wouldn't like it if the > emails contain *only* links to such sites. > That way the information is lost forever if github decides to remove the > code. Often these sites have expiration > dates for their contents. GitHub's Gists doesn't have an expiration date, since its primary purpose is not a paste bin. But yes, I understand that if GitHub decides to remove this service some day, the code is lost. -Amit. > > Albert-Jan -- http://amitsaha.github.com/ ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Looks like a judgment bug.
On Thu, Apr 11, 2013 at 8:41 PM, w qj wrote: > I found this under Windows Python3 l="http://f/"; l[-1] is not '/' > False > > and this under Linux Python3 l = "http://ff.f/"; l[-1] > '/' l[-1] is not '/' > True > > It's Looks like a python bug? No, this is not. The 'is' and 'is not' tests in Python are for checking the identities of Python objects - a string, a single character, a single number, everything is an object. So for example: >>> a=1 >>> b=1 >>> a is b True >>> id(a) == id(b) True When you perform the check, 'a is b', you are actually checking id(a) == id(b). In this case, since I am really referring to the same object, 1 with two different bindings - the identifier is the same. In your case, the check 'failed' on Windows and 'passed' on Linux, is because in one case, the identifiers were the same, and in another case it wasn't. So, when are identifiers same and when not? That depends on the type of object - mutable or immutable. You may want to read up on Python's data model to learn more about this. Also, more on "string interning" here. [1] [1] http://stackoverflow.com/questions/15541404/python-string-interning HTH, Amit. -- http://amitsaha.github.com/ ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Looks like a judgment bug.
On Fri, Apr 12, 2013 at 1:36 PM, Steven D'Aprano wrote: > On 12/04/13 12:53, Amit Saha wrote: > >> So for example: >> >>>>> a=1 >>>>> b=1 >>>>> a is b >> >> True >>>>> >>>>> id(a) == id(b) >> >> True > > > > This is not a very good example, because that behaviour itself is > implementation-dependent and not guaranteed. For example, in IronPython 2.6 > I get completely different behaviour: > >>>> a = 1 >>>> b = 1 >>>> a is b > > False >>>> >>>> print id(a), id(b) > > 43 44 > > > Even in CPython, the implementation you are probably using, the behaviour > will depend on all sorts of factors, such as the type of the object, and > even the value: > > py> a = 10001 > py> b = 10001 > py> a is b > False > > py> a = 1.0 > py> b = 1.0 > py> a is b > False > > > > > >> So, when are identifiers same and when not? That >> depends on the type of object - mutable or immutable. > > > No, not really. The best you can say is this: > > If Python has a choice between creating a new object, and re-using an > existing object, and the object is mutable, Python will never re-use the > object since that might introduce bugs. If the object is immutable, Python > *may* re-use it, or it may not. Indeed. My point was to give the original poster at least *some* idea of what the issue really is. If he/she takes that hint and experiments, reads the Python data model, and finds something weird with that statement - he/she will discover the finer/exactly correct details. So, thanks for clarifying this. > > > When does Python have a choice between re-using existing objects? That's a > complicated question, and there's no straightforward answer. The best I can > do is give some examples: > > > # References to a name will ALWAYS use the same object: > x is x # always True > > > # References to another identifier MIGHT re-use the same object: > x.attr is x.attr # sometimes True, sometimes False > x[index] is x[index] # the same > > > # References to a literal MIGHT re-use the same object, if it is immutable: > 'x' is 'x' # might be True > ['x'] is ['x'] # always False > > > # The same literal on the same line of code MIGHT be re-used: > x = 123.5; y = 123.5; x is y # might be True > > # ...even if they aren't re-used when on separate lines. > x = 123.5 > y = 123.5 > x is y # probably will be False > > > # If two or more identifiers are assigned to a value at the same time, > # Python GUARANTEES to use the same object: > x = y = anything_you_like() > x is y # always True > > > # Assignment in general never makes a new object: > x = something() > y = x > x is y # always True[1] > > > Object identity is almost never important. About the only time it is > important is when comparing things to None. > > But in practice, you can expect (but not rely on!) CPython to re-use the > following: > > * Small integers. Which values count as small depend on the version, but -1 > to 100 is common. > > * Strings that look like identifiers, e.g. "x", "item", but not "hello > world" or "?". The link to the SO question discusses string interning to some detail. > > But don't rely on this, as it is not guaranteed and could go away at any > time. Yes, the 'is' check shouldn't really be relied on checks such as those for None objects. -Amit. -- http://amitsaha.github.com/ ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Looks like a judgment bug.
On Fri, Apr 12, 2013 at 1:42 PM, Amit Saha wrote: > On Fri, Apr 12, 2013 at 1:36 PM, Steven D'Aprano wrote: >> On 12/04/13 12:53, Amit Saha wrote: >> >>> So for example: >>> >>>>>> a=1 >>>>>> b=1 >>>>>> a is b >>> >>> True >>>>>> >>>>>> id(a) == id(b) >>> >>> True >> >> >> >> This is not a very good example, because that behaviour itself is >> implementation-dependent and not guaranteed. For example, in IronPython 2.6 >> I get completely different behaviour: >> >>>>> a = 1 >>>>> b = 1 >>>>> a is b >> >> False >>>>> >>>>> print id(a), id(b) >> >> 43 44 >> >> >> Even in CPython, the implementation you are probably using, the behaviour >> will depend on all sorts of factors, such as the type of the object, and >> even the value: >> >> py> a = 10001 >> py> b = 10001 >> py> a is b >> False >> >> py> a = 1.0 >> py> b = 1.0 >> py> a is b >> False >> >> >> >> >> >>> So, when are identifiers same and when not? That >>> depends on the type of object - mutable or immutable. >> >> >> No, not really. The best you can say is this: >> >> If Python has a choice between creating a new object, and re-using an >> existing object, and the object is mutable, Python will never re-use the >> object since that might introduce bugs. If the object is immutable, Python >> *may* re-use it, or it may not. > > Indeed. My point was to give the original poster at least *some* idea > of what the issue really is. If he/she takes that hint and > experiments, reads the Python data model, and finds something weird > with that statement - he/she will discover the finer/exactly correct > details. So, thanks for clarifying this. > > >> >> >> When does Python have a choice between re-using existing objects? That's a >> complicated question, and there's no straightforward answer. The best I can >> do is give some examples: >> >> >> # References to a name will ALWAYS use the same object: >> x is x # always True >> >> >> # References to another identifier MIGHT re-use the same object: >> x.attr is x.attr # sometimes True, sometimes False >> x[index] is x[index] # the same >> >> >> # References to a literal MIGHT re-use the same object, if it is immutable: >> 'x' is 'x' # might be True >> ['x'] is ['x'] # always False >> >> >> # The same literal on the same line of code MIGHT be re-used: >> x = 123.5; y = 123.5; x is y # might be True >> >> # ...even if they aren't re-used when on separate lines. >> x = 123.5 >> y = 123.5 >> x is y # probably will be False >> >> >> # If two or more identifiers are assigned to a value at the same time, >> # Python GUARANTEES to use the same object: >> x = y = anything_you_like() >> x is y # always True >> >> >> # Assignment in general never makes a new object: >> x = something() >> y = x >> x is y # always True[1] >> >> >> Object identity is almost never important. About the only time it is >> important is when comparing things to None. >> >> But in practice, you can expect (but not rely on!) CPython to re-use the >> following: >> >> * Small integers. Which values count as small depend on the version, but -1 >> to 100 is common. >> >> * Strings that look like identifiers, e.g. "x", "item", but not "hello >> world" or "?". > > The link to the SO question discusses string interning to some detail. > >> >> But don't rely on this, as it is not guaranteed and could go away at any >> time. > > Yes, the 'is' check shouldn't really be relied on checks such as those > for None objects. Correction: Yes, the 'is' check shouldn't really be relied on checks other than checks for None objects (for example). -- http://amitsaha.github.com/ ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Python Script: Downloading Youtube videos by search result
On Fri, Apr 19, 2013 at 9:44 PM, Sayan Chatterjee wrote: > Dear All, > > I want to download some music from youtube.There are already marvellous > python scripts like youtube-dl which downloads videos and playlists from > numerous sites,but what I want to do is to download videos from youtube with > a search string. The user will give a search string, and the script will > download first 20(say) videos from the youtube.The script will use > youtube-dl on the backend and avconv tool for video to MP3 conversion etc. > > How should I proceed to make such a script. I am a newbie in Python but I am > sure with your guidance I can pick it up quite fast. :) May be take a look at the YouTube Data API? [1] Hopefully, the Getting Started section will help you [2]. [1] https://developers.google.com/youtube/1.0/developers_guide_python#SearchingVideos [2] https://developers.google.com/youtube/1.0/developers_guide_python#GettingStarted Best, Amit. -- http://amitsaha.github.com/ ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Processing Linux command line output
Hi Gareth, On Thu, Apr 25, 2013 at 8:03 AM, Gareth Allen wrote: > Hi all, > > I'm trying to get the output of a command and split it into a list that I > can process. What is the best way to go about doing this? In bash I would > use tools like grep, sed awk etc. > > Here's an example: > > ifconfig > > loLink encap:Local Loopback > inet addr:127.0.0.1 Mask:255.0.0.0 > inet6 addr: ::1/128 Scope:Host > UP LOOPBACK RUNNING MTU:16436 Metric:1 > RX packets:84253 errors:0 dropped:0 overruns:0 frame:0 > TX packets:84253 errors:0 dropped:0 overruns:0 carrier:0 > collisions:0 txqueuelen:0 > RX bytes:11763964 (11.2 MiB) TX bytes:11763964 (11.2 MiB) > > I would like to end up with something like this in a file: > > ,lo,rx_errors=0,rx_dropped=0,rx_overruns=0,rx_frame=0 I think there are two parts to your question: 1. How to execute a command and get its output? 2. How to process that output to get the desired information using text processing/etc? I will start by first discussing (1). You will find one of the functions in the 'subprocess' module useful for this. For example, the subprocess.check_output() function [1] executes your command and returns the output as a byte string. Coming to your second questions, once you have the string, you can then use string functions on it to extract the information you want. Things like indexing, slicing, stripping and splitting becomes useful then. Let's see a simple example. 'who -b' command returns the system boot time: $ who -b system boot 2013-04-13 09:00 Now, let's see how we can extract the date + time only from the above output. First, we execute the command and store the output in 'output': >>> output = subprocess.check_output(['who','-b']) The result you get will be something like this: >>> output ' system boot 2013-04-13 09:00\n' Note there are leading whitespaces and a trailing newline. So we will remove it: >>> output = output.strip() >>> output 'system boot 2013-04-13 09:00' Now, we need to extract the date and time, leaving the string out. Let's 'tokenize' it: >>> output.split() ['system', 'boot', '2013-04-13', '09:00'] So, now you have a list of which the 3rd and 4th items are the date and time respectively: >>> output.split()[2:] ['2013-04-13', '09:00'] You can combine all the operations into: >>> subprocess.check_output(['who','-b']).strip().split()[2:] ['2013-04-13', '09:00'] Well, that was a very simple example. A lot of things you will end up doing will however involve operations such as above. You can also use the 're' module to use regular expressions to retrieve information perhaps more intelligently [2]. If you are interested for some related examples, I would like to point you to couple of Python modules I was putting together [3]. In readproc.py, I am extracting information from /proc and in pylinux.py you will see a number of examples showing extracting information from 'subprocess.check_output()' calls. I put together a list of resources to help someone who may be interested in such tasks as yours for an article of mine. Here it is [4]. [1] http://docs.python.org/2/library/subprocess.html#subprocess.check_output [2] http://docs.python.org/2/library/re.html [3] https://github.com/amitsaha/pylinux/tree/master/pylinux [4] https://gist.github.com/amitsaha/4964491 Hope that helps. Best,Amit. -- http://amitsaha.github.com/ ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] changing list element in loop
On Sat, Apr 27, 2013 at 7:49 PM, Jim Mooney wrote: > Why isn't 'e' changing to 'pP here when the vowel list is mutable: > > vowelList = list('aeiouy') > > for x in vowelList: > if x == 'e': > x = 'P' This is because x is really a label for the item in your list. It does not represent a reference to the position of element as it occurs in the list. For example: >>> a= ['a','e','i'] In the above list, a[0] is 'a', a[1] is 'e' and so on. So, if you want to change the character 'e' above to 'o', you will have to do: >> a[1] = 'o' >>> a ['a','o','i'] Hope that helps. You may find the enumerate() function useful in this case: http://docs.python.org/2/library/functions.html#enumerate Best, Amit. > > print(vowelList) > > #result: ['a', 'e', 'i', 'o', 'u', 'y'] > > -- > Jim Mooney > ___ > Tutor maillist - Tutor@python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor -- http://echorand.me ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] changing list element in loop
On Sat, Apr 27, 2013 at 8:31 PM, Jim Mooney wrote: > On 27 April 2013 02:55, Amit Saha wrote: >> On Sat, Apr 27, 2013 at 7:49 PM, Jim Mooney wrote: >>> Why isn't 'e' changing to 'pP here when the vowel list is mutable: >>> >>> vowelList = list('aeiouy') >>> >>> for x in vowelList: >>> if x == 'e': >>> x = 'P' >> >> This is because x is really a label for the item in your list. It does >> not represent a reference to the position of element as it occurs in >> the list. For example: > > > Okay, I tried enumerate, but now I get an "immutable" error. So let's > turn this around since it's getting out of hand for a simple list > replacement ;') What's the simplest way to go through a list, find > something, and replace it with something else? > > vowels = 'aeiouy' > vlist = enumerate(vowels) > for x in vlist: > if x[1] == 'e': > x[0] = 'P' > > print(vowels) > #'tuple' object does not support item assignment The enumerate function returns you a tuple consisting of the 'index' of the element and the element itself. So, you have to store the two values individually. For example, here is what I did to achieve what you want to: >>> x=['a','e','i'] >>> for index, item in enumerate(x): if item == 'e': x[index]='P' >>> x ['a', 'P', 'i'] In your attempt you were attempting to change the 'tuple' itself, which is not what you want and which is not possible - tuples are immutable. I hope that makes things a little clearer? Best, Amit. -- http://echorand.me ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] exit message
On Mon, May 6, 2013 at 2:24 PM, Jim Mooney wrote: > I've noticed that if you exit() a program you always get a traceback message: > Traceback (most recent call last): > File "", line 1, in > exit('what now?') > File "C:\Python33\lib\site.py", line 380, in __call__ > raise SystemExit(code) > > What if you just want to exit for some normal reason and don't want > the message? Or is a program always supposed to end in some normal way > without an exit. Or is there a different, more graceful way to end a > program when you want? Something like this? >> import sys >>> while 1: ... sys.exit('Exiting from Infinite Loop') ... Exiting from Infinite Loop -Amit. -- http://echorand.me ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] exit message
On Mon, May 6, 2013 at 2:56 PM, Jim Mooney wrote: >> Something like this? >> import sys > while 1: >> ... sys.exit('Exiting from Infinite Loop') >> ... >> Exiting from Infinite Loop > > I still get a traceback message from the console. I just want a clean > exit without that. I have a feeling I'm thinking about something the > wrong way ;') > > Traceback (most recent call last): > File "c:\Python33\Progs\fileActions.py", line 17, in > builtins.SystemExit: you messed up too many times Strange. Can you share some relevant code that can be executed? -- http://echorand.me ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] PyScripter header?
On Wed, May 8, 2013 at 6:10 PM, Jim Mooney wrote: > I'm trying PyScripter instead of Wing 101. It works fine and has a lot > more PyLearner features than Wing 101 (at the same price ;'), such as > popups showing the parameters for methods, profiler, lint, > programmable snippets, etc. It also lets you choose your Python > version and finds the right one, which is handy, since I'm learning on > 3.3 but a lot of good stuff is older. > > However, a new file in PyScripter always starts with: > _ > > def main(): > pass > > if __name__ == '__main__': > main() > _ This allows you to write your program in such a way that main() is called only when you are running it as a standalone script. If you import your program in another program, the condition: if __name__=='__main__' evaluates to False and hence your main() function is not called. If you had written your program like this: def main(): pass main() Your main() function would be called in both cases. Some good answers here [1]. [1] http://stackoverflow.com/questions/419163/what-does-if-name-main-do > > What is that stuff? I thought I was getting away from all this > business of defining a main entry point. I don't see it in any of the > Py library files or other Py programs. Yes, it just a case of you defining the entry point..you are not required to. HTH, Amit. -- http://echorand.me ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Unknown Cause of Error
On Sat, May 11, 2013 at 12:13 PM, Jack Little wrote: > I have a slight problem. My program will not open. On top of that, I have > written similar programs all to no avail. I am creating a text adventure and > want there to be different rooms. Here is my code: > > > def menu(): > print "Welcome to Tomb Explorer!" > print "A game of Exploration from Bulldog Development" > print "Press [1] to Play or [2] to Exit" > menu1=raw_input(" >> ") > if menu1== "2": > quit() > if menu1== "1": > room1() > menu() You are not calling your function: menu(). Just move the menu() ( your last line) to the left: def menu(): print "Welcome to Tomb Explorer!" print "A game of Exploration from Bulldog Development" print "Press [1] to Play or [2] to Exit" menu1=raw_input(" >> ") if menu1== "2": quit() if menu1== "1": room1() menu() HTH,Amit. -- http://echorand.me ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Making a Primary Number List generator
On Sun, May 12, 2013 at 9:43 PM, Dave Angel wrote: > On 05/11/2013 09:58 PM, Daniel Magruder wrote: > > Please respond to the list, not the individual. Otherwise you're robbing > yourself and others of the possibility of learning from and helping multiple > people. I don't mind if you ALSO reply to me (which is what reply-all does > by default), but many people do object. In Thunderbird, you normally just > do Reply-list, and it does the right thing. But with other email programs, > you might do reply-all, and remove whichever recipients you don't need. > > > Anybody else want to recommend a tutorial for someone who has no programming > experience in other languages? I thought "Python for Kids" was a great book. The first "half" of the book teaches the Python basics while focusing on writing games in the second. I think it's worth a look. No starch press: http://nostarch.com/pythonforkids Amazon: http://www.amazon.com/Python-Kids-Playful-Introduction-Programming/dp/1593274076 -Amit. -- http://echorand.me ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Python Programming for the Absolute Beginner
Hi Grace, On Thu, May 2, 2013 at 8:04 AM, Grace Kathryn wrote: > Hello~ > > I'm working through the Book Python Programming for the Absolute Beginner > and am wondering if you could help me out with the coding to certain > Challenges at the end of the book, specifically chapter 7 challenges 1 and > 2 and chapter 8 challenges 1 and 3. > Could you help? I need something to compare my coding to. > Welcome. I am sure somebody will be able to help you out. However, you would need to tell what exactly the challenges are and if possible, any specific problem you are facing for someone to help you. Not all of the members in this list may have access to the book. Best, Amit. > > Thank you! > > ~Grace > Sent from my iPad > > ___ > Tutor maillist - Tutor@python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > -- http://echorand.me ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Random Number Game: Returns always the same number - why?
Hi Rafael, On Tue, May 21, 2013 at 2:51 AM, Rafael Knuth wrote: > > Your variable assignment for Random_Number is outside of your while > loop. Therefore its value never changes. Put it inside the while loop > just before the print statement and I think you will get what you > > That was it! Thank you, you made my day, Bob :-) Here is a visualization of how the lines of your original code are executed: http://goo.gl/uRRTu. Click on the "Forward" button there to see the next line of code that is executed. You will see that in your original code, the statement: "Random_Number = random.randint(1, 100)" which actually generates your random numbers is executed only once. Hope that helps your understanding. Best, Amit. -- http://echorand.me ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Which version of python should i use?
Hello Amal, On Mon, May 20, 2013 at 11:24 PM, Amal Thomas wrote: > Thank you very much..!! I am starting to learn python for my Bioinformatics > work, so I would look for the version that has libraries helpful for me.. Do you already have any libraries in mind (or aware of) that you would want to use? I came across this link: http://intro-prog-bioinfo-2012.wikispaces.com/, which doesn't seem to use any specific tools other than the "generic" libraries that are pretty much common in any scientific work involving Python: SciPy, Numpy, etc. The rule of thumb would probably be "If you don't have any particular library that you are looking to use and it doesn't yet support Python 3, then you may as well learn Python 3", since that is the future. I think you may need to spend some time deciding this one. However that said, why not start with Python 3? The programming language syntax and style won't be different if you need to go by chance and use Python 2 at some other point of time. Hope that helps. -Amit. > > > On Mon, May 20, 2013 at 6:38 PM, Dave Angel wrote: >> >> On 05/20/2013 05:59 AM, Amal Thomas wrote: >>> >>> hi, >>> I am a beginner. I am using a unix sytem (ubuntu 12.10). Python 2.7.3 >>> is installed in my system. I found out that Python has version upto >>> 3.3.2. >> >> >> Welcome, and thanks for telling us your environment up front. >> >> >> >>> Should I update my python version? >> >> >> No. Your OS has lots of dependencies on that installed Python, and if you >> remove that one (eg. replace it), many things will stop working. >> >> HOWEVER, you can install a second Python, of whatever version, and use >> that for all your own experimenting and learning. So the question is which >> one you should use for learning. My comments at the end. >> >> >>> Is the syntaxes of the each version >>> different? >>> >> >> Yes. Not only syntax but semantics as well. Version 3.0 was deliberately >> a breaking update, where many of the painful gotchas in the language were >> fixed, even if it meant things were incompatible. There is a 2to3 utility, >> but the transition can be painful for large programs. >> >> Which one should you learn on? >> >> #1 --- if you're committed to a particular tutorial, use the version that >> matches the tutorial. At your stage, you don't want to have to convert >> every example in your head before getting it to work. >> >> #2 --- If you have a particular library or libraries that you plan to use, >> and it's only currently available for one version, then use that version. >> >> #3 --- If neither of the above apply, then use 3.3 or the soon-coming 3.4. >> >> What's different? For a beginner, the most noticeable different is that >> the print statement in 2.x was replaced by a print function in 3.x For >> really simple cases, that just means slap a parentheses around the >> argument(s). But the print statement has syntax for redirecting to a file, >> while the print function has a parameter. And the technique for suppressing >> the trailing newline is different. Etc. >> >> The second most noticeable difference is that 3.x handles Unicode >> directly, so that a string is Unicode, and if you want bytes, those are >> different. >> >> >> >> >> -- >> DaveA >> >> ___ >> Tutor maillist - Tutor@python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor > > > > > -- > AMAL THOMAS > Third Year Undergraduate Student > Department of Biotechnology > IIT KHARAGPUR-721302 > > ___ > Tutor maillist - Tutor@python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -- http://echorand.me ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] trying to split or rpartition the contents of a list
Hello, On Wed, May 22, 2013 at 5:49 PM, Stuart Tozer wrote: > Hi everyone. > > I'm stuck on a problem while developing a small tool for Maya. Basically, I > have a folder with some filenames in it which have been returned by > os.listdir(). These filenames look something like... > > > apple_d.jpg > apple_si.jpg > apple_sg.jpg > box_d.jpg > box_si.jpg > pumpkin_d.jpg > > > Right now, I'm using os.listdir to get the filenames, and then each filename > becomes a selectable option in an option menu in maya. The code is... > > objects = os.listdir(dir) > > > > > > for object in objects: > cmds.menuItem(label = object, parent = "objectMenu") > > > > My problem is that I don't want duplicates of the same object in the menu > and I also want to truncate everything past and including the underscore. So > for eg, if my filenames are the same as the example above, I want to change > the list so I have this instead... > > apple > box > pumpkin > > > I have tried splitting the filenames, but so far haven't had any luck. > > for object in objects: > sorted(set(object.split('_', 1)[0])) > cmds.menuItem(label = object, parent = "objectMenu") You are almost there. Something like this should work: >>> labels = ['apple_d.jpg','apple_si.jpg','apple_sg.jpg','box_si.jpg'] Now, create a list of only the names (upto _): >>> labels_processed=[ ] >>> for label in labels: ... labels_processed.append(label.split('_')[0]) ... Remove the duplicates: >>> set(labels_processed) set(['box', 'apple']) If you have any doubts about this, please ask. Best, Amit. -- http://echorand.me ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] trying to split or rpartition the contents of a list
Hi Stuart, On Thu, May 23, 2013 at 10:57 PM, Stuart Tozer wrote: > Hello Amit- your solution works very well. Thanks very much! Good to know that! Hope it was clear. All the best. -Amit > > Best regards, > Stu > > > On Wed, May 22, 2013 at 11:39 AM, Stuart Tozer wrote: >> >> Thanks very much guys- I'll get back to this when I have a spare moment >> and let you know how I get on. >> >> Cheers, >> Stu >> >> >> >> On Wed, May 22, 2013 at 11:06 AM, Albert-Jan Roskam >> wrote: >>> >>> > >>> >>> >>> > >forobjectinobjects:sorted(set(object.split('_',1)[0]))cmds.menuItem(label >>> > =object,parent ="objectMenu") >>> >>> >>> "sorted" returns the sorted list but you don't assign anything to it. You >>> can either assign it to a variable, or use the .sort method instead. Also, >>> you don't need to specify the maxsplit argument (1) in .split. Also, you >>> used 'object' as a loop index but this is a reserved word. Why not use the >>> more descriptive "for filename in filenames"? >> >> >> >> >> -- >> http://stutozer.elementfx.com/ >> >> > > > > -- > http://stutozer.elementfx.com/ > > > > ___ > Tutor maillist - Tutor@python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -- http://echorand.me ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] Python and Symbolic Math for beginners
Hello Tutors, Would any of you have any teaching (or substantial self learning) experience with a library for Symbolic math? I am currently exploring sympy (http://sympy.org) as part of writing a book chapter and would like to know if there any better/easier option out there which can successfully introduce symbolic math to young programmers. Thank you for any suggestions in advance. Best, Amit. -- http://echorand.me ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Python and Symbolic Math for beginners
On Mon, Jun 17, 2013 at 11:25 AM, bob gailer wrote: > On 6/15/2013 5:53 AM, Amit Saha wrote: >> >> Symbolic math? > > What is that? Eg: https://gist.github.com/amitsaha/5787802 -- http://echorand.me ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Python and Symbolic Math for beginners
On Mon, Jun 17, 2013 at 12:14 PM, epi wrote: > i guess you'll find this pretty interesting : > > http://nbviewer.ipython.org/url/edu.scios.ch/sympy/nb_sample_sympy.ipynb > > sympy latex rendering using the ipython notebook … > > Have fun ;) Thanks, I am aware of that. I was asking for any other beginner friendly alternative to SymPy that folks may be aware of. Best, Amit. -- http://echorand.me ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Python and Symbolic Math for beginners
On Mon, Jun 17, 2013 at 12:47 PM, Jim Mooney wrote: > On 16 June 2013 18:28, Amit Saha wrote: >> On Mon, Jun 17, 2013 at 11:25 AM, bob gailer wrote: >>> On 6/15/2013 5:53 AM, Amit Saha wrote: >>>> >>>> Symbolic math? >>> >>> What is that? >> >> Eg: https://gist.github.com/amitsaha/5787802 > > x wasn't defined, and it didn't look like you needed solve(expr,x, > dict=True) the first time > since it's repeated in pprint, so I ditched it. Then it worked nicely. 'x' was defined earlier, I didn't paste it there :-), and Yes I didn't need the first solve. > > That's a nice little package. Just about self-explanatory, and you > don't need a big, honking GUI or TeX. I think I'll keep it. And works > in 3.3. I think I'll keep it ;') yeah, I am playing with the Python 3 version. Works great so far. > > -- > Jim > After indictment the bacon smuggler was put on the no-fry list -- http://echorand.me ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Python and Symbolic Math for beginners
On Mon, Jun 17, 2013 at 1:16 PM, Jim Mooney wrote: >> yeah, I am playing with the Python 3 version. Works great so far. > > I didn't even look at the docs, but I think I got the solve part > working. I cut down on typing a bit, though. Typing Symbol all day > long could get tedious: > > from sympy import Symbol as S, solve, pprint > a,b,c,x = S('a'),S('b'),S('c'),S('x') > pprint(solve(a*x*x + b*x + c, x, dict=True)) > > ## pretty picture here > > a,b,c = 3,5,6 ## seeing if it solves stuff the way I think > > y = solve(a*x*x + b*x + c, x, dict=True) > > print(y) > > ## result: [{x: -5/6 - sqrt(47)*I/6}, {x: -5/6 + sqrt(47)*I/6}] > ## Oops, looks like I accidentally went complex ;') > > I certainly like a module where you don't have to search and ponder, > and it works about like you expect. It seems very straightforward. This is a new tutorial the SymPy guys are working on: http://docs.sympy.org/tutorial/tutorial/index.html I certainly found it much more coherent and it clarified a few doubts I was having. -- http://echorand.me ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Python and Symbolic Math for beginners
On Mon, Jun 17, 2013 at 1:25 PM, Jim Mooney wrote: > On 16 June 2013 20:18, Amit Saha wrote: >> >> This is a new tutorial the SymPy guys are working on: >> http://docs.sympy.org/tutorial/tutorial/index.html > > Thanks. A lot of math bored me but I see it has matrices, and I really > liked linear algebra for some odd reason. I might fool with it again > since this package is just basics and not some Huge graphical > overkill. Indeed, it's quite fun. Also, check out https://github.com/sympy/sympy/wiki/Idioms-and-Antipatterns -- http://echorand.me ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Python and Symbolic Math for beginners
On Mon, Jun 17, 2013 at 1:25 PM, Jim Mooney wrote: > On 16 June 2013 20:18, Amit Saha wrote: >> >> This is a new tutorial the SymPy guys are working on: >> http://docs.sympy.org/tutorial/tutorial/index.html > > Thanks. A lot of math bored me but I see it has matrices, and I really > liked linear algebra for some odd reason. I might fool with it again > since this package is just basics and not some Huge graphical > overkill. I agree with that sentiment of "some Huge graphical overkill". -- http://echorand.me ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Unix Environment variables
Hello, On Tue, Jun 18, 2013 at 9:58 AM, Anu Bhagat wrote: > Hi I am fairly new to python. I will greatly appreciate if some one can tell > me how set up environment variables from a python script. > > Thanks in advance. You can use the 'os' module. This is the document for Python 2 [1]. That should help you retrieving/setting environment variables. [1] http://docs.python.org/2/library/os.html#os.environ Best, Amit. > > Anu > -- > Nothing is impossible, the word itself says 'I'm possible'. Audrey Hepburn > > Anu Bhagat > SETI Institute > 189 North Bernardo Street > Mountain View, CA 94043-5203 > Phone : 650.960.4592 > Fax : 650.960.5830 > ___ > Tutor maillist - Tutor@python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor -- http://echorand.me ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] How much in a "try" block?
On Fri, Aug 23, 2013 at 6:14 AM, leam hall wrote: > If I have a series of tasks that depend on X happening, should I put them > all in the same "try" block or just put X in there and exit out if it fails? You are right about the latter. You should put only the statement which you expect to raise the exception. -- http://echorand.me ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] How much in a "try" block?
On Fri, Aug 23, 2013 at 10:30 AM, Alan Gauld wrote: > On 22/08/13 21:27, Chris Down wrote: > >> You can also use the "else" clause if there is stuff you want to run if >> the try >> block doesn't raise the caught exception, which avoids putting it in "try" >> if >> you don't intend to exit from the exception. > > > I admit that I've never really found a use for else in a try block. > I don;t see much advantage in > > try: f(x) > except MyError: > pass > else: > g(x) > h(x) > > over > > try: f(x) > except MyError: > pass > g(x) > h(x) > > Unless you really only want g(x) executed if there > is no MyError exception but want h(x) executed regardless. > > I guess where h() is not using x it might be helpful but in most(all?) of > my code I've usually bailed when x has gone > wrong or I've fixed things such that hg() and h() are required. > > I'm curious, how often do others use the try/else combination? I think one use of writing something in an "else" would be to write those statements which are part of a "block" (loosely used) of statements which would depend on the statement in the try block. That doesn't change the way it works if they were not written in an "else", but perhaps makes it clear that those statements are to be executed only when there is no exception. Explicit is better than implicit, may be? -- http://echorand.me ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] How to present python experience (self-taught) to potential employer
Hi Jing Ai, On Fri, Aug 23, 2013 at 12:45 PM, Jing Ai wrote: > Hi everyone, > This is Jing and I am a recent college graduate with Biology and Public > Health background. I'm currently learning python on my own when i have time > off from my PH internship. There's a job posting that looks really idea for > me in the near future (a PH Research position) that requires "Python > experience" and I wonder if any of you have any suggestions how I can > demonstrate my python skills if I'm learning it on my own as opposed to > taking courses? > > Some people had previously suggested GitHub, but it seems to only show my > abilities to read python code and detect bugs, but not abilities to write > python code. Some others suggested doing a project of my own, but I don't > currently have any data or problem to solve in my field. I am not from your background. In your field of work do you need to do lot of data analysis (read statistical analysis)?. Do you think you could find something like that and something of your interest? You could then use Python (the language and related tools) to perform data analysis, presenting data graphically, etc to work the data and infer some relevant conclusions. For example, http://www.quandl.com/ has data sets related to various fields of study. Does that sound like something you may find interesting and is relevant? Best, Amit. -- http://echorand.me ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] How to present python experience (self-taught) to potential employer
On Fri, Aug 23, 2013 at 1:52 PM, Jing Ai wrote: > @Amit > Thank you for your suggestions! I'll look into the data there and see if > there's something relevant that I can use to do a project. Yes I believe it > would involve some data analysis (and I may need to learn R as well or use > RPy). Do you think one project is sufficient to demonstrate my skills if > it's in-depth? Or does it take several projects? Hmm I am not sure. But, depends on how much time you have. If you can do one "big" project that demonstrates a number of your skills - use of Python and one or more of the scientific libraries, that perhaps speaks fair bit about what you know. Also, consider using version control for your projects and of course, unit testing. I also suggest looking into Sphinx for documentation of your project. They also demonstrate that you know some of the things that you need to beyond just writing programs. Best of luck. -Amit. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] cs student needs help import math
On Sun, Sep 8, 2013 at 8:02 AM, Byron Ruffin wrote: > I am writing a simple program based off an ipo chart that I did correctly. > I need to use ceil but I keep getting an error saying ceil is not defined. > I did import math, I think. I am using 3.2.3 and I imported this way... > import math math.pi > 3.141592653589793 math.ceil(math.pi) > 4 math.floor(math.pi) > 3 > > ... but I get the error when using ceil... > > pepsticks = ceil(peplength / StickLength) > Traceback (most recent call last): > File "", line 1, in > pepsticks = ceil(peplength / StickLength) > NameError: name 'ceil' is not defined So, like you see earlier, you used math.ceil() to refer to the ceil() function. That is how you refer to a function defined in a module. If you want to refer to it as ceil(), you have to import it like so: from math import ceil Best, Amit. -- http://echorand.me ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Python Programming Help
Hi Katie, On Wed, Sep 11, 2013 at 11:01 AM, Katie wrote: > Hello, > > I am a beginner in computer programming. I am studying math, and the math > class that I will be taking requires knowledge in Python. So, I am in a > computer science class. Therefore, I do not have an in-depth knowledge of > computer programming. Welcome to the forum and welcome to the world of programming! > > I am currently trying to write a program in Python version 2.7.5 that uses > the math module to compute sinh(x) = 1/2(e^x - e^(-x)) in three ways for a > given value of x: > 1a) by using the sinh function > 1b) by using the exp function > 1c) by using the value of e and the exponentiation operator ** > > 2. Print the results and note any differences that appear. > > So, I know that I have to create a NotePad file so that I can import that > into my command prompt. > > In my NotePad file, I have the following...I'm not sure if I am even going > about doing this problem correctly... Okay, so when you are programming, there are two things you do to see the result of your programs: 1. First, you write the program. You write this in an text editor. Notepad is a text editor (There are better options, but let's keep it as it is for now) 2. Then, you run the program. Sometimes you can run the program from the editor itself, such as in IDLE. Other times, you have to run it separately. So, before you write the solution to the programming problem above, can you first try to write a program and then run it? What operating system are you working? If you are on Windows, can I suggest you to take a look at these videos I created a while back and they may help you: http://www.youtube.com/playlist?list=PLD0rs_vnIQS5r8IhNpu0rWIAyKpTX34yo Only when you have written your first program, which is really simple, you should try to attempt your exercise. Hope that helps. -Amit. -- http://echorand.me ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Python Programming Help
On Wed, Sep 11, 2013 at 7:59 PM, Oscar Benjamin wrote: > On 11 September 2013 10:48, Amit Saha wrote: >> Hi Katie, >> >> So, before you write the solution to the programming problem above, >> can you first try to write a program and then run it? What operating >> system are you working? If you are on Windows, can I suggest you to >> take a look at these videos I created a while back and they may help >> you: http://www.youtube.com/playlist?list=PLD0rs_vnIQS5r8IhNpu0rWIAyKpTX34yo > > Good work Amit. I don't have any sound on this machine but I skimmed > those videos and they seem really useful. I'll remember to point > someone there in future. Do you know of anything similar for OSX? Thanks, Oscar. I haven't really seen something similar for OSX, mainly because I have never used one. I searched now though on YouTube and there seems to be a few. -- http://echorand.me ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Web Services with python
On Wed, Sep 18, 2013 at 7:05 PM, Ismar Sehic wrote: > Hello, can someone point me to some good guality resources to learn Web > Services with Python?with some exaples, tutorials, exercises and such. What do you want to do? Do you want to connect to a remote server or do you want to implement a server, or both? -- http://echorand.me ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Copy and paste python on Microsoft word
On Wed, Sep 18, 2013 at 2:59 PM, Sammy Cornet wrote: > I'm using python 3.3.0, I have made a program on my script and output it. I > have tried several times to copy and paste the output and the script on > Microsoft word, every time I select the part that I need and right click on > it, this message appears: go to the file/line. It provides me no access to > copy and paste them. Please, can someone help me? Are you using IDLE ? If so, select the text and use the "Edit" menu to copy/cut/paste. -- http://echorand.me ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] Checking that the input is float()-able
Hi all, I want my program to report an error if anything other than a number which I can then convert to float using float() is entered as input: # Python 3 try: a = float(input('Enter a number: ')) except ValueError: print('Wrong input') else: print('Right input') This seems to do the job for me. python3 input_number.py $ Enter a number: 34.563 Right input $ python3 input_number.py Enter a number: abcd Wrong input $ python3 input_number.py Enter a number: {} Wrong input I have two queries: - Is this the best way to do this? - Is this is the easiest way to tell a beginner to do this? (Even though it introduces try..except) Thanks for any comments. Best, Amit. -- http://echorand.me ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] A demon command line interpreter using the 'cmd' module
I wrote this demo command line interpreter to demonstrate using the cmd module: https://gist.github.com/amitsaha/6047955 $ python3 demo_cmd_interpreter.py Welcome to Dummy shell. Type help or ? to list commands. dummyshell>> help Documented commands (type help ): exit help shell whoami dummyshell>> whoami gene dummyshell>> !date Sun Sep 22 13:00:01 EST 2013 dummyshell>> quit Bye! To learn more about the cmd module: http://docs.python.org/3/library/cmd.html Hope someone finds this useful in their learning/teaching. Best, Amit. -- http://echorand.me ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Checking that the input is float()-able
On Sun, Sep 22, 2013 at 11:28 AM, Steven D'Aprano wrote: > On Sun, Sep 22, 2013 at 10:18:23AM +1000, Amit Saha wrote: >> Hi all, >> >> I want my program to report an error if anything other than a number >> which I can then convert to float using float() is entered as input: >> >> # Python 3 >> try: >> a = float(input('Enter a number: ')) >> >> except ValueError: >> print('Wrong input') >> else: >> print('Right input') >> >> >> This seems to do the job for me. > [...] >> I have two queries: >> >> - Is this the best way to do this? >> - Is this is the easiest way to tell a beginner to do this? (Even >> though it introduces try..except) > > Yes, and yes. > > Thank you Joel and Steven. Best, Amit. -- http://echorand.me ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] List Python Question..Please help
On Fri, Sep 27, 2013 at 3:48 PM, Jacqueline Canales wrote: > So I have been trying to do this program using ifs and or loops. > I am having a hard time solving this question, If you could please assist me > in the right direction. > > Write a program that lists all the composers on the list ['Antheil', > 'Saint-Saens', 'Beethoven', 'Easdale', 'Nielsen'] whose name starts and ends > with the same letter (so Nielsen gets lsited, but Antheil doesn't). > > I know below it prints the entire list of composers but i dont know how to > do the program above. I think I am thinking to much into but ive looked at > all my notes and online resources and having a hard time coming up with > anything. > Please help! > > composers = ['Antheil', 'Saint-Saens', 'Beethoven', 'Easdale', 'Nielsen'] > for person in composers: > print(person) So, here you are printing every compose as you rightly state above. What you now need to do is: For each of the composers (`person'), you need to check if the first letter and the last letter are the same. Here;s a hint: >>> s='abba' The first letter: >>> s[0] 'a' The last letter: >>> s[-1] 'a' If you now compare these, you will know if they are the same and hence you print him/her. Hope that helps. -Amit. -- http://echorand.me ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] List Python Question..Please help
Hi Jacqueline, On Sat, Sep 28, 2013 at 3:04 AM, Jacqueline Canales wrote: > composers = ['Antheil', 'Saint-Saens', 'Beethoven', 'Easdale', 'Nielsen'] > x = 'Antheil' > s = 'Saint-Saens' > h = 'Beethoven' > y = 'Easdale' > k = 'Nielsen' > > if s[0] == 'S' or s[0] == 's' == s[-1] == 'S' or s[-1] == 's': > if y[0] == 'E' or y[0] == 'e' == y[-1] == 'E' or y[-1] == 'e': > if k[0] == 'N' or k[0] == 'n' == k[-1] == 'N' or k[-1] == 'n': > print(s,k,y) > else: > print(" ") > > Answer i Got Below > Saint-Saens Nielsen Easdale > > Is this what i was going for in the direction i was a bit confused if we > were suppose create loops or if statements that are verified in the actual > composers list. I don't know i feel as if i know what i need to do i just > cant put it together. Nothing to worry. Let us break the problem down. In your first post, you mentioned this for loop: composers = ['Antheil', 'Saint-Saens', 'Beethoven', 'Easdale', 'Nielsen'] for person in composers: print(person) What does this do? It prints all the composers' names. However, what you want is to print *only* the composer whose name starts and ends with the first letter. So, what can you do? I shall try to explain with an example from every day life. Let us say, the management in your local cinema theatre says that you can choose to see all of the films playing there. So, you can see all of: 'Turbo', 'Planes' and 'The Smurfs 2'. Now, let is say that your cinema management became a little shrewd and tells you that you can only watch the films starting with 'P'. So what do you do? In your mind, you think which of 'Turbo',' Planes' and 'The Smurfs 2' starts with 'P'. So, you first check, 'Turbo' and you see that it fails the condition, but 'Planes' agree with the condition and 'The Smurfs 2' also fails. Thus, you choose 'Planes'. So, your above program is in the right direction. What you have to now do is, before printing the 'person', you need to check if the person's name starts and ends with the same letter. I already showed you how you can do so. You may find the lower() method helpful here. It returns you a capital letter into a lower one: >>> 'A'.lower() 'a' Does that make it easier? Good luck. -Amit -- http://echorand.me ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] List Python Question..Please help
On Sat, Sep 28, 2013 at 3:36 PM, Jacqueline Canales wrote: > Thank you guys so much i was able to figure it out. I definitely thought to > much into the the problem and made it harder on myself. Cant thank you > enough for assisting me. I have one more problem with the coding tho. > > composers = ['Antheil', 'Saint-Saens', 'Beethoven', 'Easdale', 'Nielsen'] > new_list = [] > person = new_list > for person in composers: > if person[0].lower() == person[-1].lower(): > print(person) > > Output: > Saint-Saens > Easdale > Nielsen Great work! > > composers = ['Antheil', 'Saint-Saens', 'Beethoven', 'Easdale', 'Nielsen'] > new_list = [] > person = new_list > for person in composers: > if person[0].lower() == person[-1].lower(): > new_list.append(person) > print(new_list) > > output: > ['Saint-Saens'] > ['Saint-Saens', 'Easdale'] > ['Saint-Saens', 'Easdale', 'Nielsen'] > > How can i make the output of the names into just one individual list. You mean, just print it once? The last line of your output? Just print after the loop is over. -- http://echorand.me ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] writing python on the web
On Tue, Oct 1, 2013 at 5:42 AM, Alan Gauld wrote: > On 30/09/13 13:49, roberto wrote: >> >> Hi, my school is considering a massive shift to Chromebooks. I've to >> carefully think about how could the students go on writing their python >> programs on the web. > > > It's not just Python it's any kind of program. > There are a few online interpreters around but if you are > planning on teaching computing, a ChromeBook or any other cloud > based tool is going to make it hard if not impossible to teach effectively. > > You maybe need to feed that back to your administration before they > seriously damage their students prospects and their schools reputation. > They may be slightly cheaper (and we are only talking about $50 each!) > but they are very limited devices. > > If you are forced to go down that route consider finding an online terminal > emulator and get the students to use it to access a server someplace where > you can install Python and any other environment you need. That's still > limiting things to text but better than an online interpreter IMHO. I am +1 in agreeing with Alan on all the above points. If your school really wants to teach programming, nothing other than a "real" computer should be the first preference. That said, considering Alan's last point, if you must, take a look at https://www.nitrous.io . I haven't used it much, but they give you terminal access, etc. May help. -Amit. -- http://echorand.me ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Easiest framework for web development?
On Mon, Sep 30, 2013 at 7:15 PM, wrote: > Hi > > Which of the available Python frameworks is the EASIEST to learn for a > NEWBIE who needs to do *basic* web development? (only the *most basic* web > functionality will be needed) Only the *most basic* web functionality won't need you to use a Python web framework. It needs HTML and CSS and some Javascript at best. Now, I am sure you want more. You will get various answers, but I found Flask (http://flask.pocoo.org/) to be very easy to start with. I had no clue of any web frameworks when I started with it and found it very easy to get started with. The documentation is one of the best I have come across for any open source project. So, it should help you get started fairly easily. Although the quickstart guide: http://flask.pocoo.org/docs/quickstart/ has more than the basics, but it's a good idea to go through it as much as you can and experiment on your own. Hope that helps. -Amit -- http://echorand.me ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] why does platform.architecture default to sys.executable?
On Sun, Oct 27, 2013 at 2:39 AM, Albert-Jan Roskam wrote: > Hi, > > Why does the "executable" parameter default to sys.executable? Yesterday I > was surprised to see platform.architecture return "32bit" on a 64-bit > system, just because a 32-bit Python interpreter was installed. Wouldn't > this make more sense: > > import sys, platform > pf = sys.platform.lower()[:3] > executable = "iexplore.exe" if pf[:3] == "win" else "/bin/ls" I think it's mainly because of avoiding choosing arbitrary programs, although they are most certainly guaranteed to be present. Besides, there are better ways to find the platform architecture, I think. os.uname() comes to mind. -Amit. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] why does platform.architecture default to sys.executable?
On Oct 27, 2013 2:51 AM, "Amit Saha" wrote: > > On Sun, Oct 27, 2013 at 2:39 AM, Albert-Jan Roskam wrote: > > Hi, > > > > Why does the "executable" parameter default to sys.executable? Yesterday I > > was surprised to see platform.architecture return "32bit" on a 64-bit > > system, just because a 32-bit Python interpreter was installed. Wouldn't > > this make more sense: > > > > import sys, platform > > pf = sys.platform.lower()[:3] > > executable = "iexplore.exe" if pf[:3] == "win" else "/bin/ls" > > I think it's mainly because of avoiding choosing arbitrary programs, > although they are most certainly guaranteed to be present. Besides, > there are better ways to find the platform architecture, I think. > os.uname() comes to mind. Although that will lie if you have, for example a 32-bit os installed on a 64-bit system. Then, you can read /proc/cpuinfo and look for the lm flag. If it is present, it is a 64-bit system, else a 32-bit one. This is specific to Intel, i think. > > -Amit. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] why does platform.architecture default to sys.executable?
On Sun, Oct 27, 2013 at 7:46 AM, Alan Gauld wrote: > On 26/10/13 18:13, Amit Saha wrote: > >> a 64-bit system. Then, you can read /proc/cpuinfo and look for the lm >> flag. If it is present, it is a 64-bit system, > > > But that will only work on *nix systems I assume? Indeed, both my answers assumed a Linux system. Sorry about that. -- http://echorand.me ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Python String Help
On Oct 29, 2013 7:18 PM, "Alex Tenno" wrote: > > Hey everyone, > > I'm encountering a problem with a python function that I am supposed to create. I want my function to look at a string, and then replace each letter in the string with its relative position in the alphabet. for example, 'abcde' would return '12345', 'zabd' would return '4123', and 'xpft' would return '4213'. I have been given hints that tell me "You may want to iterate over the letters ch in s as in the for loop above, and inside that for loop, count the number of letters that are in s and come before the loop variable ch. You will also need an accumulator to build the permutation the function will return." any help would be greatly appreciated. Have you thought on the lines of sorting the string and checking what position each letter of the original string is in the sorted string? For eg. 'zabd' sorted would be 'abdz' and you can check which position 'z' is in and so on. Hope that helps. Best, Amit. > > Many thanks! > > ___ > 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] Hi!
Hello, On Sun, Nov 10, 2013 at 7:04 AM, Vlad Olariu wrote: > Hello. I am new to python and mailing lists. Where should I post some code > if I need to? Welcome. Here is an example of a post with code. Assume that I am explaining to someone how they can exit out a while loop before the condition violated the first time: A while loop is an example of an "entry controlled" loop. This means that the condition is checked before entering the loop. Hence, this means if your loop condition was violated during the previous iteration, but not at the beginning, your loop will terminate after the first violation, not before it. Here is a simple example: >>> a = 1 >>> while a < 5: ... a = a+3 ... print a ... 4 7 .. and so on. Also switch to "Plain Text" in your Gmail window before you post. (if you do not know what this means, please search on the Web a bit). Good Luck. Best. Amit. -- http://echorand.me ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Help merge files using python
On Thu, Nov 14, 2013 at 8:26 AM, jarod...@libero.it wrote: > Hi I want to merge many files like this: > #file1 > A 10 > B 20 > C 30 > #file2 > B 45 > Z 10 > #file1 > A 60 > B 70 > C 10 > > I want to obtain > > A 10 0 60 > B 20 45 70 > C 30 0 10 > Z 0 10 0 >From your example, it looks like you can have any number of unique letters and the final file should have each of those listed. Against each, you should have the numbers that appear against them in the files (0 if not). So here is what I think should be an approach you could follow: 1. For each file, record each letter and the number against it (A dictionary comes to mind) 2. Once you have the dictionary for each file, create a set (as in a Python data structure) of the keys. This set will give you all the unique letters. 3. Now for each member of this set, look if it appears it each of the above dictionaries. If it occurs, note it's value, else put it down as 0. Create a new dictionary (which will be your final dictionary). The key should be each letter and the value should be a list with one or more numbers. 4. Once you are done iterating over each element of the set, your dictionary in step 3 will have the unique letters against the numbers that occur against them in the files. Now, you can write this dictionary into a file. Since you want a plain text file you will have to iterate over the keys and values. So let's consider your example: > #file1 > A 10 > B 20 > C 30 > #file2 > B 45 > Z 10 > #file3 > A 60 > B 70 > C 10 After step 1 above, you have three dictionaries, say d1, d2 and d3: d1 = {'A':10, 'B': 20, 'C':30} d2 = {'B':45, 'Z':10} d3 = {'A':60, 'B':70, 'C':10} Now, step 2, will give you a set of the keys above: unique_letters = {'A', 'B', 'C', 'Z'} After step 3, you will have this global dictionary: d = {'A':[10, 0, 60], 'B':[20, 45, 70], 'C':[30, 0, 10], 'Z':[0, 10, 0]} Now you can write this dictionary to a file. Note that step 2 will require you to combine the three individual dictionaries, so you may have to learn how to do that first. > > I try to do like this: > f = os.listdir(".") > for i in f: > T =open(i,"r") > for r in t.readlines(): > print r > > Could you please help me to understand how to use the right procedure in > python?Thanks a lot! Does the above steps help? Best, Amit. -- http://echorand.me ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Need help on Python API programmig
Hello Sourav, On 16/11/2013 6:53 AM, "Sourav Biswas" wrote: > > Hi All, > > This is my first post. I want to learn API programming with Python. I have basic knowledge of Python Programming. Could you please let me know the starting points for this programming. Since your question is fairly vague, could you please describe what you are trying to learn? An API is an interface. It can be an operating system interface, a vehicle web API or simply a web API. Some more details will be a lot of help. Best, Amit. > > -- > Thanks, > Sourav Biswas > Hyderabad > > ___ > 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] Need help on Python API programmig
Hi Sourav, Please use "Reply all" when you reply an email so that everyone else also gets your messages and your chances of getting better help increases. On Sat, Nov 16, 2013 at 3:35 PM, Sourav Biswas wrote: > Hi Amit, > > Yes I know, the question is not quite good. Currently I am trying to learn > web API programming with Python. The ultimate goal is work with OpenStack > API. > > Can you please let me know, how to start on this. > > Thanks for the reply and thanks in advance. > Sorry, I certainly didn't mean that your question was "not good". Now that you have mentioned what specifically you are looking to learn, it becomes slightly easier to make some suggestions. I don't have any personal experience with OpenStack API. However, looking at [1], it seems like you will be mostly dealing with making HTTP requests and reading responses. There are couple of standard library modules such as urlllib2 and httplib that may be useful to you. However, in this case, you would certainly benefit from directly learning to use Requests [2]. Note that however, you will need to be familiar with Python data structures such as dictionaries and know how to work with JSON data ( please see the 'json' standard module). [1] http://docs.openstack.org/api/quick-start/content/ [2]http://www.python-requests.org/en/latest/ I am hoping those prove helpful. All the best, Amit. -- http://echorand.me ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] Fwd: Need help on Python API programmig
Hi John, Perhaps your answer was directed towards Sourav. CCing tutor. -- Forwarded message -- From: John Steedman Date: Sun, Nov 17, 2013 at 6:26 AM Subject: Re: [Tutor] Need help on Python API programmig To: Amit Saha Hi Amit, I've been using Django Rest Framework for developing a database-driven API. If you choose to follow their tutorial, you may accomplish your goal quite quickly while learning a lot about web APIs and quite good engineering at the same time. Tastypie is a similar option. John On Fri, Nov 15, 2013 at 9:14 PM, Amit Saha wrote: > Hello Sourav, > > On 16/11/2013 6:53 AM, "Sourav Biswas" wrote: >> >> Hi All, >> >> This is my first post. I want to learn API programming with Python. I have >> basic knowledge of Python Programming. Could you please let me know the >> starting points for this programming. > > Since your question is fairly vague, could you please describe what you are > trying to learn? An API is an interface. It can be an operating system > interface, a vehicle web API or simply a web API. > > Some more details will be a lot of help. > > Best, Amit. > > -- http://echorand.me ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Issue w/ while loops
On Thu, Nov 21, 2013 at 9:00 PM, Rafael Knuth wrote: > Hej there, > > I want to use a while loop in a program (version used: Python 3.3.0), > and I expect it to loop unless the user enters an integer or a > floating-point number instead of a string. > > print("TIME TRACKING") > hours_worked = input("How many hours did you work today? ") > while hours_worked != str() or int(): > hours_worked = input("Can't understand you. Please enter a number! ") > > print("you worked " + str(hours_worked) + " hours today.") > > When I run the program, it keeps looping even if the condition is met. > How do I need to modify the program on the 3rd line so that it stops > looping when the user enters a floating-point number or an integer? There are two fundamental mistakes in your program: 1. The input() function always returns a string. So, there is no way to check directly whether the user has entered a number or a string. 2. hours_worked != str() or int() does not do what you want to do. In Python, str() creates a new string object and similarly int() creates an integer object, 0. So, to check whether the input is an integer or float, here is an idea: >>> def check_input(user_input): ... try: ... user_input = float(user_input) ... except ValueError: ... return 'Invalid input' ... else: ... return user_input ... >>> check_input('a') 'Invalid input' >>> check_input('1.5') 1.5 >>> check_input('1') 1.0 The idea above is basically, you convert the input (a string) to a float. If the input is a number, 1.5 or 1, the check_input() function will return the numeric equivalent. However, if the number is a string, it returns invalid input. You could make use of this in your program above. Hope that helps. Best, Amit. -- http://echorand.me ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] raw input program is still running.
On Sat, Nov 23, 2013 at 7:02 AM, Imrose Baga wrote: > Hi I've just started using python. I tried to use raw input for name, city > and state. But only my name shows up and then when i try to close the > program, it is showed as still running and asks if I wish to kill the > program. please any help Please share your program. -- http://echorand.me ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] minor display issue with python dictionaries
On Mon, Nov 25, 2013 at 2:55 AM, Joel Goldstick wrote: > On Sun, Nov 24, 2013 at 11:03 AM, Reuben wrote: >> Hi, >> >> ## > > new_dict = {'a':10, 'b' :20, 'c': 30,'d' : 40} > > > print new_dict >> {'a': 10, 'c': 30, 'b': 20, 'd': 40} > >> >> >> # >> >> >> From the above output, I see key 'c' is at third position during input, but >> while displaying the output it is displayed at second position >> >> Although, I dont see any impact of it since we mainly refer to dictionary >> values only using "keys" -- but just for curiosity why is this position >> change? >> >> Regards, >> Reuben >> >> ___ >> Tutor maillist - Tutor@python.org >> To unsubscribe or change subscription options: >> https://mail.python.org/mailman/listinfo/tutor >> > The key is the way to the value. Depending on the implementation, > python might find the value by different algorithms. Sometimes people > call dictionaries 'hashes', which I believe refers to a method of > indexing that does some algorithm on the key to get the value > location. This is for speed and for space savings in memory. > > So, sometimes you might see a dictionary displayed in the order you > entered it, but sometimes not. And if order is important, you should look at using OrderedDict [1]. See here [2] for examples. [1] http://docs.python.org/2/library/collections.html#collections.OrderedDict [2] http://docs.python.org/2/library/collections.html#ordereddict-examples-and-recipes Best, Amit. -- http://echorand.me ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Splitting lists with strings and integers
On Wed, Nov 27, 2013 at 5:00 AM, Sam Lalonde wrote: > Hi, I am very new to python. > > I have a list with mixed strings/integers. I want to convert this to a list > of lists, and I want the numbers to get stored as integers. > list1 = ['dog 1 2', 'cat 3 4', 'mouse 5 6'] list2 = [] for animal in list1: > ... animal = animal.split() > ... list2.append(animal) > ... print list2 > [['dog', '1', '2'], ['cat', '3', '4'], ['mouse', '5', '6']] for animal in list2: > ... print animal[1] + animal[2] > ... > 12 > 34 > 56 The numbers are appended because: '1' + '2' = '12' and so on. > > You can see that it just appended the numbers to each other. I'd like the > output to be: > > 3 > 7 > 11 > > Is there a clean way to get the numbers stored as int instead of str when I > build list2? Consider your original list: >>> list1 = ['dog 1 2', 'cat 3 4', 'mouse 5 6'] For each item of the list, you want to extract the numbers and add them with the sums in a new list. Let's take it one step at a time >>> # extract the numbers only ... for item in list1: ... print item.split()[1:] ... ['1', '2'] ['3', '4'] ['5', '6'] But, we want each number as integer and print their sum instead of the individual numbers: >>> for item in list1: ... print int(item.split()[1]) + int(item.split()[2]) ... 3 7 11 So, we have our numbers. But we would like this to be a list instead. So, instead of printing, simply create a list. Hope that helps. Best, Amit. > > Thanks > > ___ > Tutor maillist - Tutor@python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > -- http://echorand.me ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] Alternatives to append() for "growing" a list
Hello, I was told by someone (as a comment) that a code snippet such as this "would make Pythonistas talk my ear off about how evil the append()" function is: >>> mylist = [] >>> mylist.append(1) # a number of times over I have some ideas that on an append() the list's internal size increases (doubled?) since CPython over-allocates memory, and such. So, the question is: what is the alternative to growing a list when I have no idea what items or how many may be there? Thanks, Amit. -- http://echorand.me ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Alternatives to append() for "growing" a list
On Sun, Dec 1, 2013 at 5:04 PM, Steven D'Aprano wrote: > On Sun, Dec 01, 2013 at 02:32:38PM +1000, Amit Saha wrote: >> Hello, >> >> I was told by someone (as a comment) that a code snippet such as this >> "would make Pythonistas talk my ear off about how evil the append()" >> function is: > > There is absolutely nothing wrong with append. Either you have > misunderstood, or the person who told you this was smoking crack. heh, no I literally quote the person above, so I think I understood him alright. > >> >>> mylist = [] >> >>> mylist.append(1) >> # a number of times over > > However, growing a list one item at a time using append like this is too > much hard work. Some better solutions: > > # You have an existing list, and want to append a bunch of things to it > mylist.extend([x, y+1, z*2]) > > # You want a list consisting of the same objects repeated many times > mylist = [0, 1, 2]*100 # like [0, 1, 2, 0, 1, 2, 0, 1, 2, ...] > > # You want to create a list containing known objects > mylist = [1, 2, 4, 8, 16, 32, 64] > > # Like above, but using a list comprehension > mylist = [2**n for n in range(7)] > > # You don't know how many things you want to add. > mylist = [] > x = 1 > while x < 100: > mylist.append(x) > x = 3*x-1 > > and so on. As you can see, append has its job to do. > The last case is the closest to the context in which I used the above code construct. > >> I have some ideas that on an append() the list's internal size >> increases (doubled?) since CPython over-allocates memory, and such. > > Not just on append. Any operation that adds or deletes items from a list > might trigger a re-size. If the list needs to increase, it will double > in size up to some maximum, then it will grow by a smaller amount. The > purpose of this is that *on average* appending to the list will take a > fixed amount of time. > > >> So, the question is: what is the alternative to growing a list when I >> have no idea what items or how many may be there? > > Don't worry about growing the list. That's all handled for you as part > of the list interface. The whole point of using Python is to not have to > worry about internal details like that. Right, that's what I thought. Good that I checked here, now I can write a nice reply to the comment :-) Thanks Steven and Dave. Best, Amit. -- http://echorand.me ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Occurrence of number 2 in a range from 1 to 100
Hello, On Sun, Dec 1, 2013 at 3:50 PM, Reuben wrote: > Hi, > > How can we write a logic for detecting the number 2 in range from 1 to 100 You question is unclear. Could you please give more details ? Best, Amit. -- http://echorand.me ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] Loop over floating point values
Hello, Much to my disbelief, I realized I hadn't written a program in Python as far as I can recall which required me to do something like this, in psuedocode: x = 0.1 for i = 0 to x step 0.01 # do something with i end i Simply stated, I want to start from say a value, 0 and go upto 0.1 in increments of 0.01. I don't want to create a list with the values hard-coded and then iterate over it, and hence I would use a while loop instead: x = 0.1 while i < x: # do something with i i += 0.01 I think this is one case, where you definitely cannot do this with a for loop assuming the following restrictions: - Do not create a list of the floating point values as i=[0.01, 0.02, 0.03..] - either like that or by using a suitable mathematical formula combined with a list comprehension - Use numpy's linspace() to create the list for you Thoughts? Thanks, Amit. -- http://echorand.me ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Loop over floating point values
On Sun, Dec 1, 2013 at 7:26 PM, Steven D'Aprano wrote: > On Sun, Dec 01, 2013 at 07:03:15PM +1000, Amit Saha wrote: >> Hello, >> >> Much to my disbelief, I realized I hadn't written a program in Python >> as far as I can recall which required me to do something like this, in >> psuedocode: >> >> x = 0.1 >> >> for i = 0 to x step 0.01 >> # do something with i >> end i > > > Such floating point loops are tricky to get right, thanks to rounding of > floats. Observe: > > py> x = 0.0 > py> while x < 1.0: > ... x += 0.1 > ... > py> x == 1.0 > False > py> x > 1.0999 > > We expect that after the loop is done, x should equal 1, but it doesn't. > That means that it actually loops one time too many. Indeed, that's a good point. Surprisingly, C does it just fine: # include int main(int argc, char **argv) { float x = 0.0; while(x<1) { x += 0.1; printf("%f\n", x); } return 0; } gives the following output: 0.10 0.20 0.30 0.40 0.50 0.60 0.70 0.80 0.90 1.00 > > One way to fix this is to iterate over integers, and then divide just > before doing the work: > > for x in range(0, 10): > print x/10.0 Yes, that's one approach to ensure that we do not exceed the hard limit of 1. > > > Another way is to use the recipes I have here: > > http://code.activestate.com/recipes/577878-generate-equally-spaced-floats/ > > http://code.activestate.com/recipes/577881-equally-spaced-floats-part-2/ > > http://code.activestate.com/recipes/577068-floating-point-range/ > > I encourage you to read all three. If you have any questions, please > feel free to ask. Thanks for sharing these, I will go through them. Best, Amit. -- http://echorand.me ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Loop over floating point values
On Sun, Dec 1, 2013 at 7:14 PM, Dominik George wrote: > Hi, > >> - Do not create a list of the floating point values as i=[0.01, 0.02, >> 0.03..] - either like that or by using a suitable mathematical formula >> combined with a list comprehension > > You could simply write your own version of xrange that does it, as a > generator: > > def xrange_f(start, stop, step): > x = start > while x < stop: > yield x > x += step > > Then, in your code, you can do: > > for f in xrange_f(0, 10, 0.01): > pass Thanks Dominik. Yes, this is a good abstraction if I need this functionality at multiple places. Best, Amit. -- http://echorand.me ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Loop over floating point values
On Sun, Dec 1, 2013 at 7:47 PM, spir wrote: > On 12/01/2013 10:03 AM, Amit Saha wrote: >> >> Hello, >> >> Much to my disbelief, I realized I hadn't written a program in Python >> as far as I can recall which required me to do something like this, in >> psuedocode: >> >> x = 0.1 >> >> for i = 0 to x step 0.01 >> # do something with i >> end i >> >> Simply stated, I want to start from say a value, 0 and go upto 0.1 in >> increments of 0.01. I don't want to create a list with the values >> hard-coded and then iterate over it, and hence I would use a while >> loop instead: >> >> x = 0.1 >> while i < x: >> # do something with i >> i += 0.01 >> >> I think this is one case, where you definitely cannot do this with a >> for loop assuming the following restrictions: >> >> - Do not create a list of the floating point values as i=[0.01, 0.02, >> 0.03..] - either like that or by using a suitable mathematical formula >> combined with a list comprehension >> - Use numpy's linspace() to create the list for you >> >> >> Thoughts? > > > There is a general solution for this (a typical school problem ;-), maybe > the reason why we rarely meet it in practice!). Depends on what your practice is. This will come up in any problem where you need a continuous stream of numbers. Like, drawing a circle with x=rcos(theta) and y=rsin(theta) with theta between 0 to 360. However, watch the issues > with binary floats mentionned by Steven. > > # loop from x0 to x1 with step dx, total n passes > x0, x1, dx, n = -0.3, 0.8, 0.2, 6 > for i in range(n): > x = x0 + dx * i > print(x) Yes, IIUC, I think this is an "easier" problem considering that you care abut the number of passes here more than you care about the upper bound of the numbers. Thanks for sharing. Best, Amit. -- http://echorand.me ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Loop over floating point values
On Mon, Dec 2, 2013 at 4:36 PM, Asokan Pichai wrote: > On Mon, Dec 2, 2013 at 11:58 AM, Amit Saha wrote: >> >> On Sun, Dec 1, 2013 at 7:26 PM, Steven D'Aprano >> wrote: >> > On Sun, Dec 01, 2013 at 07:03:15PM +1000, Amit Saha wrote: >> >> Hello, >> >> >> >> Much to my disbelief, I realized I hadn't written a program in Python >> >> as far as I can recall which required me to do something like this, in >> >> psuedocode: >> >> >> >> x = 0.1 >> >> >> >> for i = 0 to x step 0.01 >> >> # do something with i >> >> end i >> > >> > >> > Such floating point loops are tricky to get right, thanks to rounding of >> > floats. Observe: >> > >> > py> x = 0.0 >> > py> while x < 1.0: >> > ... x += 0.1 >> > ... >> > py> x == 1.0 >> > False >> > py> x >> > 1.0999 >> > >> > We expect that after the loop is done, x should equal 1, but it doesn't. >> > That means that it actually loops one time too many. >> >> Indeed, that's a good point. Surprisingly, C does it just fine: > > I am not sure. >> >> >> # include >> >> int main(int argc, char **argv) >> { >> float x = 0.0; >> >> while(x<1) >> { >> x += 0.1; >> printf("%f\n", x); >> } >> >> return 0; >> } >> >> gives the following output: >> >> 0.10 >> 0.20 >> 0.30 >> 0.40 >> 0.50 >> 0.60 >> 0.70 >> 0.80 >> 0.90 >> 1.00 > > > Try double here instead of float. > 0.10 > 0.20 > 0.30 > 0.40 > 0.50 > 0.60 > 0.70 > 0.80 > 0.90 > 1.00 > 1.10 > is what I get on a debian machine with gcc 4.8.2 , though I suspect that > these are not relevant. Yes, I didn't mean to imply C's result as something which is absolutely the case always. I believe, the inherent nature of floating point number representations will make this an issue, always. Best, -Amit. -- http://echorand.me ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Loop over floating point values
On Mon, Dec 2, 2013 at 10:27 PM, Dave Angel wrote: > On Mon, 2 Dec 2013 16:28:38 +1000, Amit Saha wrote: >> >> Indeed, that's a good point. Surprisingly, C does it just fine: > > > >> # include > > > >> int main(int argc, char **argv) >> { >> float x = 0.0; >> while(x<1) >> { >> x += 0.1; >> printf("%f\n", x); >> } > > > >> return 0; >> } > > > >> gives the following output: > > > >> 0.10 >> 0.20 >> 0.30 >> 0.40 >> 0.50 >> 0.60 >> 0.70 >> 0.80 >> 0.90 >> 1.00 > > > Fine The output is pretty, but thoroughly wrong. There's an extra value > at the end. You missed the fact that I am printing the value of x *after* incrementing it. -- http://echorand.me ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Alternatives to append() for "growing" a list
On Tue, Dec 3, 2013 at 6:32 AM, Danny Yoo wrote: >> >> I was told by someone (as a comment) that a code snippet such as this >> "would make Pythonistas talk my ear off about how evil the append()" >> function is: >> > > > I think this thread demonstrates: we don't need an excuse to talk your ears > off. :P > hehe, indeed. > Using append() is fine. > > If anything, the comment might be referring to an issue with appending > strings in a naive way. But without further information, can't say for > sure. If you can get more information about what your friend was talking > about, that would be helpful. It didn't have to do with strings. It was a basic example of using append() which is to start with an empty list and and then build it incrementally: >>> l = [ ] >>> l.append(1) # append more But yeah, I think that bit of "talking my ears off" is now no more valid and I have written a good rebuttal to the comment :) Best, Amit. -- http://echorand.me ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Loop over floating point values
On Mon, Dec 2, 2013 at 4:49 PM, eryksun wrote: > On Mon, Dec 2, 2013 at 1:28 AM, Amit Saha wrote: >> Indeed, that's a good point. Surprisingly, C does it just fine: >> >> # include >> >> int main(int argc, char **argv) >> { >> float x = 0.0; >> while(x<1) >> { >> x += 0.1; >> printf("%f\n", x); >> } >> >> return 0; >> } > > Python uses double precision: > > >>> import os, ctypes > >>> open('tmp.c', 'w').write(r''' > ... double test_d() { > ... double x = 0.0; > ... while (x < 1.0) > ... x += 0.1; > ... return x; > ... } > ... float test_f() { > ... float x = 0.0; > ... while (x < 1.0) > ... x += 0.1; > ... return x; > ... } > ... ''') > >>> rc = os.system('gcc -shared -o tmp.so tmp.c') > >>> tmp = ctypes.CDLL('./tmp.so') > >>> tmp.test_d.restype = ctypes.c_double > >>> tmp.test_f.restype = ctypes.c_float > >>> tmp.test_d() > 1.0999 > >>> tmp.test_f() > 1.001192092896 Thanks eryksun, that example taught me more than one thing there. Best, Amit. -- http://echorand.me ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Alternatives to append() for "growing" a list
On Sun, Dec 1, 2013 at 7:27 PM, spir wrote: > On 12/01/2013 05:32 AM, Amit Saha wrote: >> >> Hello, >> >> I was told by someone (as a comment) that a code snippet such as this >> "would make Pythonistas talk my ear off about how evil the append()" >> function is: >> >>>>> mylist = [] >>>>> mylist.append(1) >> >> # a number of times over >> >> I have some ideas that on an append() the list's internal size >> increases (doubled?) since CPython over-allocates memory, and such. >> >> So, the question is: what is the alternative to growing a list when I >> have no idea what items or how many may be there? > > > Maybe you are confusing with catenating _strings_, rather than lists. > Python's concat is problematic because it is a binary operation. So, > catenating n bits makes n-1 operations, each with intermediate results, of > growing sizes, all thrown away except for the last one, the actual result. > If all of the bitN are strings: > bit1 + bit2 + bit3 + bit4 + bit5 > actually constructs: > bit1+bit2 > bit1+bit2+bit3 > bit1+bit2+bit3+bit4 > bit1+bit2+bit3+bit4+bit5 > A number of unneeded string object, and a very big useless memory weight. Thanks Denis, good to know this is how it is done. I hadn't thought about it simply because, never have probably concatenated strings beyond the simple "adding a new line" to a string. Best, Amit. -- http://echorand.me ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Unit testing in Python (3.3.0) for beginners
On Sun, Dec 8, 2013 at 8:22 PM, Rafael Knuth wrote: > Hey there, > > I struggle to understand what unit testing specifically means in > practice and how to actually write unit tests for my code (my gut is > telling me that it's a fairly important concept to understand). Your gut feeling is right. However, you will only *truly* understand it's usefulness as you write more programs yourself. No matter how many articles or blog posts or books you read it in, it's something which you will yourself have to "realize" and once you do so, you will find great value in it. Also, don't fret if you don't realize it. You will, sooner or latter. Here is a fairly common use case where you will really find tests useful (try it!): Say, you have a fairly big program, single file (module) or spread across multiple files. Now, as you improve your understanding, you realize that you can write more efficient/elegant code. So you go on a wholesale refactoring spree (the technical term for changing your existing code to cleanup your existing code to write more optimized or idiomatic code). However, you are not very confident that all the changes haven't broken any of your existing features. So, what do you do? When you don't have tests, you have to manually imagine and run the programs for all possible inputs and check if the output/results are as expected. On the other hand, if you have a tests, you can simply run these tests and refactor your code confidently. However, I have also realized during my own learning adventures and learning from the existing code base and users' bug reports that the benefit of tests are solely dependent on the the "test cases" you have covered in your tests. If you missed a scenario (a test case) in your tests, then it is likely that any breakage of functionality in that area of your program will not be undetected when you run the tests. > > Over the last few days I learned how to write and work with classes, I > learned quite a lot about functions, nested loops and I currently walk > through every program in the Python.org wiki "Simple Programs" > https://wiki.python.org/moin/SimplePrograms ... and here's the unit > test program they provide: > > import unittest > def median(pool): > copy = sorted(pool) > size = len(copy) > if size % 2 == 1: > return copy[(size - 1) / 2] > else: > return (copy[size/2 - 1] + copy[size/2]) / 2 BTW, this program will not work in Python 3, since a division operation returns a float. so, 4/2 = 2.0 . > class TestMedian(unittest.TestCase): > def testMedian(self): > self.failUnlessEqual(median([2, 9, 9, 7, 9, 2, 4, 5, 8]), 7) > if __name__ == '__main__': > unittest.main() > > Also, I went through the "Beginning Test-Driven Development in Python" > http://net.tutsplus.com/tutorials/python-tutorials/test-driven-development-in-python/ > but I have to admit I still don't fully understand how unit tests work > in practice and how to write my own unit tests. I will attempt an explanation with a far simpler function: # myarith.py def sum(a,b): return a+b Let's say you have saved this function in a module, myarith.py. Now, how would you really verify if the function actually returns the sum of the numbers passed to it? By calling the function of course. Here is one way: >>> import myarith >>> myarith.sum(1, 2) 3 >>> myarith.sum(1, 5) 6 >>> myarith.sum(-11, -5) -16 test case So, you are confident that your function works as expected. Now, instead of calling your function as above, you want to use the unittest module. Here is a test module which tests the above function: # test_arith.py import unittest import myarith class ArithTest(unittest.TestCase): def test_sum(self): self.assertEqual(myarith.sum(1,2), 1+2) if __name__ == '__main__': unittest.main() We first create a class ArithTest which is a subclass of unittest.TestCase. This means that, the class ArithTest is a test case and in it you will have various tests to test the functions in your myarith module. Right now, there is only one function, sum(). So, we create a function, test_sum() where we call the sum() function as above, but we call it inside the assertEqual() method which basically tests whether the first argument's value is equal to the second argument. Now, when you run this module, you will see something like: $ python3 test_arith.py . -- Ran 1 test in 0.000s OK Now, let us modify the test_sum() method: import unittest import myarith class ArithTest(unittest.TestCase): def test_sum(self): self.assertEqual(myarith.sum(1,2), 1+2) def test_sum_2(self): self.assertEqual(myarith.sum(2,2), 15) if __name__ == '__main__': unittest.main() A new test has been added, test_sum_2() which is obviously going to fail. Let's see what happens when we run the module again: .F ===
Re: [Tutor] Suggestion required on python as scripting language
Hello, On Sun, Dec 8, 2013 at 4:59 PM, Shankar Donepudi wrote: > Hi All, > > I am working as test engineer in Networking in storage domain. We have > decided to automate our testing and have chosen python for the same. We have > basic knowledge on python so can anyone suggest good tutorials for writing > automation scripts using python. As others have mentioned, you will most need to be more specific about what you are trying to do and any specific problems you are facing. I am going to take a guess and perhaps a book such "Python for Unix and Linux System Administration" [1] may give you some ideas. I also wrote this article a while ago [2] which is a fairly basic introduction/treatment of exploring Linux using Python. [1] http://shop.oreilly.com/product/9780596515829.do (The reviews aren't so good, but I did go through it and you will likely find useful things there) [2] http://amitsaha.github.io/site/notes/articles/python_linux/article.html Best, Amit. -- http://echorand.me ___ 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 6:08 PM, Rafael Knuth 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. >>> sum([int(digit) for digit in str(55)]) 10 That's using list comprehensions. Since a string is basically a sequence, you can do the above. Best, Amit. -- http://echorand.me ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] What is a namespace? What is meant by "A namespace is a mapping from names to objects"
On Mon, Dec 9, 2013 at 2:46 PM, Varuna Seneviratna wrote: >> Let’s begin with some definitions. >> >> A namespace is a mapping from names to objects. Most namespaces are >> currently implemented as Python dictionaries, but that’s normally not >> noticeable in any way (except for performance), and it may change in the >> future. Examples of namespaces are: the set of built-in names (containing >> functions such as abs(), and built-in exception names); the global names in >> a module; and the local names in a function invocation. In a sense the set >> of attributes of an object also form a namespace. The important thing to >> know about namespaces is that there is absolutely no relation between names >> in different namespaces; for instance, two different modules may both define >> a function maximize without confusion — users of the modules must prefix it >> with the module name. > >The above paragraph was extracted from the description about namespaces > from the Python tutorial(Python Scopes and Namespaces).I do not understand > what is meant by "A namespace is a mapping from names to objects". How I > understand to be a namespace is a particular space within which a particular > name is unique.For a example within the space set of built-in names the name > "abs()" is used to denote the function which returns the absolute value of a > number and no other function(operation) can be named abs() as a built-in > function.Am I right?. You can name anything else as abs - a function, for example. But that will override the built-in abs() function. For example: >>> abs(1) # built-in abs 1 >>> def abs(num): ... print('In my abs') ... ... >>> abs(1) In my abs Similarly: >>> abs = 1 >>> abs() Traceback (most recent call last): File "", line 1, in TypeError: 'int' object is not callable But what is meant by "A namespace is a mapping from > names to objects" I don't think I can explain this clearly enough to help elucidate the literal meaning, so I hope somebody else will. Best, Amit. -- http://echorand.me ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Unit testing in Python (3.3.0) for beginners
On Sun, Dec 8, 2013 at 8:22 PM, Rafael Knuth wrote: > Hey there, > > I struggle to understand what unit testing specifically means in > practice and how to actually write unit tests for my code (my gut is > telling me that it's a fairly important concept to understand). > > Over the last few days I learned how to write and work with classes, I > learned quite a lot about functions, nested loops and I currently walk > through every program in the Python.org wiki "Simple Programs" > https://wiki.python.org/moin/SimplePrograms ... and here's the unit > test program they provide: > > import unittest > def median(pool): > copy = sorted(pool) > size = len(copy) > if size % 2 == 1: > return copy[(size - 1) / 2] > else: > return (copy[size/2 - 1] + copy[size/2]) / 2 > class TestMedian(unittest.TestCase): > def testMedian(self): > self.failUnlessEqual(median([2, 9, 9, 7, 9, 2, 4, 5, 8]), 7) > if __name__ == '__main__': > unittest.main() > > Also, I went through the "Beginning Test-Driven Development in Python" > http://net.tutsplus.com/tutorials/python-tutorials/test-driven-development-in-python/ > but I have to admit I still don't fully understand how unit tests work > in practice and how to write my own unit tests. > > As it turned out over the last few weeks, the best modus operandi for > me as an absolute beginner is to grab a small program, take it apart > in the first place, understand how each component works through trial > & error, then put all those pieces together and then I kind of get the > big picture. Once I "get it" I practice as much as possible to > memorize what I just learned and *then* I start readying as many > blogs, tutorials etc. as possible to deepen my understanding (I > frankly find most tutorials & blogs too complex and confusing from a > beginner's viewpoint, and I learn faster by taking code apart and > learning through trial & error in the first place). So, what I am > specifically searching for is a very simple code sample which I can > take apart and iterate through each component, and I was wondering if > you are aware of resources that might be helpful? > > My understanding of unit testing is that I have to embed my code into > a test and then I have to define conditions under which my code is > supposed to fail and pass. Is that assumption correct? > > I am a bit lost & confused here .. any help & hing is highly appreciated! Here is an article I came across today that you may find useful: http://www.jeffknupp.com/blog/2013/12/09/improve-your-python-understanding-unit-testing/ Best, Amit. -- http://echorand.me ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] list comprehension equivalent to map(function, list item)
On Sat, Dec 14, 2013 at 11:03 AM, Bo Morris wrote: > i have the following simple function that iterates over the list. It passes > the list item into the function and adds the numbers. What would be the > equivalent way of writing the "map" portion with list comprehension? My code > is as follows: > > def add(number): > print 1 + int(number) > > > > x = ['2', '4', '6', '8', '10', '12'] > > map(add, x) Think of a list comprehension as: [ dosomething(item) for item in alist] And, comparing it with your map implementation, here is what you get: >>> [1+int(item) for item in x] [3, 5, 7, 9, 11, 13] Here, dosomething(item) corresponds to 1+int(item). Hope that helps. -Amit. -- http://echorand.me ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] weird lambda expression -- can someone help me understand how this works
On Sat, Dec 14, 2013 at 12:14 PM, Michael Crawford wrote: > I found this piece of code on github > > https://gist.github.com/kljensen/5452382 > > def one_hot_dataframe(data, cols, replace=False): > """ Takes a dataframe and a list of columns that need to be encoded. > Returns a 3-tuple comprising the data, the vectorized data, > and the fitted vectorizor. > """ > vec = DictVectorizer() > mkdict = lambda row: dict((col, row[col]) for col in cols) > #<< > vecData = pandas.DataFrame(vec.fit_transform(data[cols].apply(mkdict, > axis=1)).toarray()) > vecData.columns = vec.get_feature_names() > vecData.index = data.index > if replace is True: > data = data.drop(cols, axis=1) > data = data.join(vecData) > return (data, vecData, vec) > > I don't understand how that lambda expression works. > For starters where did row come from? > How did it know it was working on data? Consider this simple example: >>> l = lambda x: x**2 >>> apply(l, (3,)) 9 A lambda is an anonymous function. So, when you use apply(), the lambda, l gets the value 3 in x and then returns x**2 which is 9 in this case. Hope this helps you. Best, Amit. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] weird lambda expression -- can someone help me understand how this works
On Sat, Dec 14, 2013 at 12:29 PM, Amit Saha wrote: > On Sat, Dec 14, 2013 at 12:14 PM, Michael Crawford wrote: >> I found this piece of code on github >> >> https://gist.github.com/kljensen/5452382 >> >> def one_hot_dataframe(data, cols, replace=False): >> """ Takes a dataframe and a list of columns that need to be encoded. >> Returns a 3-tuple comprising the data, the vectorized data, >> and the fitted vectorizor. >> """ >> vec = DictVectorizer() >> mkdict = lambda row: dict((col, row[col]) for col in cols) >> #<<<<<<<<<<<<<<<<<< >> vecData = pandas.DataFrame(vec.fit_transform(data[cols].apply(mkdict, >> axis=1)).toarray()) >> vecData.columns = vec.get_feature_names() >> vecData.index = data.index >> if replace is True: >> data = data.drop(cols, axis=1) >> data = data.join(vecData) >> return (data, vecData, vec) >> >> I don't understand how that lambda expression works. >> For starters where did row come from? >> How did it know it was working on data? > > Consider this simple example: > >>>> l = lambda x: x**2 >>>> apply(l, (3,)) > 9 > > A lambda is an anonymous function. So, when you use apply(), the > lambda, l gets the value 3 in x and then returns x**2 which is 9 in > this case. Argh, no sorry, that doesn't answer your question. Sorry, my bad. I should have read your query properly. -- http://echorand.me ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor