1

So, I asked this question yesterday but I think I can word it a lot better. I have a csv file with 4 columns, 1 of which contains the day that a ticket has been purchased for (Wed, Thur and Fri), and another containing how many tickets each customer has bought. Wed & Thur tickets are a different price from Fri tickets. I need to get the code to loop through the tickets bought column and only take the data from the rows containing 'W' or 'T' in the day of purchase column so I can calculate how much money was made from Wed & Thur sales, and then the same for the Fri sales. I hope I've explained it well. If it helps, here is my code so far:

wedThur = int(5.00)
friday = int(10.00)

def readFile():
    ticketid = []
    ticketsBought = []
    method = []

    f = open("ticketdata.csv")
    csvFile = csv.reader(f)
    for row in csvFile:
        ticketid.append(row[1])
        ticketsBought.append(int(row[2]))
        method.append(row[3])
    f.close()

    return ticketid, ticketsBought, method

def calculatePurchases(ticketid, ticketsBought):
    price = 0
    amount = len(ticketid)
    if 'W' or 'T' in ticketid:
        price = wedThur * amount
        print(price)
    else:
        price = friday * amount
        print(price)

    return price

1 Answer 1

1

Python has many amazing features to work with such data. First of all, I would change your read file function to return more suitable data structure. Instead of returning tuple of lists, I would return list of tuple.

def read_file():
    data = []

    f = open("ticketdata.csv")
    csvFile = csv.reader(f)
    for row in csvFile:
        data.append(row)
    f.close()

    return data

Python has built-in function sum, which sums all elements in a sequence. sum([1, 2, 3]) returns 6. All is needed to compose right sequence for it.

def iterate_by_day(days, data):
    for d in data:
        if d[0] in days:
            yield d[1]

This creates a special object called a generator. Visit python tutorial and make yourself familiar with it.

This should print the expected result.

data = read_file()
wed_thur = 5
print(sum(iterate_by_day("WT", data) * wed_thur))

# This works the same
print(sum(iterate_by_day(["W", "T"], data)) * wed_thur)

Sign up to request clarification or add additional context in comments.

2 Comments

When I try to run that code, I get this error message: print(sum(iterate_by_day(["W", "T"], data) * wed_thur)) TypeError: unsupported operand type(s) for *: 'generator' and 'int'
Ooops, I've put one closing parenthesis in the wrong place. I've edited the question and now it should work fine.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.