Thread Shed Color Counter

Thread Shed - Python Lesson
My Code so Far

Everything above the color_counter function I had operating but I keep getting crazy numbers for the color count. Instead of having it say there are 28 white threads sold I am getting 4 digit numbers.

There are tests built in with comments. This is the code after re-writing it so many time I am not really sure what was innate. I am sure you can see something I can’t.

1 Like

Unindent line 129 so it is out of the inner loop.

Lines 152 to 161

thread_sold_split = []
for thread in thread_sold: 
  if '&' in thread:
    for color in thread:
      thread_sold_split.append(thread.replace('&', ' ').split(' '))
    split = []

This line,


Is not doing anything. What happens if you write the iterator like so,

for thread in thread_sold:
  for color in thread.split('&'):

We can isolate our color names by casting them to a set, then we can iterate over the set to count each color.

colors = set(thread_sold_split)

LInes 170 thru 175

def color_count(color):
  color_total = 0
  for thread_color in thread_sold_split:
    if color == 'white':
      color_total += 1
return color_total

For as many iterations as there are in thread_sold_split, ‘white’ is accumulating but not others are. We have a count method that can help to simplify this…

def color_count(color):
  return thread_sold_split.count(color)

We see no mention of any specific color. Just a count of the color we passed in. Of course we could use a loop, as you have done…

def color_count(color):
  count = 0
  for thread in thread_sold_split:
    if thread == color:
      count += 1
  return count

Now iterating over our set of colors,

for color in colors:
  print ('Color: {} Count: {}'.format(color, color_count(color)))
1 Like

This was the bit that I was hung up on (in addition to the others). I am having a hard time switching between str and lists so this bit got rewritten a many times. I had some written exactly as you suggested the first time too grrr. Off to finish the project now, finally! Thank you!


Finished the last part in less than two minutes, wish I asked for help sooner. Thank you again!