Re: [Tutor] encoder decoder problem
> On Nov 27, 2018, at 16:17, Alan Gauld via Tutor wrote: > > On 27/11/2018 21:04, Kamina Kamtarin wrote: >> A De/Coder. Think back to 3rd grade when you passed notes to friends in >> class. We can't let the teacher see what we're writing so we used a code. >> A=1, B=2, C=3, etc. Your job is to create a program which does the >> following: >> >> 1. Presents the user with a menu choice: encode or decode >> 2. Depending on what they chose you will either encode letters into >> numbers (seperated by dashes) or decode a series of numbers (separated by >> dashes) into letters. >> 3. For example: >> - "How are you?" would encode as "8-15-23 1-18-5 25-15-21?" >> - "8-15-23 1-18-5 25-15-21" would decode as "How are you?" > > Look at the builtin ord() and chr() functions. > > For example ord('A') -> 65 and ord('a') -> 97 > > Similarly chr(97) -> 'a' and chr(65) -> ‘A' I would also try to break up your requirements into smaller pieces. For example, some things to solve: How would you get input? How would you break up a string into individual characters? How would you break up an encoded string into individual numbers? How would you put the characters/numbers back together for output? Have you started writing any code? What have you tried so far? — David Rock da...@graniteweb.com ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Need help,please!
On 27/11/2018 21:04, Kamina Kamtarin wrote: > A De/Coder. Think back to 3rd grade when you passed notes to friends in > class. We can't let the teacher see what we're writing so we used a code. > A=1, B=2, C=3, etc. Your job is to create a program which does the > following: > >1. Presents the user with a menu choice: encode or decode >2. Depending on what they chose you will either encode letters into >numbers (seperated by dashes) or decode a series of numbers (separated by >dashes) into letters. >3. For example: > - "How are you?" would encode as "8-15-23 1-18-5 25-15-21?" > - "8-15-23 1-18-5 25-15-21" would decode as "How are you?" Look at the builtin ord() and chr() functions. For example ord('A') -> 65 and ord('a') -> 97 Similarly chr(97) -> 'a' and chr(65) -> 'A' Now a little bit of arithmetic should get you to/from 1. How you handle upper/lower case issues is up to you, but if they aren't important then the string upper() and lower() methods may help too. I don't know what you do with punctuation, you didn't say but you should be able to get the core done using the above. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] Need help,please!
A De/Coder. Think back to 3rd grade when you passed notes to friends in class. We can't let the teacher see what we're writing so we used a code. A=1, B=2, C=3, etc. Your job is to create a program which does the following: 1. Presents the user with a menu choice: encode or decode 2. Depending on what they chose you will either encode letters into numbers (seperated by dashes) or decode a series of numbers (separated by dashes) into letters. 3. For example: - "How are you?" would encode as "8-15-23 1-18-5 25-15-21?" - "8-15-23 1-18-5 25-15-21" would decode as "How are you?" ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Error Python version 3.6 does not support this syntax.
On 11/27/18 5:50 AM, srinivasan wrote: > Dear Python Experts, > > As still I am newbie and learning python, I am trying to reuse the > Bluetoothctl wrapper in Python from the link ( > https://gist.github.com/egorf/66d88056a9d703928f93) I am using python3.6 > version, In pycharm editor on the bold highlighted code snippets I see the > error message "Python version 3.6 does not support this syntax.", once again you've posted in a way that inserts lots of extra crud, you avoided that last time. The syntax change is simple (and works on most older Pythons too): except ErrorType, e: becomes except ErrorType as e: > > Could you please how help me how the below highlighted lines of code can be > can be ported to python3.6 version? > > *except BluetoothctlError, e:* > > *print(e)* > *return None* > ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Writing the right code rite
Steve, I appreciated your letter and it helped point me in the direction this group may be designed for. For some it is sort of like forms of therapy where the goal is to help them reach an insight rather than toss a diagnosis at them and maybe write a prescription. The ultimate goal is to learn how to use resources by yourself. I am so used to doing my own work and getting a real understanding, that it is not easy to adjust to how some others are like the Help Vampires in the article you quoted. Having read it, I do recognize how some people I know may fit into that category and I have often after a while automatically set up not enabling them in some of the ways you describe. Amusingly enough, I have lived in Transylvania (border area where Romania and Hungary meet) and never met any (nonexistent) Vampires. But they seem to be everywhere in books and on TV so why not HELP Vampires. Avi -Original Message- From: Tutor On Behalf Of Steven D'Aprano Sent: Tuesday, November 27, 2018 5:40 AM To: tutor@python.org Subject: Re: [Tutor] Writing the right code rite On Mon, Nov 26, 2018 at 07:18:46PM -0500, Avi Gross wrote: > What kind of answers have people provided? The archives of this mailing list go back to 1994. If you spend some time browsing randomly at the answers people provide, you should get a feel for what sort of answers we tend to give. https://mail.python.org/pipermail/tutor/ > I know it slows things down, especially with a moderator, but often > the best answer is to ask some questions before trying to supply an answer. Indeed. Learning how to ask good questions is part of the learning process, and when people ask poor questions, asking questions in return will either: - teach them by example what sort of information they need to solve their problem; or - discourage the lazy help-vampires from draining the energy out of this group. http://www.skidmore.edu/~pdwyer/e/eoc/help_vampire.htm > Perhaps a > rapid email exchange directly with a student, perhaps moving on to > instant messaging or phone or video forms of communication would work > better for those interested. Of course you are an adult in a free country and you have the right to do whatever you like, but I don't recommend this. In fact I would consider it anti-social and hostile to the rest of the community. I think I speak for most of us when I say we're looking to help and educate the entire community. We're not the personal servants of individual posters, or private teachers. We post so that *everyone* can learn from the answers, not just the person asking the question, and the *process* of reaching the answer is just as important as the final code. Taking that process off-list is, in my opinion, not helping the community. (Here, I'm not speaking for others.) Its also likely to get annoying fast, for both parties: you, when the poster starts bombarding you with question after question, and the poster themselves, when you are too slow to respond. At least if they email the list, there is the opportunity for others to reply in your stead. Of course there are circumstances where it is appropriate to take discussion off-list: - you're being paid to help; - the discussion wanders off-topic; - or it becomes irrelevant and of no interest to the rest of the community (perhaps because it is too specialised to interest anyone but yourself and the original poster); - or moves into confidential/private areas of discussions that shouldn't be posted to the list (were you asked to sign an NDA?); etc. Some subjective judgement may be required. > When done, you might post a summary if appropriate for others > interested but note showing a full solution can be unfair if other > students working on the same problem just latch on to that. The community standard here is that we don't do homework for others. We'll answer concrete questions about Python the language itself, of course: "how do I use the zip function?". We'll help them debug their code, if they've written some code. If they haven't written even a single line of code, we generally don't do much more than say "Show us what you've tried." We'll help guide people towards solutions, but not hand them the solution on a platter. That's for students in school, of course. We're a bit more flexible when it comes to self-learners or even professional programmers asking for help. And we usually take it on trust if they say "this isn't homework". But even then, we're not the personal slave of the poster, and we have no obligation to solve their problem for them. We're not obliged to hand over a complete solution, and in fact doing so goes against our stated aim to *teach* people. (How will they learn effectively if we do their work for them?) Again, some subjective judgement is required. I wouldn't hesitate to answer minor or trivial questions in full, e.g. "how do I count the number of digits in a string?". If it were homework, I might answer a slightly
[Tutor] Error Python version 3.6 does not support this syntax.
Dear Python Experts, As still I am newbie and learning python, I am trying to reuse the Bluetoothctl wrapper in Python from the link ( https://gist.github.com/egorf/66d88056a9d703928f93) I am using python3.6 version, In pycharm editor on the bold highlighted code snippets I see the error message "Python version 3.6 does not support this syntax.", Could you please how help me how the below highlighted lines of code can be can be ported to python3.6 version? *except BluetoothctlError, e:* *print(e)* *return None* Full Code snippet: == import time import pexpect import subprocess import sys class BluetoothctlError(Exception): """This exception is raised, when bluetoothctl fails to start.""" pass class Bluetoothctl: """A wrapper for bluetoothctl utility.""" def __init__(self): out = subprocess.check_output("rfkill unblock bluetooth", shell = True) self.child = pexpect.spawn("bluetoothctl", echo = False) def get_output(self, command, pause = 0): """Run a command in bluetoothctl prompt, return output as a list of lines.""" self.child.send(command + "\n") time.sleep(pause) start_failed = self.child.expect(["bluetooth", pexpect.EOF]) if start_failed: raise BluetoothctlError("Bluetoothctl failed after running " + command) return self.child.before.split("\r\n") def start_scan(self): """Start bluetooth scanning process.""" try: out = self.get_output("scan on") *except BluetoothctlError, e:print(e)return None* def make_discoverable(self): """Make device discoverable.""" try: out = self.get_output("discoverable on") * except BluetoothctlError, e:print(e)return None* def parse_device_info(self, info_string): """Parse a string corresponding to a device.""" device = {} block_list = ["[\x1b[0;", "removed"] string_valid = not any(keyword in info_string for keyword in block_list) if string_valid: try: device_position = info_string.index("Device") except ValueError: pass else: if device_position > -1: attribute_list = info_string[device_position:].split(" ", 2) device = { "mac_address": attribute_list[1], "name": attribute_list[2] } return device def get_available_devices(self): """Return a list of tuples of paired and discoverable devices.""" try: out = self.get_output("devices") *except BluetoothctlError, e:print(e)return None* else: available_devices = [] for line in out: device = self.parse_device_info(line) if device: available_devices.append(device) return available_devices def get_paired_devices(self): """Return a list of tuples of paired devices.""" try: out = self.get_output("paired-devices") *except BluetoothctlError, e:print(e)return None* else: paired_devices = [] for line in out: device = self.parse_device_info(line) if device: paired_devices.append(device) return paired_devices def get_discoverable_devices(self): """Filter paired devices out of available.""" available = self.get_available_devices() paired = self.get_paired_devices() return [d for d in available if d not in paired] def get_device_info(self, mac_address): """Get device info by mac address.""" try: out = self.get_output("info " + mac_address) *except BluetoothctlError, e:print(e)return None* else: return out def pair(self, mac_address): """Try to pair with a device by mac address.""" try: out = self.get_output("pair " + mac_address, 4) *except BluetoothctlError, e:print(e)return None* else: res = self.child.expect(["Failed to pair", "Pairing successful", pexpect.EOF]) success = True if res == 1 else False return success def remove(self, mac_address): """Remove paired device by mac address, return success of the operation.""" try: out = self.get_output("remove " + mac_address, 3) *except BluetoothctlError, e:print(e)return None* else: res = self.child.expect(["not available", "Device has been removed", pexpect.EOF]) success = True if res == 1 else False return
Re: [Tutor] Writing the right code rite
On Tue, Nov 27, 2018 at 10:22:24AM +, Alan Gauld via Tutor wrote: > there are no stupid questions. "Was it you or your brother who died in the war?" More seriously: https://www.themuse.com/advice/how-to-ask-stupid-questions-without-sounding-stupid although I disagree with the last bit of advice. I think it is fine to acknowledge that you recognise when you are asking a "stupid" (basic) question. -- Steve ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Issue in using "subprocess.Popen" for parsing the command output
Dear All, I have fixed the issue with below code snippet for parsing the command output without try and exception, pls let me know if any improvements are needed, might be useful for others def to_bytes(self, str): # Encode to UTF-8 to get binary data. if isinstance(str, bytes): return str return str.encode('utf-8') def to_string(self, bytes): if isinstance(bytes, str): return bytes return self.to_bytes(bytes) def convert_string(self, bytes): try: return self.to_string(bytes.decode('utf-8')) except AttributeError: # 'str' object has no attribute 'decode'. return str(bytes) except UnicodeError: return str(bytes) def sample(self, ssid, pw): cmd = "nmcli device wifi connect '%s' password '%s'" % (ssid, pw) p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True) out, err = p.communicate() out = self.convert_string(out) err = self.convert_string(err) print("The value of data", out.split(" ")) print("printing stdout!!", out) print("printing err!!", err) print("printing retcode!!", p.returncode) if p.returncode != 0: raise subprocess.CalledProcessError(cmd=cmd, returncode=p.returncode, output="{}\n{}".format(out, err)) return out if __name__ == "__main__": m = bt() print(m.sample("NIassddWiFi", "T.f.o.s.1996!abcdfg")) On Sun, Nov 25, 2018 at 11:05 PM Steven D'Aprano wrote: > > I think you are sending email using Gmail. If so, there is a command in > Gmail to send only PLAIN TEXT with no added formatting. Please use it. > Your code at the moment has extra asterisks * added at the beginning and > end of each line. > > More comments below. > > > On Sun, Nov 25, 2018 at 10:43:10PM +0530, srinivasan wrote: > > > 1. Am trying to improve the below code with "try" and "exception", could > > you please help me how "try" and "exception" can be used on the below code > > snippet. I hope in my code with try and exception, seems to be a bug. > > As a beginner, you should normally not use try...except to report > errors. You should learn how to diagnose errors by reading the > traceback. Covering up the traceback with try...except makes debugging > harder. > > Your use here: > > > > *try:* > > *cmd = "nmcli device wifi connect '%s' password '%s'" % (ssid, pw)* > > *proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, > > stderr=subprocess.PIPE, shell=True, universal_newlines=True)* > > *stdout, stderr = proc.communicate()* > > *retcode = proc.returncode* > > *print("printing stdout!!", stdout)* > > *print("printing retcode!!", retcode)* > > *except subprocess.CalledProcessError as e:* > > *s = """While executing '{}' something went wrong.* > > *Return code == '{}'* > > *Return output:\n'{}'* > > *""".format(cmd, e.returncode, e.output, > > shell=enable_shell)* > > *raise AssertionError(s)* > > doesn't seem right to me. The string.format() method doesn't take a > shell=enable_shell agument, so I expect that line > > s = """...""".format(cmd, ..., shell=enable_shell) > > to fail. But even if it doesn't fail, the next line: > > raise AssertionError(s) > > is an abuse of exceptions. The failure here is *not* an assertion, and > you shouldn't use AssertionError. You wouldn't use TypeError or > UnicodeEncodeError or AttributeError. "AssertionError" should not be > used for "some arbitrary error". > > There are almost no reasons to manually raise AssertionError, except > perhaps in test frameworks like unittest. Normally you should only get > an AssertionError from the "assert" command: > > https://import-that.dreamwidth.org/676.html > > My opinion is, you should remove that try...except altogether. I don't > think that it helps your code, even if it worked. Calls to Popen can > fail in many, many ways, and it seems pointless to single out just one > of them and to replace the useful traceback and error message with a > less accurate one. > > > > *Command:* > > :~$ nmcli device wifi connect 'Apartment 18' password > > '40672958689850014685abcdf' > > Error: Connection activation failed: (7) Secrets were required, but not > > provided. > > If you cannot get nmcli working directly from the command line, you have > *no hope* of getting it working with Python getting in the way. > > *First* you must be able to run the command directly from the shell, > with no errors. Then you can move the *working* command to Python and > Popen. > > > return proc.strip().decode("utf-8") > > AttributeError: 'Popen' object has no
Re: [Tutor] Writing the right code rite
On Mon, Nov 26, 2018 at 07:18:46PM -0500, Avi Gross wrote: > What kind of answers have people provided? The archives of this mailing list go back to 1994. If you spend some time browsing randomly at the answers people provide, you should get a feel for what sort of answers we tend to give. https://mail.python.org/pipermail/tutor/ > I know it slows things down, especially with a moderator, but often the best > answer is to ask some questions before trying to supply an answer. Indeed. Learning how to ask good questions is part of the learning process, and when people ask poor questions, asking questions in return will either: - teach them by example what sort of information they need to solve their problem; or - discourage the lazy help-vampires from draining the energy out of this group. http://www.skidmore.edu/~pdwyer/e/eoc/help_vampire.htm > Perhaps a > rapid email exchange directly with a student, perhaps moving on to instant > messaging or phone or video forms of communication would work better for > those interested. Of course you are an adult in a free country and you have the right to do whatever you like, but I don't recommend this. In fact I would consider it anti-social and hostile to the rest of the community. I think I speak for most of us when I say we're looking to help and educate the entire community. We're not the personal servants of individual posters, or private teachers. We post so that *everyone* can learn from the answers, not just the person asking the question, and the *process* of reaching the answer is just as important as the final code. Taking that process off-list is, in my opinion, not helping the community. (Here, I'm not speaking for others.) Its also likely to get annoying fast, for both parties: you, when the poster starts bombarding you with question after question, and the poster themselves, when you are too slow to respond. At least if they email the list, there is the opportunity for others to reply in your stead. Of course there are circumstances where it is appropriate to take discussion off-list: - you're being paid to help; - the discussion wanders off-topic; - or it becomes irrelevant and of no interest to the rest of the community (perhaps because it is too specialised to interest anyone but yourself and the original poster); - or moves into confidential/private areas of discussions that shouldn't be posted to the list (were you asked to sign an NDA?); etc. Some subjective judgement may be required. > When done, you might post a summary if appropriate for > others interested but note showing a full solution can be unfair if other > students working on the same problem just latch on to that. The community standard here is that we don't do homework for others. We'll answer concrete questions about Python the language itself, of course: "how do I use the zip function?". We'll help them debug their code, if they've written some code. If they haven't written even a single line of code, we generally don't do much more than say "Show us what you've tried." We'll help guide people towards solutions, but not hand them the solution on a platter. That's for students in school, of course. We're a bit more flexible when it comes to self-learners or even professional programmers asking for help. And we usually take it on trust if they say "this isn't homework". But even then, we're not the personal slave of the poster, and we have no obligation to solve their problem for them. We're not obliged to hand over a complete solution, and in fact doing so goes against our stated aim to *teach* people. (How will they learn effectively if we do their work for them?) Again, some subjective judgement is required. I wouldn't hesitate to answer minor or trivial questions in full, e.g. "how do I count the number of digits in a string?". If it were homework, I might answer a slightly different question instead: number_of_vowels = sum(thestring.count(vowel) for vowel in "aeiouAEIOU") and let them generalise to digits. But more substantial questions, I probably wouldn't unless the problem really tickled my fancy and I had plenty of time to work on a solution. (Time. I remember when I had time.) -- Steve ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Writing the right code rite
On 27/11/2018 00:18, Avi Gross wrote: > But in watching, I conclude that a subset of the requests come from people > who are some form of early students and only aware of selected aspects of > the language. One of the challenges of this list is identifying the level of the requester. We get several general categories: 1) Professional programmers just starting with Python. Often with a specific project and need a rapid run up the learning curve. They know all about code and tools they just need to know how Python does it. 2a) Academic beginners - those learning Python on a course. These often are not very interested in learning about the theoretical side of things, or whether there is another way to tackle the problem, they simply want to get their homework done. Knowledge level ranges from junior school to under-grad CS courses. 2b) Advanced students (eg. PhD etc) who may or may not have previous programming experience but typically need help using Python for a specific aim. These are often like a cross between 1 and 2a. They know all about their domain but possibly have little CS knowledge/experience. They often assume that NumPy/SciPy are part of the standard library and that most Python users will know them. 3) Hobbyist programmers - those who learn for fun, maybe just out of curiosity or to extend some other skill set - such as working on the Raspberry Pi or with a package like Blender. These can range from youngsters(pre teen) to seniors(70+). They usually have zero CS knowledge and are varied in their enthusiasm for learning the background principles. We need to identify the skill and knowledge level and learning goals of each individual and take that into account in our responses. Figuring that out is often harder than answering the immediate question! We just need to remember that they all have the same right to be here and there are no stupid questions. (Although they may need some help to ask the right question!) -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] Writing the right code rite
I am here to learn but also to help out when I already know something that is asked. What has been of some concern to me is how to reply when the asked has not shared with us lots of info. If I see them using "print" without parentheses, I can assume they are not using 3.x and perhaps emulate their usage. Showing them samples of code that won't work in their environment is a bit of a waste of time, theirs and mine. But in watching, I conclude that a subset of the requests come from people who are some form of early students and only aware of selected aspects of the language. For some of them uses of words and phrases is a tad loose so when they say "list" they might mean something that can range from what others might call tuples or lists or dictionaries or sets or reaching a bit beyond to other words like vectors, arrays, matrices, bags, collections, name spaces and so on. What many want is for someone to help them write some kind of simple loop. Ideally, they would state the problem clearly enough and try to write code and ask help when it does not seem to work. If they answer a few questions to clarify, they can often get a simple answer they can use or understand. But it might help to steer them otherwise. We have had recent requests for example for what sounded like a need to read text into words and then keep adding them to a 'list" if not already there. What kind of answers have people provided? What many of the answers would have in common is to break the lines up into tokens we consider words. But even that can be a complex task that can be done many ways depending on what the file might contain and whether words can include an apostrophe or hypen. Some solutions might tokenize a line at a time and some do the entire file at once using some regular expression that matches anything after one or more non-word characters till the next series of one or more non-word characters. Others might just split a line on a single space which likely won't work on normal English text containing punctuation and so on. Similarly, some may suggest tossing all the tokens into a set to get unique results. Others may suggest using a dictionary and couniting how many times each word appears (even if that was not required.) Others may use lists and introduce use of whys to check if something is already in the list or extend the list. Some may suggest using a data structure like a dequeue for reasons I am not able to explain. Others may want to use a list and carefully explain how to search in an item is already in a list and how to extend the list. Some may even want them to keep the list in alphabetical order. Some may want to dump all words in list 1 then iterate on it by adding only words not already in list2 to list2. Some may want to use a binary tree that finds thing in O(log(N) or something. And yes, some would like you to make a long list then sort it and apply a function such as an iterator that returns the next item after finding all consecutive items that are the same. There are an amazing number of fairly reasonable ways to solve problems, with the usual tradeoffs. But if someone is new to this, what answer meets their immediate needs? For most school projects, unless they are told to use some module, the expectation is for something fairly simple without worrying that the small dataset used will run very long or use much memory. And, the solution probably should not be deeply nested in ways hard to read. I recently wrote a function for someone (not on this group) with about a dozen lines of code that did things step by step using variables with somewhat meaningful names. In English, the goal was to take in a DataFrame and only keep those rows where some subset of the columns all had valid data. The long version was easy to understand. It did things like make a narrow copy of the data using just that subset of the columns. Then it applied a function that returned a vector of True/False if the narrow rows were all OK or had anything missing. Then that vector was used to index the original table to select only rows where it was true. But all that could be collapsed into a single line with a single but somewhat nested statement as each step sort of feeds into being an index of another step. But I would not want that kind of code around without paragraphs of comments and in this case, what difference does it make if temporary variables had a name before being garbage collected when the function returns? Since I find I am more interested in examining different ways to solve a problem with some thought on what is better or just easier or more elegant and so on, I am not always a best fit for instructing new students unless they are sitting in a class I am teaching and mostly at the same level. This is an open forum where we often have no clue what the student already knows or has tried and we do not encourage them to post more than a minimal example. But we can