Thread Shed Challenge

When we are taught for loops, it is described something like this…

for element in iterable:

It can be any iterable, a string, a list, a tuple, a set, a dict, or an iterator such as map, filter, zip, etc.

We learned that str.split() returns a new list, so as it appears here is also iterable, so,

for x in str.split(separator):

where separator can be any character string, hence we see,

for color in sale.split('&'):

It is not necessary in this case to assign it to any variable since it is a list object, already. Nothing is keeping us from creating an intermediate variable, and then using it, but on refactoring we would eventually revert to the above.

sale_split_on_ampersand = sale.split('&')

for color in sale_split_on_ampersand:

Blockquote
My code for this, is there any way to make it cleaner ?

daily_sales_replaced = daily_sales.replace(";,;",";")
daily_transactions = daily_sales_replaced.split(",")

daily_transactions_split = []

for i in daily_transactions:
  daily_transactions_split.append(i.split(";"))

transactions_clean = []

for i in daily_transactions_split:
  for a in i:
    transactions_clean.append(a.strip())


customers = transactions_clean[0::4]
sales = transactions_clean[1::4]
thread_sold = transactions_clean[2::4]


total_sales = 0
for i in sales:
  value = float(i.strip("$"))
  total_sales += value
thread_sold_a = []
thread_sold_split = []
for i in thread_sold:
  if i.find("&") == True:
    thread_sold_split.append(i)
  else:
    for a in i.split("&"):
      thread_sold_split.append(a)
#print(thread_sold_split)
      
def color_count(color):
  color_count = 0
  for a in thread_sold_split:
    if a == color:
      color_count += 1
  return color_count

#print(color_count("white"))  

colors = ['red','yellow','green','white','black','blue','purple']

for i in colors:
  print(f"Thread Shed sold {color_count(i)} threads of {i} thread today")
    

If you think of your program like a big math expression to be simplified with parts of it cancelling out and removed … then yeah there’s a fair bit you can get rid of in that.

For example, a lot of your loops are iterating through the same thing. An entry from the input. They could all be the same loop.

Splitting on “&” can be done regardless of whether there’s a “&” in it. You have two separate cases for that, they’re the same thing.