Python Forum
Python 25 Line Challenge
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Python 25 Line Challenge
#21
@codingCat
I'm not sure. I just have started experimenting with it. It works for some but not all. One of the more experienced programmers will have to answer that one. I'm somewhat of a beginner.
I welcome all feedback.
The only dumb question, is one that doesn't get asked.
My Github
How to post code using bbtags


Reply
#22
turtles[i].forward(randint(0, 5))
saves a line. I think the index i should be increased before the forward move.
codingcat Wrote:Does python let you separate commands with a comma
If you separate expressions by commas on a line, it creates a tuple, for example
2 ** 2 , 2 ** 3, 2 ** 4
creates the tuple (4, 8, 16) and then deletes it immediately because it is not assigned to any variable.

@menator01 you could even write with the walrus operator
turtles[i := (i + 1) % len(turtles)].forward(randint(0, 5))
ndc85430 likes this post
Reply
#23
@Gribouillis
Thanks again. Code is now 25 lines without spaces and comments. I forgot about the walrus operator.
I welcome all feedback.
The only dumb question, is one that doesn't get asked.
My Github
How to post code using bbtags


Reply
#24
You can write the while loop like this
# Set a variable for accessing turtle objects
i = 0
# Setup a while loop
while turtles[i].xcor() < 200:
    turtles[i := (i + 1) % len(turtles)].forward(randint(0, 5))
turtles[i].home()
turtles[i].write(f'winner: {i+1}', font=('system', 25, 'bold'))
sleep(5)
Reply
#25
(May-09-2022, 07:07 PM)Gribouillis Wrote:
# Set a variable for accessing turtle objects
while turtles[i].xcor() < 200:
    turtles[i := (i + 1) % len(turtles)].forward(randint(0, 5))
As a teacher, seeing this type of code makes me nuts as no student, even one who understand basic python, would have any idea what is going on.

As a programmer, and former developer... I absolutely love it. The fact that you have have an assignment operator that returns a value is insane. Stuff like this is exactly why I describe python as being fun rather than easy.
Reply
#26
Here is my next submission, one of my favorite demos... bouncing balls. from 150 lines, I managed to drop it down to 30 with the help a dictionary rather than multiple lists. I could get the last five, but that would tip it into unreadable.

import tkinter, time, math, random

def onTimer():
    if len(ballstats) < 100:
        ballstats.append({"shape": None, "x":random.randrange(0,winWid),"y":random.randrange(0,winHei), "spdx":(random.random() * 2)-1, "spdy":(random.random() * 2)-1})
        color = "#"
        for i in range(0,6): color = color + random.choice(["0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F"])
        ballstats[len(ballstats)-1]["shape"] = canvas.create_oval(ballstats[len(ballstats)-1]["x"],ballstats[len(ballstats)-1]["y"], ballstats[len(ballstats)-1]["x"]+balldiameter,ballstats[len(ballstats)-1]["y"]+balldiameter, outline=color, fill=color)
    for i in range(0,len(ballstats)):
        ballstats[i]["x"] = ballstats[i]["x"] + ballstats[i]["spdx"]
        ballstats[i]["y"] = ballstats[i]["y"] + ballstats[i]["spdy"]
        for j in range(i+1,len(ballstats)):
            dist = math.sqrt(( (ballstats[i]["x"]+(balldiameter/2)) - (ballstats[j]["x"]+(balldiameter/2)))**2 + ( (ballstats[i]["y"]+(balldiameter/2)) - (ballstats[j]["y"]+(balldiameter/2)))**2) 
            if dist < balldiameter:
                ballstats[i]["spdx"], ballstats[j]["spdx"] = ballstats[j]["spdx"], ballstats[i]["spdx"]
                ballstats[i]["spdy"], ballstats[j]["spdy"] = ballstats[j]["spdy"], ballstats[i]["spdy"]
        if ballstats[i]["x"] < 0 or ballstats[i]["x"] > winWid-balldiameter: ballstats[i]["spdx"] = ballstats[i]["spdx"] * -1
        if ballstats[i]["y"] < 0 or ballstats[i]["y"] > winHei-balldiameter: ballstats[i]["spdy"] = ballstats[i]["spdy"] * -1
        canvas.coords(ballstats[i]["shape"], (ballstats[i]["x"], ballstats[i]["y"], ballstats[i]["x"]+balldiameter, ballstats[i]["y"]+balldiameter))
    timerhandle = window.after(2,onTimer)

winWid = 640
winHei = 480
balldiameter = 7
ballstats = []
window = tkinter.Tk()
canvas = tkinter.Canvas(window, width=winWid, height=winHei, bg="white")
canvas.pack()
timerhandle = window.after(2,onTimer)
window.mainloop()
Gribouillis and menator01 like this post
Reply
#27
I humanized the bouncing balls and made it 25 lines long.
import tkinter, time, math, random, dataclasses
Ball = dataclasses.make_dataclass('Ball', ('shape', 'x', 'y', 'spdx', 'spdy', 'color'))
def onTimer():
    for i, ball in enumerate(ballstats):
        ball.x += ball.spdx
        ball.y += ball.spdy
        for other in ballstats[i+1:]:
            dist = math.sqrt((ball.x - other.x)**2 + (ball.y - other.y)**2) 
            if dist < balldiameter:
                ball.spdx, other.spdx = other.spdx, ball.spdx
                ball.spdy, other.spdy = other.spdy, ball.spdy
        if ball.x < 0 or ball.x > winWid - balldiameter: ball.spdx = - ball.spdx
        if ball.y < 0 or ball.y > winHei - balldiameter: ball.spdy = - ball.spdy
        canvas.coords(ball.shape, (ball.x, ball.y, ball.x + balldiameter, ball.y + balldiameter))
    timerhandle = window.after(2,onTimer)
winWid, winHei = 640, 480
balldiameter = 7
window = tkinter.Tk()
canvas = tkinter.Canvas(window, width=winWid, height=winHei, bg="white")
canvas.pack()
ballstats = [Ball(None, random.randrange(0, winWid), random.randrange(0, winHei), random.random() * 2 - 1, random.random() * 2 - 1, "#" + ''.join(random.choices("0123456789ABCDEF", k=6))) for i in range(100)]
for ball in ballstats:
    ball.shape = canvas.create_oval(ball.x, ball.y, ball.x + balldiameter, ball.y + balldiameter, outline=ball.color, fill=ball.color)
timerhandle = window.after(2,onTimer)
window.mainloop()
Some lines are too long. Normally I don't write lines larger than 80 characters.
menator01 likes this post
Reply
#28
(May-10-2022, 01:43 PM)codingCat Wrote: The fact that you have have an assignment operator that returns a value is insane.
The walrus operator := appeared only in 2018 with PEP 572. For more than 25 years, Guido van Rossum refused to have an expression assignment operator in Python (as there is in C for example). For old pythonistas like me, this operator breaks somewhat the clean syntax of Python because it allows assignments to be buried into complex expression instead of being clearly visible in the statements sequence. We used to accept the lack of this as a sacrifice for a greater cause.
Reply
#29
(May-11-2022, 05:51 AM)Gribouillis Wrote:
(May-10-2022, 01:43 PM)codingCat Wrote: The fact that you have have an assignment operator that returns a value is insane.
The walrus operator := appeared only in 2018 with PEP 572. For more than 25 years, Guido van Rossum refused to have an expression assignment operator in Python (as there is in C for example). For old pythonistas like me, this operator breaks somewhat the clean syntax of Python because it allows assignments to be buried into complex expression instead of being clearly visible in the statements sequence. We used to accept the lack of this as a sacrifice for a greater cause.

I find that fascinating.

A lot of the consequences of the design choices in C is the ability to obfuscate your code. I'm sure the motivation was pure at the time as C was developed at the tail end of the punch card era and most of the techniques can save you some very valuable space on a punch card. What has developed over the years though, is a type of coder who loves using these tools to make the code all but unreadable while patting themselves on the back for saving a few keystrokes. My favorite example is: i += i++ + ++i; Having worked as a teacher, where clean and understandable is primary and also as an assembler coder and saw that the result of such lines actually results in more commands for the computer to crunch through; I have never been a big fan of these design choices.

Then I stumbled across Python. Python seems to be the language where all of the design choices were made to save on typing and to obfuscate the code. It is absolutely fascinating that in a language that seems to embrace ease of coding so highly above readability that one of the lead designers would shy away from something as comparably innocuous as an expression assignment operator.

Crazy.
Reply
#30
(May-09-2022, 06:33 PM)codingCat Wrote:
(May-09-2022, 06:04 PM)menator01 Wrote: If you remove comments and spacing, got it to 31 lines.
hideturtle(), speed('fastest')
penup(), goto(-200, 10*30/2), pendown(), goto(-200, 0-270)
penup(), goto(200, 10*30/2), pendown(), goto(200, 0-270)

There is another technique that is new to me... can you explain the comma separator between the commands? Does python let you separate commands with a comma the way MS BASIC did with the colon, or is there a special case I am missing?

Hello,
These are tuples:
penup(), goto(-200, 10*30/2), pendown(), goto(-200, 0-270) == (penup(), goto(-200, 10*30/2), pendown(), goto(-200, 0-270))
I speak Python but I don't speak English (I just read it a little). If I express myself badly, please blame the translator^^.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Python 100 line Challenge codingCat 9 3,268 Jun-20-2022, 07:18 AM
Last Post: Coricoco_fr
  Zen Python Challenge ichabod801 3 4,116 Aug-13-2018, 12:02 AM
Last Post: ichabod801

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020