0

Is anyone able to explain this code? My friend wrote it and I don’t understand anything about the line defining “diff”

import math
import turtle
import random

t = turtle.Turtle()
screen = turtle.Screen()
t.shape("turtle")
t.speed(0)
t.tracer(100)

COLOR = [18.0, 0.0, 41.0]
COLOR_2 = [0.0, 172.0, 219.0]
WIDTH = screen.window_width()
HEIGHT = screen.window_height()

diff = [(hue - COLOR[index]) / HEIGHT for index, hue in enumerate(COLOR_2)]

2 Answers2

0

If you wanted to evenly distribute values from COLOR to COLOR_2 over HEIGHT steps, this would compute how much to change each component at each step. For example, if HEIGHT were 2, it would compute [-9.0, 86.0, 89.0].

Scott Hunter
  • 48,888
  • 12
  • 60
  • 101
0

enumerate(COLOR_2) returns an enumerate object where the first variable is the index of the item in the list and the second variable is the actual item. Then the for loop loops through these results, so for the list COLOR_2 the first iteration will give: index = 0 and hue = 0.0, and so on: index = 1, hue = 172.0 etc. So for each iteration it evaluates (hue - COLOR[index]) / HEIGHT which, for the first iteration, is: (0.0 - COLOR[0]) / screen.window_height() Since this generator of sorts is in list brakets [] it is a list comprehension and thus creates a list where each item is the formula: (hue - COLOR[index]) / HEIGHT evaluated at each value pair (explained earlier) from index, hue in enumerate(COLOR_2).

For further understanding the code is equivalent to:

diff = []
for index, hue in enumerate(COLOR_2):
    diff.append((hue - COLOR[index]) / HEIGHT)

Another simplification:

for i, item in enumerate(lst): #this is the same as:

for item in lst: #this

#the only difference is that the second option does not have a 
#variable that loops through the indices (0, 1, 2, 3, 4, etc.)

Therefore, since your code needs COLOR[index] (so that the items in COLOR are linked with the items in COLOR_2) you need to use enumerate so that you also get the index since it is needed.

The output (value of diff) given a HEIGHT of 800 (for example) should be:

[-0.0225, 0.215, 0.2225]

Based on my understanding of the purpose of this code, you could then increment from COLOR to COLOR_2 by diff to create a "gradient" or "Ombre effect".

Eli Harold
  • 2,280
  • 1
  • 3
  • 22