Re: The "loop and a half"
On 10/3/2017 5:08 PM, Stefan Ram wrote: Steve D'Apranowrites: On Wed, 4 Oct 2017 04:45 am, Rhodri James wrote: On 03/10/17 18:29, Stefan Ram wrote: Is this the best way to write a "loop and a half" in Python? Define "best". I'd start with "define loop and a half". I encountered this phenomenon decades ago. But only some years ago, I heard someone using a special word for it! Let me try to find it ... Yes, it was Mehran Sahami who used it, possibly in one of his lectures of the course "Programming Methodology" (CS 106A) at "Stanford Engineering". ... The history of this problem goes way back into the past. In the 1950s (and possibly still inthe 1960s), such mundane loops were research topics, and Knuth and others wrote research articles about how to write such a loop in such a way that no test or statement has to be repeated. (I sometimes liked to read old magazines from those years.) Thanks for all the answers so far! I'm adding to what Stefan wrote, simply to point out how a newb like me came across this issue formally, besides actually dealing with this in my practice. In Python Programming Fundamentals 2nd ed., the author, Kent D. Lee, brings up loop and a half in ch. 3, Repetitive Tasks (p. 82). He wrote: "Whether you are writing code in Python or some other language, this Reading Records From a File pattern comes up over and over again. It is sometimes called the loop and a half problem. The idea is that you must attempt to read a line from the file before you know whether you are at the end of file or not. This can also be done if a boolean variable is introduced to help with the while loop. This boolean variable is the condition that gets you out of the while loop and the first time through it must be set to get your code to execute the while loop at least one." best, John -- https://mail.python.org/mailman/listinfo/python-list
Re: TypeError with map with no len()
On 9/25/2017 5:37 PM, Thomas Jollans wrote: On 25/09/17 18:44, john polo wrote: Python List, I am trying to make practice data for plotting purposes. I am using Python 3.6. The instructions I have are import matplotlib.pyplot as plt import math import numpy as np t = np.arange(0, 2.5, 0.1) y1 = map(math.sin, math.pi*t) If you use np.sin instead of math.sin, you don't have to use map: Most numpy functions operate elementwise on arrays (for example, you're multiplying math.pi with an array - something that wouldn't work with a list). Here's the numpy way of doing this: t = np.arange(0, 2.5, 0.1) y1 = np.sin(np.pi * t) Without using numpy at all, this might be t = [i * 0.1 for i in range(25)] y1 = [math.pi * a for a in t] The numpy way looks like a great alternative. Thank you, Thomas. John -- https://mail.python.org/mailman/listinfo/python-list
Re: TypeError with map with no len()
On 9/25/2017 12:03 PM, Paul Moore wrote: You're using Python 3, and I suspect that you're working from instructions that assume Python 2. In Python 3, the result of map() is a generator, not a list (which is what Python 2's map returned). In order to get an actual list (which appears to be what you need for your plot call) you just need to call the list constructor: y1 = list(map(math.sin, math.pi*t)) Although given that you're using numpy, it may be that there's a more idiomatic numpy way of doing this. I'm not a numpy expert though, so I can't help on that. Paul Paul, Thank you very much for the explanation. best regards, John -- https://mail.python.org/mailman/listinfo/python-list
TypeError with map with no len()
Python List, I am trying to make practice data for plotting purposes. I am using Python 3.6. The instructions I have are import matplotlib.pyplot as plt import math import numpy as np t = np.arange(0, 2.5, 0.1) y1 = map(math.sin, math.pi*t) plt.plot(t,y1) However, at this point, I get a TypeError that says object of type 'map' has no len() In [6]: t Out[6]: array([ 0. , 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1. , 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 1.7, 1.8, 1.9, 2. , 2.1, 2.2, 2.3, 2.4]) In [7]: y1 Out[7]: In [8]: math.pi*t Out[8]: array([ 0. , 0.31415927, 0.62831853, 0.9424778 , 1.25663706, 1.57079633, 1.88495559, 2.19911486, 2.51327412, 2.82743339, 3.14159265, 3.45575192, 3.76991118, 4.08407045, 4.39822972, 4.71238898, 5.02654825, 5.34070751, 5.65486678, 5.96902604, 6.28318531, 6.59734457, 6.91150384, 7.2256631 , 7.53982237]) At the start of creating y1, it appears there is an array to iterate through for the math.sin function used in map(), but y1 doesn't appear to be saving any values. I expected y1 to hold a math.sin() output for each item in math.pi*t, but it appears to be empty. Am I misunderstanding map()? Is there something else I should be doing instead to populate y1? John -- https://mail.python.org/mailman/listinfo/python-list
Re: Re: errors with json.loads
On 9/21/2017 10:11 AM, Ned Batchelder wrote: I can only assume that the actual data being read is different than the data they put into the message here. --Ned. There was a typo in the file that I had made and saved; an extra comma before one of the ":". Apologies to the list for not catching that sooner. John -- https://mail.python.org/mailman/listinfo/python-list
Re: Re: errors with json.loads
On 9/21/2017 4:24 AM, Thomas Jollans wrote: It looks to me like the root cause of the problem was that they copied the code from a web page, and the web page contained invalid JSON. Thank you, Thomas. John -- https://mail.python.org/mailman/listinfo/python-list
Re: Re: errors with json.loads
On 9/20/2017 6:40 PM, Dennis Lee Bieber wrote: On Wed, 20 Sep 2017 17:13:41 -0500, john polo <jp...@mail.usf.edu> declaimed the following: and the example code for reading the file is: file = open('books.json','r') What encoding is the file? I did a cut from your post into a file, and the contents (Python 2.7) failed with Dennis, I typed it into notepad++ and saved as .json. On the bottom of the notepad++ window it says: Windows (CR LF) UTF-8 I think that answers your question? Thanks, John -- "Ask a man to be quiet, and he'll be silent for a moment. Feed a man to a red dragon and he'll be silent for a lifetime." -Anne Isabella Thackeray Ritchie -- https://mail.python.org/mailman/listinfo/python-list
Re: Re: errors with json.loads
On 9/20/2017 5:58 PM, Bill wrote: Interesting problem, John. I have probably even less experience with json than you do, so I'm taking this as an opportunity to learn with you. Suggestions: 1. Try your example with Python 2 rather than Python 3. Bill, Thanks for the reply. I wasn't sure how to get Python 2 through the cmd or IPython, so I went through ArcGIS, but it's mostly the same result: >>> file = open('books.json','r') >>> text = file.read() >>> text = json.loads(text) Runtime error Traceback (most recent call last): File "", line 1, in NameError: name 'json' is not defined >>> import json #whoops, forget to do that first in this go 'round. >>> text = json.loads(text) Runtime error Traceback (most recent call last): File "", line 1, in File "C:\Python27\ArcGIS10.4\Lib\json\__init__.py", line 338, in loads return _default_decoder.decode(s) File "C:\Python27\ArcGIS10.4\Lib\json\decoder.py", line 366, in decode obj, end = self.raw_decode(s, idx=_w(s, 0).end()) File "C:\Python27\ArcGIS10.4\Lib\json\decoder.py", line 382, in raw_decode obj, end = self.scan_once(s, idx) ValueError: Expecting : delimiter: line 5 column 50 (char 161) >>> 2. Take your file and make it into a string literal in your program, and try calling json.loads with that as an argument. I am not sure I follow what you meant, but this was what I did: In [26]: file2 = open('books.txt') In [27]: text2 = file2.read() In [28]: text2 = json.loads(text2) --- JSONDecodeError Traceback (most recent call last) in () > 1 text2 = json.loads(text2) c:\users\jpolo\appdata\local\programs\python\python36\lib\json\__init__.py in lo ads(s, encoding, cls, object_hook, parse_float, parse_int, parse_constant, objec t_pairs_hook, **kw) 352 parse_int is None and parse_float is None and 353 parse_constant is None and object_pairs_hook is None and not kw): --> 354 return _default_decoder.decode(s) 355 if cls is None: 356 cls = JSONDecoder c:\users\jpolo\appdata\local\programs\python\python36\lib\json\decoder.py in dec ode(self, s, _w) 337 338 """ --> 339 obj, end = self.raw_decode(s, idx=_w(s, 0).end()) 340 end = _w(s, end).end() 341 if end != len(s): c:\users\jpolo\appdata\local\programs\python\python36\lib\json\decoder.py in raw _decode(self, s, idx) 353 """ 354 try: --> 355 obj, end = self.scan_once(s, idx) 356 except StopIteration as err: 357 raise JSONDecodeError("Expecting value", s, err.value) from None JSONDecodeError: Expecting ':' delimiter: line 5 column 50 (char 161) best, John -- https://mail.python.org/mailman/listinfo/python-list
Re: Re: errors with json.loads
On 9/20/2017 5:56 PM, John Gordon wrote: In <mailman.101.1505945630.2730.python-l...@python.org> john polo <jp...@mail.usf.edu> writes: JSONDecodeError: Expecting ':' delimiter: line 5 column 50 (char 161) ?json.loads says that the method is for deserializing "s", with "s" being a string, bytes, or bytearray. In [24]: type(text) Out[24]: str So "text" seems to be a string. Why does json.loads return an error? Because, although text is the right type, it does not contain a valid json string. Thank you for the reply, John. I am not familiar with how to check validity for json. I typed the example into notepad++ and saved as .json and didn't take any further steps after that. I'll look into that. John -- https://mail.python.org/mailman/listinfo/python-list
errors with json.loads
Greetings, I am using IPython 6.1.0 with Python 3.6.2 on a Windows 7 machine. I am not a programmer. I am using a book called Python Data Analytics to try to learn some of Python. I am at a section for reading and writing JSON data. The example JSON file is: Listing 5-13. books.json [{"writer": "Mark Ross", "nationality": "USA", "books": [ {"title": "XML Cookbook", "price": 23.56}, {"title": "Python Fundamentals", "price": 50.70}, {"title": "The NumPy library", "price": 12.30} ] }, {"writer": "Barbara Bracket", "nationality": "UK", "books": [ {"title": "Java Enterprise", "price": 28.60}, {"title": "HTML5", "price": 31.35}, {"title": "Python for Dummies", "price": 28.00} ] }] and the example code for reading the file is: >>> file = open('books.json','r') >>> text = file.read() >>> text = json.loads(text) When I use those 3 lines, I get the following: JSONDecodeError Traceback (most recent call last) in () > 1 text = json.loads(text) c:\users\..\python\python36\lib\json\__init__.py in loads(s, encoding, cls, object_hook, parse_float, parse_int, parse_constant, object_pairs_hook, **kw) 352 parse_int is None and parse_float is None and 353 parse_constant is None and object_pairs_hook is None and not kw): --> 354 return _default_decoder.decode(s) 355 if cls is None: 356 cls = JSONDecoder c:\users\..\python\python36\lib\json\decoder.py in decode(self, s, _w) 337 338 """ --> 339 obj, end = self.raw_decode(s, idx=_w(s, 0).end()) 340 end = _w(s, end).end() 341 if end != len(s): c:\users\..\python\python36\lib\json\decoder.py in raw_decode(self, s, idx) 353 """ 354 try: --> 355 obj, end = self.scan_once(s, idx) 356 except StopIteration as err: 357 raise JSONDecodeError("Expecting value", s, err.value) from None JSONDecodeError: Expecting ':' delimiter: line 5 column 50 (char 161) ?json.loads says that the method is for deserializing "s", with "s" being a string, bytes, or bytearray. In [24]: type(text) Out[24]: str So "text" seems to be a string. Why does json.loads return an error? John -- https://mail.python.org/mailman/listinfo/python-list
Re: script output appears correct but still raises, AssertionError
ChrisA, Thank you for pointing out my error: using print() when I should have used return(). John -- https://mail.python.org/mailman/listinfo/python-list
script output appears correct but still raises AssertionError
Python People, I am learning about assertions. I wrote a small script that takes 2 inputs, an amino acid sequence and one residue symbol. The script should return what percent of the sequence is residue in output. The point of this script is to use assert for debugging. My script seems to work correctly, but when I use the assert statements that are supposed to test the script, the assertions indicate there is a problem with the script. >>> def aminosleft(sequence, res): ... sequp = sequence.upper() ... lens1 = len(sequp) ... rep = res.upper() ... reps2 = sequp.replace(rep,"") ... lens2 = len(reps2) ... resid = 100* (lens1 - lens2) / lens1 ... print(int(resid)) ... ... >>> aminosleft("MSRSLLLRFLLFPPLP", "M") 5 >>> assert aminosleft("MSRSLLLRFLLFPPLP", "M") == 5 5 Traceback (most recent call last): File "", line 1, in AssertionError >>> aminosleft("MSRSLLLRFLLFPPLP", "r") 10 >>> assert aminosleft("MSRSLLLRFLLFPPLP", "r") == 10 10 Traceback (most recent call last): File "", line 1, in AssertionError >>> aminosleft("msrslllrfllfpplp", "L") 50 >>> assert aminosleft("msrslllrfllfpplp", "L") == 50 50 Traceback (most recent call last): File "", line 1, in AssertionError >>> aminosleft("MSRSLLLRFLLFPPLP", "Y") 0 >>> assert aminosleft("MSRSLLLRFLLFPPLP", "Y") == 0 0 Traceback (most recent call last): File "", line 1, in AssertionError The script returns an integer. I don't know if the assertion uses an integer or if that matters. What is causing the AssertionError? John -- https://mail.python.org/mailman/listinfo/python-list
Re: read in a list in a file to list
On 4/8/2017 3:21 PM, breamore...@gmail.com wrote: On Saturday, April 8, 2017 at 7:32:52 PM UTC+1, john polo wrote: Hi, I am using Python 3.6 on Windows 7. I have a file called apefile.txt. apefile.txt's contents are: apes = "Home sapiens", "Pan troglodytes", "Gorilla gorilla" I have a script: apefile = open("apefile.txt") apelist = apefile.read() for ape in apelist: print("one of the apes is " + ape) apefile.close() The output from the script does not print the ape names, instead it prints each letter in the file. For example: one of the apes is a one of the apes is p one of the apes is e What should I do instead to get something like one of the apes is Home sapiens one of the apes is Pan troglodytes one of the apes is Gorilla gorilla John I'll start you off. with open("apefile.txt") as apefile: for line in apefile: doSomething(line) String methods and/or the csv module might be used here in doSomething(line), but I'll leave that to you so that you can learn. If you get stuck please ask again, we don't bite :) Kindest regards. Mark Lawrence. Mark, Thanks for the reply. I looked back through the methods for strings. I also looked at the csv module, but I couldn't tell which one of those would help. The small .txt file does have commas, but with the weird form of listname = [1] , [2], [3], etc. for a .csv, I don't know how that would be read in a like a .csv. But now that I think about it, datObj2 in my script prints just the list elements, so maybe the 'listname=' part wouldn't affect it... Anyway, after reviewing string methods some more, I came up with this. If I understood your hint, the loop was supposed to somehow break up the long string that came from the apelist file, but it seemed that trying to use the split method in a loop wouldn't work, especially since one of my attempts started a list and then the interpreter said there were no split methods for list. The new attempt gives me a list, now I have to figure out how to deal with unwanted quotation marks and spaces. datFil = open("apelist.txt") datObj = datFil.read() datObj2 = datObj.replace('" ','') #added this comment while writing this email: I guess I could have used 'datObj = datFil.read().replace('" ','')'. Can you make two replacements in the same statement, for example 'datObj=datFil.read().replace('" ','').replace('"','')? datObj2 = datObj2.replace('"','') #this was here to try to get rid of " that didn't have a subsequent space. datObj2 = datObj2.split(',') print(datObj2) for i in datObj2: print("one of the apes is " + i) datFil.close() Output: ['Homo sapiens', ' Pan troglodytes', ' Gorilla gorilla'] one of the apes is Homo sapiens one of the apes is Pan troglodytes one of the apes is Gorilla gorilla Per reply of Rick Johnson, I altered variable names to something generic. Thanks for the prodding from the replies. John -- https://mail.python.org/mailman/listinfo/python-list
read in a list in a file to list
Hi, I am using Python 3.6 on Windows 7. I have a file called apefile.txt. apefile.txt's contents are: apes = "Home sapiens", "Pan troglodytes", "Gorilla gorilla" I have a script: apefile = open("apefile.txt") apelist = apefile.read() for ape in apelist: print("one of the apes is " + ape) apefile.close() The output from the script does not print the ape names, instead it prints each letter in the file. For example: one of the apes is a one of the apes is p one of the apes is e What should I do instead to get something like one of the apes is Home sapiens one of the apes is Pan troglodytes one of the apes is Gorilla gorilla John -- https://mail.python.org/mailman/listinfo/python-list
Re: syntax error in first-time user script
I had a misconception of how the Python interpreter works. If I have a script, call it example.py, in order to run it, I shouldn't be in the interpreter? In other words, I should be at the Windows command prompt, for example C:/test> python example.py and not >>> python example.py ? So, if I am already on >>> and have a problem with a script and need to edit it and want to run the script again, how do I do that? Do I exit the interpreter and start it again? Or is there a different way to run the script once the interpreter is active and I am at >>> ? Cheers, John -- https://mail.python.org/mailman/listinfo/python-list
Re: syntax error in first-time user script
On 3/24/2017 9:11 AM, Bob Gailer wrote: On Mar 24, 2017 4:53 AM, "john polo" <jp...@mail.usf.edu <mailto:jp...@mail.usf.edu>> wrote: > > Greetings, > I am attempting to learn Python. I have no programming background. I'm on a computer with Windows 7. I checked the PATH in System Variables and Python and Python\Scripts are in the path. I have a book, Python for Biologists and it supplies example scripts, one is called comment.py. The output from comment.py is > > Comments are very useful! > > I use cd to get to the directory with the example scripts We can assume you are at a Windows command prompt. It' a good idea too tell us that, so we don't have to assume! and open a command prompt with "python" and get the prompt. Assumptions / terminology again! Typing "python" normally invokes the python interpreter. Since you did not pass any arguments you get a window displaying the python interpreter prompt (>>>). I type > > "python comment.py" > > and get > > "File "", line 1 > python comment.py > ^ > SyntaxError: invalid syntax It is great (as John said) that you provided the traceback. It would have been even greater if you had given us the rest e.g, Microsoft Windows [Version 10.0.14393] (c) 2016 Microsoft Corporation. All rights reserved. C:\Users\bgailer>cd /examples C:\examples>python Python 3.3.5 (v3.3.5:62cf4e77f785, Mar 9 2014, 10:35:05) [MSC v.1600 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> python comment.py File "", line 1 python comment.py ^ SyntaxError: invalid syntax >>> Which brings up one other important matter: when writing us also tell us which python version you are using. In my example it is 3.3.5. I'm using 3.6.0. > > Sorry, I realize this may not all line up like it does when I'm typing this in the email. The caret/error pointer is under the t in comment. I am not sure what is causing this error. > > If I type > > "import comment.py" > > the output is > > "Comments are very useful! > Traceback (most recent call last): > File "", line 1, in > ModuleNotFoundError: No module named 'comment.py'; 'comment' > " > > If I use IDLE shell: > > "python comment.py" > > "SyntaxError: invalid syntax" > > I know I can open the file in the editor and use F5, but shouldn't I be able to use a command from shell? How do I run comment.py from a command line without error? Or is that not possible? > > cheers, > John > -- > https://mail.python.org/mailman/listinfo/python-list <https://mail.python.org/mailman/listinfo/python-list> -- Men occasionally stumble over the truth, but most of them pick themselves up and hurry off as if nothing had happened. -- Winston Churchill -- https://mail.python.org/mailman/listinfo/python-list
syntax error in first-time user script
Greetings, I am attempting to learn Python. I have no programming background. I'm on a computer with Windows 7. I checked the PATH in System Variables and Python and Python\Scripts are in the path. I have a book, Python for Biologists and it supplies example scripts, one is called comment.py. The output from comment.py is Comments are very useful! I use cd to get to the directory with the example scripts and open a command prompt with "python" and get the prompt. I type "python comment.py" and get "File "", line 1 python comment.py ^ SyntaxError: invalid syntax " Sorry, I realize this may not all line up like it does when I'm typing this in the email. The caret/error pointer is under the t in comment. I am not sure what is causing this error. If I type "import comment.py" the output is "Comments are very useful! Traceback (most recent call last): File "", line 1, in ModuleNotFoundError: No module named 'comment.py'; 'comment' " If I use IDLE shell: "python comment.py" "SyntaxError: invalid syntax" I know I can open the file in the editor and use F5, but shouldn't I be able to use a command from shell? How do I run comment.py from a command line without error? Or is that not possible? cheers, John -- https://mail.python.org/mailman/listinfo/python-list