[Tutor] Turtle
Hello tutors, I have been learning basic python on my Macintosh computer and everything I have tried so far has worked, except when I tried to use the turtle module. I then used my Linux computer and the turtle module still did not work. I tried to use the command line and type "sudo dnf install turtle", "sudo pip install turtle", and it told me "no package turtle available". I tried to install Python-tk and python3-tk, and I was told that no packages by those names were available. I also tried reinstalling python 2 and python 3, to no avail. I am running Python 2.7.1 using Mac OS X 10.6.8 on an iMac, Python 3.5.1 using Mac OS X 10.10.5, and the default python2 and Python3 that comes with fedora 24. On my Mac running Python 3, I have tried about 6 times to enter the command import turtle, and nothing has happened. However, on my most recent attempt, I changed nothing about the program and hit run, and for some reason it worked. All of the terms were still underlined in my pycharm window, and it told me that the commands were not found, and implied that they should not be working. However, after exiting pycharm, and reopening it, it worked again, even though it told me the commands were not valid. My question about running Python 3 on my Mac running 10.10.5: What do I need to do to make it so my computer recognizes that they are valid commands? My questions about running python 2.7 on my Mac running 10.6.8 and my computer running Python 2 and 3 on fedora 24: What do I have to do to get the turtle module? And once I have it, how do I use it? Thank you, Hershel ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] help with comparing list of tuples in python 2
On Fri, Jun 17, 2016, 6:12 PM Lulu J wrote: > Hi there, > > My apologies if this is a trivial question but I am sort of new to python. > Here is my problem: > I have a list of dictionaries. Each dictionary has a word and its position > in the text the positions are in the form of a tuple. > Here is an example: > [ > {'position': (5, 4), 'term': u'happy',}, > {'position': (5, 5), 'term': u'something'} > ] > > for the potions, the first element is the paragraph number and the second > is the word number in that paragraph(sequence from 1...n) > > What I would like to is find which words are next to each other. Meaning, > they will be in the same paragraph and the difference of their word numbers > is 1. > Put the words in a dictionary, key is the location, value is the word. Sort the location-word pairs by location. Loop over the result pairwise. > ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] help with comparing list of tuples in python 2
Lulu J wrote: > Hi there, > > My apologies if this is a trivial question but I am sort of new to python. > Here is my problem: > I have a list of dictionaries. Each dictionary has a word and its position > in the text the positions are in the form of a tuple. > Here is an example: > [ > {'position': (5, 4), 'term': u'happy',}, > {'position': (5, 5), 'term': u'something'} > ] How did you get your data? Perhaps it is possible to store it in a different data structure in the first place, one that is a better fit for your problem. > for the potions, the first element is the paragraph number and the second > is the word number in that paragraph(sequence from 1...n) > > What I would like to is find which words are next to each other. Meaning, > they will be in the same paragraph and the difference of their word > numbers is 1. What is the actual question your script has to answer? Is it (1) What word precedes/follows the third word in the sixth paragraph? or (2) What words precede/follow the word u"happy"? or something else I didn't think of? For (2) here is a not-so-short self-contained example: $ cat neighbors.py import pprint import sys try: raw_input except NameError: raw_input = input # Python 3 SAMPLE = u"""\ The sky is blue Press the blue button This is pie in the sky """ def gen_terms(paragraphs): """Generate {"position": (para_index, word_index), "term": word} dicts. A minimalistic emulation of what your code does. """ for para_index, para in enumerate(paragraphs): for word_index, word in enumerate(para.lower().split()): yield {"position": (para_index, word_index), "term": word} def find_neighbors(word, position_to_word, word_to_position): before = set() # use collections.Counter() if you are after = set() # interested in frequencies for para_index, word_index in word_to_position[word]: try: left_word = position_to_word[para_index, word_index-1] except KeyError: pass # first word in paragraph else: before.add(left_word) try: right_word = position_to_word[para_index, word_index+1] except KeyError: pass # last word in paragraph else: after.add(right_word) return before, after def format_words(words): return ", ".join(sorted(words)) or "" def build_lookup_tables(terms): # map word to all positions in the text word_to_position = {} # map position to the corresponding word position_to_word = {} for term in terms: pos = term["position"] word = term["term"] word_to_position.setdefault(word, []).append(pos) position_to_word[pos] = word return word_to_position, position_to_word def normalize(word): try: word = word.decode() except AttributeError: pass # Python 3 return word.lower() def main(): verbose = "--verbose" in sys.argv if verbose: print("Original text:") print(SAMPLE) terms = list(gen_terms(SAMPLE.lower().splitlines())) if verbose: print("list of terms:") pprint.pprint(terms) print("") word_to_position, position_to_word = build_lookup_tables(terms) if verbose: print("word --> position") pprint.pprint(dict(word_to_position)) print("position --> word") pprint.pprint(position_to_word) print("") while True: word = normalize(raw_input("enter a word: ")) if not word: print("Bye!") break elif word not in word_to_position: print("Unknown word, enter one of these:") print(format_words(word_to_position)) print("") else: before, after = find_neighbors( word, position_to_word=position_to_word, word_to_position=word_to_position ) print(u"These words occur before '{}'".format(word)) print(format_words(before)) print(u"These words occur after '{}'".format(word)) print(format_words(after)) print("") if __name__ == "__main__": main() Let's run it in verbose mode so that you can see the data structures used: $ python neighbors.py --verbose Original text: The sky is blue Press the blue button This is pie in the sky list of terms: [{'position': (0, 0), 'term': u'the'}, {'position': (0, 1), 'term': u'sky'}, {'position': (0, 2), 'term': u'is'}, {'position': (0, 3), 'term': u'blue'}, {'position': (1, 0), 'term': u'press'}, {'position': (1, 1), 'term': u'the'}, {'position': (1, 2), 'term': u'blue'}, {'position': (1, 3), 'term': u'button'}, {'position': (2, 0), 'term': u'this'}, {'position': (2, 1), 'term': u'is'}, {'position': (2, 2), 'term': u'pie'}, {'position': (2, 3), 'term': u'in'}, {'position': (2, 4), 'term': u'the'}, {'position': (2, 5), 'term': u'sky'}] word --> posit
Re: [Tutor] Turtle
On Fri, Jun 17, 2016 at 11:25:40PM -0700, Hershel Millman wrote: > Hello tutors, > > I have been learning basic python on my Macintosh computer and > everything I have tried so far has worked, except when I tried to use > the turtle module. I then used my Linux computer and the turtle module > still did not work. What does "did not work" mean? Did you get an error message? Blue Screen Of Death? Computer caught fire? I see later on that you are running PyCharm. Let's try this with the default Python interpreter. Open a terminal window. You should see a prompt ending with a dollar sign $ e.g. on my computer I see: [steve@ando ~]$ Type the command "python" without quotes, and hit Enter. You should get a message about the version of Python you are running, and a >>> prompt. This is the Python interpreter. Now enter: import turtle What happens? Do you get an error? If not, what happens if you enter these lines? turtle.shape('turtle') for i in range(4): turtle.right(90) turtle.forward(200) (Hit the TAB key at the beginning of the last two lines to get the indent. When you have finished typing, you will need to enter one extra time to have Python run the code.) Describe what happens. Do you get an error? If you do, copy and paste the ENTIRE error message, starting with the line "Traceback". > I tried to use the command line and type "sudo dnf > install turtle", "sudo pip install turtle", and it told me "no package > turtle available". That's because turtle is part of the standard library. It's already installed. If you run: locate turtle.py from your Linux or Mac OS X shell (not from Python!) you should see a list of at least one turtle.py files. > I tried to install Python-tk and python3-tk, and I > was told that no packages by those names were available. I also tried > reinstalling python 2 and python 3, to no avail. Reinstalling Python should be the *last* resort, not the first, or second. -- Steve ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] Why are expressions not allowed as parameters in function definition statements?
I have (Finally!) gotten a bit of time to look at Peter's answer to my Model-View-Controller question from May 29th, particularly his CircleImageView class to which he added a "#FIXME" comment. I thought it would be helpful to abbreviate his distance function in the interpreter while I played around with pencil and graph paper. I got: Python 3.5.1 (v3.5.1:37a07cee5969, Dec 6 2015, 01:54:25) [MSC v.1900 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license" for more information. py3: def d(row, col/2, radius=5): File "", line 1 def d(row, col/2, radius=5): ^ SyntaxError: invalid syntax And this surprised me. It seems that only identifiers are allowed as parameters in a function definition statement, and I cannot help but wonder why? It seems that in most other places in Python's syntax it will allow one to insert almost any kind of object or expression. TIA! -- boB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Why are expressions not allowed as parameters in function definition statements?
On Sat, Jun 18, 2016 at 3:04 PM, boB Stepp wrote: > I have (Finally!) gotten a bit of time to look at Peter's answer to my > Model-View-Controller question from May 29th, particularly his > CircleImageView class to which he added a "#FIXME" comment. I thought > it would be helpful to abbreviate his distance function in the > interpreter while I played around with pencil and graph paper. I got: > > Python 3.5.1 (v3.5.1:37a07cee5969, Dec 6 2015, 01:54:25) [MSC v.1900 > 64 bit (AMD64)] on win32 > Type "help", "copyright", "credits" or "license" for more information. > py3: def d(row, col/2, radius=5): > File "", line 1 > def d(row, col/2, radius=5): > ^ > SyntaxError: invalid syntax > > And this surprised me. It seems that only identifiers are allowed as > parameters in a function definition statement, and I cannot help but > wonder why? It seems that in most other places in Python's syntax it > will allow one to insert almost any kind of object or expression. > > TIA! > > -- > boB I'll take a stab. The function is defined once. The parameters name the arguments to be passed when the function is invoked. They can have defaults, but you are asking it to perform a calculation, which would only be done when the function is defined. > ___ > Tutor maillist - Tutor@python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor -- Joel Goldstick http://joelgoldstick.com/blog http://cc-baseballstats.info/stats/birthdays ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Why are expressions not allowed as parameters in function definition statements?
On Sat, Jun 18, 2016 at 3:14 PM, Joel Goldstick wrote: > On Sat, Jun 18, 2016 at 3:04 PM, boB Stepp wrote: >> Python 3.5.1 (v3.5.1:37a07cee5969, Dec 6 2015, 01:54:25) [MSC v.1900 >> 64 bit (AMD64)] on win32 >> Type "help", "copyright", "credits" or "license" for more information. >> py3: def d(row, col/2, radius=5): >> File "", line 1 >> def d(row, col/2, radius=5): >> ^ >> SyntaxError: invalid syntax >> >> And this surprised me. It seems that only identifiers are allowed as >> parameters in a function definition statement, and I cannot help but >> wonder why? It seems that in most other places in Python's syntax it >> will allow one to insert almost any kind of object or expression. > I'll take a stab. The function is defined once. The parameters name > the arguments to be passed when the function is invoked. They can > have defaults, but you are asking it to perform a calculation, which > would only be done when the function is defined. In retrospect, I probably should have figured this out. I know that defaults to parameters are assigned at function definition time and that arguments only get passed at function call time. If I use an expression, at function definition time there is no value to assign. So as long as Python uses this mechanism for handling function definition, I now don't see how expressions can be usable as parameters. Thanks Joel! boB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Why are expressions not allowed as parameters in function definition statements?
On 18/06/16 20:04, boB Stepp wrote: > py3: def d(row, col/2, radius=5): > File "", line 1 > def d(row, col/2, radius=5): > ^ > SyntaxError: invalid syntax > > And this surprised me. It seems that only identifiers are allowed as > parameters in a function definition statement, and I cannot help but > wonder why? What are the parameters (as opposed to the arguments)? They are names. They are keys in the local dictionary used by the function to look up the values passed in as arguments. You cannot use an expression as a key in a dictionary. If you try, Python tries to evaluate the expression and uses the result if its valid or throws a nameerror etc. hth -- 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
Re: [Tutor] Why are expressions not allowed as parameters in function definition statements?
On Sat, Jun 18, 2016 at 02:04:46PM -0500, boB Stepp wrote: > I have (Finally!) gotten a bit of time to look at Peter's answer to my > Model-View-Controller question from May 29th, particularly his > CircleImageView class to which he added a "#FIXME" comment. I thought > it would be helpful to abbreviate his distance function in the > interpreter while I played around with pencil and graph paper. I got: > > Python 3.5.1 (v3.5.1:37a07cee5969, Dec 6 2015, 01:54:25) [MSC v.1900 > 64 bit (AMD64)] on win32 > Type "help", "copyright", "credits" or "license" for more information. > py3: def d(row, col/2, radius=5): > File "", line 1 > def d(row, col/2, radius=5): > ^ > SyntaxError: invalid syntax > > And this surprised me. I'm surprised that you're surprised. I don't even know what you expect a parameter col/2 would even mean. > It seems that only identifiers are allowed as > parameters in a function definition statement, and I cannot help but > wonder why? Because they are parameters, which by definition are variable names, i.e. identifiers. What else could they be? def foo(x, 1+2, y): # how do I refer to the second parameter here? foo(1000, 2000, 3000) # what happens to the second argument here? Can you explain what you expected def d(row, col/2) to mean? I have literally no idea. > It seems that in most other places in Python's syntax it > will allow one to insert almost any kind of object or expression. You can't use arbitrary expressions on the left hand side of assignment: 1 + 2 = "some value" x/2 = y Function parameters are a form of assignment. -- Steve ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Why are expressions not allowed as parameters in function definition statements?
On Sat, Jun 18, 2016 at 9:10 PM, Steven D'Aprano wrote: > On Sat, Jun 18, 2016 at 02:04:46PM -0500, boB Stepp wrote: > Can you explain what you expected > > def d(row, col/2) > > to mean? I have literally no idea. You know Steve, as I was typing the beginning of a reply responding to a similar question you asked earlier in your response, I suddenly realized how ridiculous having a parameter of 'col/2' is! I'll just have either eat crow or attribute this to a brain fart. You pick! Cheers! -- boB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Why are expressions not allowed as parameters in function definition statements?
> You know Steve, as I was typing the beginning of a reply responding to > a similar question you asked earlier in your response, I suddenly > realized how ridiculous having a parameter of 'col/2' is! I'll just > have either eat crow or attribute this to a brain fart. You pick! Just to play devil's advocate: it's not crazy. Essentially, what you're asking for is called "pattern matching", and it is done in a class of many programming languages. One of the more well known of these is Prolog. https://en.wikipedia.org/wiki/Prolog. Other forms of pattern matching show up in ML, and it *is* used in industry. (e.g. Microsoft's F#.) It's a bit out of scope to talk about this much here, but I just wanted to chime in here to say that you are not ridiculous. :P But Python does not have a robust pattern matching facility; the closest it has is a limited form of tuple matching: ## > def f((x,y), z): ... print x, y, z ... > f([1, 2], 3) 1 2 3 ## with very limited applicability and rarely used. I hope everyone is well! ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Correct use of model-view-controller design pattern
On Sun, May 29, 2016 at 9:28 AM, Peter Otten <__pete...@web.de> wrote: > Here's a commandline example with two views (the circle-drawing routine has > to be fixed)... I have to admit that now that I have finally gotten around to your code, I am left scratching my head. My main issue is what am I aiming at for a final CLI display of a circle? This is not such a simple thing! First, what are the units for a circle's radius in a CLI? If it is 1 radius unit = 1 character, then your code is displaying too many characters. To me it seems more natural to use 1 character as the basic unit of measurement. But if that is done, then the output looks more like a non-circular ellipse with the longer axis being vertical. On my Windows PowerShell for the font I am using, each character space is 8 pixels wide and 14 pixels wide. I suspect this is why your code uses range(2*diameter) and column/2, to compensate for the built in stretching in the vertical direction due to how characters are displayed. So my current best version of your code modifies your distance function as well as your CircleImageView class. I am not totally happy with it. I think I am still missing something, but it tries to adhere to 1 measurement unit = 1 character based on my display's font. > def dist(ax, ay, bx, by): > return ((ax-bx)**2 + (ay-by)**2)**.5 I replaced this with: def dist(ax, ay, bx, by): # Each character is 8 pixels wide by 14 pixels high. width_px = 8 height_px = 14 return (((ax-bx)*width_px)**2 + ((ay-by)*height_px)**2)**0.5 I also flipped how you used ax, ay and bx, by as I associate rows with y-coordinates and columns with x-coordinates. > > class CircleImageView(CircleView): > > def changed(self, model): > self.update_radius(model.radius) > > def update_radius(self, radius): > # FIXME > diameter = 2*radius > cx = cy = radius > for row in range(diameter): > for column in range(2*diameter): > if dist(cx, cy, row, column/2) < radius: > print("*", end="") > else: > print(" ", end="") > print() And I replaced this (Renaming some identifiers to make it clearer to me) with: class CircleImageView(CircleView): def changed(self, model): self.update_radius_in_chars(model.radius_in_chars) def update_radius_in_chars(self, radius_in_chars): diameter_in_chars = 2 * radius_in_chars cx = cy = radius_in_chars for row in range(diameter_in_chars + 1): for column in range(diameter_in_chars + 1): if dist(cx, cy, column, row) <= dist(cx, 0, 0, 0): print("O", end="") else: print(" ", end="") print() I did a '+ 1' in the range statements since a character should be displayed in the center of the circle from which the radius is measured. I used '<= dist(cx, 0, 0, 0)'. First, if it is equal to the radius, I feel a character should be displayed. Second, I used 'cx' instead of 'cy' to keep the result from being stretched vertically. Finally, I felt I needed to use some form of absolute distance calculation, so the distance function converts everything to pixels, which is what everything ultimately is displayed in anyway on a monitor. Doing things this way, I feel my displayed character circles look better as the radius increases. Some edited (I just removed blank lines.) sample output (I changed from asterisks to capital ohs): OOO O OOO O OOO Circle radius_in_chars is now 5 Model-View-Controler Demo Enter an integer to set the circle radius or 'grow' to increase the radius or 'shrink' to decrease the radius or 'add' to add another CircleValueView radius or 'grow' or 'shrink' or 'add': 6 O O OOO O OOO O O radius or 'grow' or 'shrink' or 'add': 13 O OOO OOO O OOO O O OOO O O OOO O OOO OOO O I have to say, I did a lot of playing around on graph paper with a pencil and a compass. If I actually draw a circle with a compass and fill in marks for a distance from the circle's center, I get a very unsatisfactory result! I still have more conceptual work to do on your code. I still do not fully get decorators. In your code I get the impression that you are trying to be more formal in how you are writing your classes so as to have getter and setter methods, as well as having more explicit separation between model, view and controller. And I haven't made it to your tkinter version at all! BTW, thank you very much
Re: [Tutor] Why are expressions not allowed as parameters in function definition statements?
One other thing to add: the notion of pattern matching is often used in mathematics. For example, if we want to define a function that does something special to even numbers vs. odd numbers, it's not uncommon to see the following when we want to describe a function `f`: for `n` in the natural numbers: f(2n) = f(2n+1) = where it's notationally convenient to express a function as a collection of multiple cases, where we decide which case to use by pattern matching against the argument to find the appropriate case to use. We can contrast this style versus one which puts the case analysis in the body of the function itself. Again, it's just that we don't have direct support for this kind of thing in Python. On Sat, Jun 18, 2016 at 7:10 PM, Steven D'Aprano wrote: > On Sat, Jun 18, 2016 at 02:04:46PM -0500, boB Stepp wrote: >> I have (Finally!) gotten a bit of time to look at Peter's answer to my >> Model-View-Controller question from May 29th, particularly his >> CircleImageView class to which he added a "#FIXME" comment. I thought >> it would be helpful to abbreviate his distance function in the >> interpreter while I played around with pencil and graph paper. I got: >> >> Python 3.5.1 (v3.5.1:37a07cee5969, Dec 6 2015, 01:54:25) [MSC v.1900 >> 64 bit (AMD64)] on win32 >> Type "help", "copyright", "credits" or "license" for more information. >> py3: def d(row, col/2, radius=5): >> File "", line 1 >> def d(row, col/2, radius=5): >> ^ >> SyntaxError: invalid syntax >> >> And this surprised me. > > I'm surprised that you're surprised. I don't even know what you expect a > parameter col/2 would even mean. > >> It seems that only identifiers are allowed as >> parameters in a function definition statement, and I cannot help but >> wonder why? > > Because they are parameters, which by definition are variable names, > i.e. identifiers. What else could they be? > > > def foo(x, 1+2, y): > # how do I refer to the second parameter here? > > foo(1000, 2000, 3000) # what happens to the second argument here? > > > Can you explain what you expected > > def d(row, col/2) > > to mean? I have literally no idea. > >> It seems that in most other places in Python's syntax it >> will allow one to insert almost any kind of object or expression. > > You can't use arbitrary expressions on the left hand side of > assignment: > > 1 + 2 = "some value" > x/2 = y > > Function parameters are a form of assignment. > > > -- > Steve > ___ > 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] Correct use of model-view-controller design pattern
On Sat, Jun 18, 2016 at 11:18 PM, boB Stepp wrote: > On Sun, May 29, 2016 at 9:28 AM, Peter Otten <__pete...@web.de> wrote: > >> Here's a commandline example with two views (the circle-drawing routine has >> to be fixed)... > > I have to admit that now that I have finally gotten around to your > code, I am left scratching my head. My main issue is what am I aiming > at for a final CLI display of a circle? This is not such a simple > thing! First, what are the units for a circle's radius in a CLI? If > it is 1 radius unit = 1 character, then your code is displaying too > many characters. To me it seems more natural to use 1 character as > the basic unit of measurement. But if that is done, then the output > looks more like a non-circular ellipse with the longer axis being > vertical. On my Windows PowerShell for the font I am using, each > character space is 8 pixels wide and 14 pixels wide... That should be "...and 14 pixels high ...". Guess I'm sleepy! boB ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Why are expressions not allowed as parameters in function definition statements?
On Sun, Jun 19, 2016 at 4:04 AM, Danny Yoo wrote: > >> def f((x,y), z): > ... print x, y, z > ... >> f([1, 2], 3) > 1 2 3 Note that Python 3 doesn't support tuple parameter unpacking. See PEP 3113: https://www.python.org/dev/peps/pep-3113 ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor