Answers to homework questions [WAS]: Re: Python homework
Hi Roger, On 13/12/17 23:31, ROGER GRAYDON CHRISTMAN wrote: On Wed, Dec 13, 2017, Lorenzo Sutton wrote: On 05/12/17 06:33, nick martinez2 via Python-list wrote: I have a question on my homework. [...] For this kind of problem I think the collections module [1] can be very useful. In this case in particular have a look at the Counter package ;) [...] A nice answer at face value, and for general questions, but perhaps not the best given the subject line and the first sentence in the OP's note. > [...] When I teach my course, I have no desire to have all my students turn into cargo cultists. At least this particular student did post his intended solution, instead of outright begging for code. And most of the responses I see did attempt to work within the perceived constraints regarding what language tools the student was expected to use. I see your point as a teacher, but after all this *is* a Python mailing list and not a python-homework-support mailing list. Plus, the OP had already received various good answers specifically helping them solve the problem along the lines of his proposed code, so I guessed hinting to a standard library module which is interesting and potentially relevant in this case might be useful to both the OP and other people on the ML while enriching the discussion ;-) Best, Lorenzo. -- https://mail.python.org/mailman/listinfo/python-list
Re: Python homework
Hi, On 05/12/17 06:33, nick martinez2 via Python-list wrote: I have a question on my homework. My homework is to write a program in which the computer simulates the rolling of a die 50 times and then prints (i). the most frequent side of the die (ii). the average die value of all rolls. For this kind of problem I think the collections module [1] can be very useful. In this case in particular have a look at the Counter package ;) Lorenzo. [1] https://docs.python.org/3.6/library/collections.html I wrote the program so it says the most frequent number out of all the rolls for example (12,4,6,14,10,4) and will print out "14" instead of 4 like I need. This is what I have so far: import random def rollDie(number): rolls = [0] * 6 for i in range(0, number): roll=int(random.randint(1,6)) rolls[roll - 1] += 1 return rolls if __name__ == "__main__": result = rollDie(50) print (result) print(max(result)) -- https://mail.python.org/mailman/listinfo/python-list
Re: How to reduce the DRY violation in this code
On 27/09/2016 17:49, Steve D'Aprano wrote: I have a class that takes a bunch of optional arguments. They're all optional, with default values of various types. For simplicity, let's say some are ints and some are floats: class Spam: def __init__(self, bashful=10.0, doc=20.0, dopey=30.0, grumpy=40, happy=50, sleepy=60, sneezy=70): # the usual assign arguments to attributes dance... self.bashful = bashful self.doc = doc # etc. I also have an alternative constructor that will be called with string arguments. May I ask: do you really need to add this method? Can't you ensure that the data passed during initialisation is already of the right type (i.e. can you convert to float/ints externally)? If now why? Lorenzo. It converts the strings to the appropriate type, then calls the real constructor, which calls __init__. Again, I want the arguments to be optional, which means providing default values: @classmethod def from_strings(cls, bashful='10.0', doc='20.0', dopey='30.0', grumpy='40', happy='50', sleepy='60', sneezy='70'): bashful = float(bashful) doc = float(doc) dopey = float(dopey) grumpy = int(grumpy) happy = int(happy) sleepy = int(sleepy) sneezy = int(sneezy) return cls(bashful, doc, dopey, grumpy, happy, sleepy, sneezy) That's a pretty ugly DRY violation. Imagine that I change the default value for bashful from 10.0 to (let's say) 99. I have to touch the code in three places (to say nothing of unit tests): - modify the default value in __init__ - modify the stringified default value in from_strings - change the conversion function from float to int in from_strings Not to mention that each parameter is named seven times. How can I improve this code to reduce the number of times I have to repeat myself? -- https://mail.python.org/mailman/listinfo/python-list
Re: python parsing suggestion
Hi, On 30/05/2016 09:34, Ganesh Pal wrote: Hi , Trying to extract the '1,1,114688:8192' pattern form the below output. pdb>stdout: '3aae5d0-1: Parent Block for 1,1,19169280:8192 (block 1,1,114688:8192) --\n3aae5d0-1: magic 0xdeaff2fe mark_cookie 0x\ngpal-3aae5d0-1: super.status 3super.cookie 390781895\ngpal-3aae5d0-1: cg_xth 0 What parts of the string (i any) can we assume to always be the same? 1. Is parsing with stdout.strip().split('\n')[0].split()[6][:-1] sufficient do I need to add extra check ? it looks fine for me though. 2. Better ways to achieve the same output we need to parse is a string 3. Is re.search(r'(\d+),(\d+),(\d+):(\d+)', parent_block) needed ? I added as an extra check ,any ideas on the same Regards, Ganesh -- https://mail.python.org/mailman/listinfo/python-list
Re: The irony
On 10/05/2016 20:03, DFS wrote: "There should be one-- and preferably only one --obvious way to do it." https://www.python.org/dev/peps/pep-0020/ "Explicit is better than implicit." What is your use case and scenario? :-) Maybe it's better to write a function to automatise this so that if instead of "line 1\n ..." you want "banana 1~banana 2~ " etc. you can simply change parameters? That said join and list comprehensions would also come to mind, but not sure how "obvious" that is... Lorenzo. --- sSQL = "line 1\n" sSQL += "line 2\n" sSQL += "line 3" --- sSQL = ("line 1\n" "line 2\n" "line 3") --- sSQL = "\n".join([ "line 1", "line 2", "line 3", ]) --- sSQL = """line 1 line 2 line 3""" --- sSQL = """\ line 1 line 2 line 3""" --- sSQL = "line 1\n" \ "line 2\n" \ "line 3" --- Which is the "one obvious way" to do it? I liked: sSQL = "line 1\n" sSQL += "line 2\n" sSQL += "line 3" but it's frowned upon in PEP8. -- https://mail.python.org/mailman/listinfo/python-list
Re: Tk alternative to askopenfilename and askdirectory?
On 16/12/2015 14:18, Ulli Horlacher wrote: Is there an alternative to Tk's askopenfilename() and askdirectory()? I want to select a files and directories within one widget, but askopenfilename() let me only select files and askdirectory() let me only select directories. I guess it would help if you could provide some information on your use case and what you want to achieve ;) Lorenzo. -- https://mail.python.org/mailman/listinfo/python-list
Re: Question about math.pi is mutable
On 06/11/2015 13:30, Bartc wrote: On 06/11/2015 02:33, wa...@travelsky.com wrote: Hello, python-list guys: I am a newbie of python from Beijing. China. I have a question about "math.pi". As you can see in the attachment, why i can modify "math.pi"? (in "mathmodule.c" "pi" is a "static const double") Python isn't C. Your attachment isn't visible, but it can be demonstrated easily: import math math.pi=0 print (math.pi) In Python, presumably 'pi' is just another variable, and variables can be written to. (Perhaps math.pi would be better off as a function.) Still nothing stops you from doing: math.sin = 0 If you really want to? -- https://mail.python.org/mailman/listinfo/python-list
Re: Detection of a specific sound
On 26/10/15 01:17, Montana Burr wrote: I'm looking for a library that will allow Python to listen for the shriek of a smoke alarm. Once it detects this shriek, it is to notify someone. Ideally, specificity can be adjusted for the user's environment. For example, I expect to need moderate specificity as I live in a quiet neighborhood, but an apartment dweller might need more. I'm thinking of recording a smoke alarm and having the program try to find the recorded sound in the stream from the microphone. Any help is greatly appreciated! It would really be helpful if you could explain the (hardware) setting in more detail. When you say "Python to listen" I assume you mean a microphone connected to a computer where your python programme will be running. How many smoke allarms and in what radius should be detected? Or is it only a specific one? This could range from a simple programme triggered by an amplitude change (e.g. a piezo attached to the single alarm in question) to a complex audio fingerprinting one... Lorenzo. -- https://mail.python.org/mailman/listinfo/python-list
Re: Python, convert an integer into an index?
On 23/09/2015 17:32, Denis McMahon wrote: On Tue, 22 Sep 2015 14:43:55 -0700, Chris Roberts wrote: results = 134523 #(Integer) This appears to be an integer expressed (presumably) in base 10 with 6 digits Desired: results = [1, 2, 3, 4, 5, 2, 3] #(INDEX) This appears to be a python list of 7 elements, with the first and the the third through seventh elements corresponding to the first and the second through sixth most significant digits respectively of the previously discussed integer. I can't actually see any direct method of creating the list given from the number given. However, if I understand the intent of the question you meant to ask, you might find that the following code does something interesting: x = 9876543210 y = [] while x > 0: y.append(x % 10) x = int(x / 10) y = list(reversed(y)) print y I like the math approach even if the pythonic list string is quicker... One 'math' way would also be (avoiding the list reverse, but need to import math): >>> import math >>> result = 1234567 >>> digits = int(math.log10(result) + 1) >>> y = [] >>> for x in range(digits, 0, -1): number = result % (10 ** x) / (10 **(x-1)) y.append(int(number)) >>> y [1, 2, 3, 4, 5, 6, 7] -- https://mail.python.org/mailman/listinfo/python-list
Python 3 windows installer problem [WAS: Re: an installing problem]
Hi, Not too familiar with the 'new' Python 3 installer on windows.. but On 23/09/2015 13:37, Narges Asadi wrote: Hello I’ve encountered a problem when I wanted to install Python 3.5. I sent you the log file. Please help me to fix the problem. From the log: [0F4C:1110][2015-09-23T14:54:17]e000: Error 0x80072ee7: Failed to send request to URL: https://www.python.org/ftp/python/3.5.0/win32/core_pdb.msi, trying to process HTTP status code anyway. which seems to be reachable now... so maybe a network problem when you were installing?? Look here about installing without downloading, it might be helpful. https://docs.python.org/3/using/windows.html#installing-without-downloading This bug report might also be relevant: https://bugs.python.org/issue25126 Hope this helps. Lorenzo. -- https://mail.python.org/mailman/listinfo/python-list
Re: Pyarmor, guard your python scripts
On 18/09/2015 13:41, Jondy Zhao wrote: [...] In reality, when we leave the house, we lock the door, even the lock could not make sure the safe of our property. It's just make it difficult. It's same in the software world. Someone need the lock in both of the world. I think you meant "in the *proprietary* software world". This discussion on the topic, and in particular this answer, on Stackoverflow are quite inspiring: http://stackoverflow.com/questions/261638/how-do-i-protect-python-code/261727#261727 Lorenzo. -- https://mail.python.org/mailman/listinfo/python-list
Re: XML Binding
Hi, On 03/09/2015 21:54, Burak Arslan wrote: Hello, On 09/03/15 19:54, Palpandi wrote: Hi All, Is there any module available in python standard library for XML binding? If not, any other suggestions. lxml is the right xml library to use. You can use lxml's objectify or Spyne. I second lxml.. [...] Which is good for parsing large file? How large is large? I have used lxml (coupled with pygtk) with very good results on XML files up to around 250Mb. Lorenzo. -- https://mail.python.org/mailman/listinfo/python-list
Re: global and loop control variable
On 23/07/2015 12:24, candide wrote: [...] Now, global declaration has another restriction, as PLR explains: [https://docs.python.org/3.4/reference/simple_stmts.html#the-global-statement] ~ Names listed in a global statement must not be defined as formal parameters or in a for loop control target, ~ What I understand is that the following is a must-not-code: # --- def f(): global i for i in range(1,3): print(10*i) f() print(i) # --- But, the later code executes silently without any warning: ~ 10 20 2 ~ So my question is: what is the restriction about global as loop control variable the docs is referring to? I think for situations like this one? # --- def f(): global temperature for temperature in range(1,3): print In f temperature is:, temperature temperature = 500 print temperature is now, temperature f() printtemperature is now:, temperature # temperature is now broken if temperature = 100: print Launching rocket else: # this never happens print temperature too high! Aborting launch. # --- -- https://mail.python.org/mailman/listinfo/python-list
Re: global and loop control variable
On 23/07/2015 14:31, Steven D'Aprano wrote: On Thu, 23 Jul 2015 09:20 pm, Lorenzo Sutton wrote: On 23/07/2015 12:24, candide wrote: Now, global declaration has another restriction, as PLR explains: [https://docs.python.org/3.4/reference/simple_stmts.html#the-global-statement] ~ Names listed in a global statement must not be defined as formal parameters or in a for loop control target, ~ What I understand is that the following is a must-not-code: def f(): global i for i in range(1,3): print(10*i) [...] So my question is: what is the restriction about global as loop control variable the docs is referring to? You are correct. The above example is exactly the restriction mentions. The very next paragraph in the docs says: CPython implementation detail: The current implementation does not enforce the two restrictions, but programs should not abuse this freedom, as future implementations may enforce them or silently change the meaning of the program. In other words, the behaviour of global loop variables is not guaranteed, and you should not use it even if the compiler/interpreter fails to raise a syntax error. I think for situations like this one? def f(): global temperature for temperature in range(1,3): print In f temperature is:, temperature There's no meaningful difference between the example Candide gave (for i in range) and the example you give (for temperature in range). They both use a global for the loop variable. Only the names differ. Of course... it was just to highlight that it could be potentially, especially if your programme is going to launch a rocket - eventually (see my entire code example) :-) Lorenzo. -- https://mail.python.org/mailman/listinfo/python-list