JonnyDoeInWisco
JonnyDoeInWisco

Reputation: 233

Comparing and Combining List Items in Python

Im working on Advent of Code: Day 2, and Im having trouble working with lists. My code takes a string, for example 2x3x4, and splits it into a list. Then it checks for an 'x' in the list and removes them and feeds the value to a method that calculates the area needed. The problem is that before it removes the 'x's I need to find out if there are two numbers before the 'x' and combine them, to account for double digit numbers. I've looked into regular expressions but I don't think I've been using it right. Any ideas?

def CalcAreaBox(l, w, h):
    totalArea = (2*(l*w)) + (2*(w*h))+ (2*(h*l))
    extra = l * w
    toOrder = totalArea + extra
    print(toOrder)

def ProcessString(dimStr):

    #seperate chars into a list
    dimStrList = list(dimStr)
    #How to deal with double digit nums?

    #remove any x
    for i in dimStrList:
        if i == 'x':
            dimStrList.remove(i)
    #Feed the list to CalcAreaBox
    CalcAreaBox(int(dimStrList[0]), int(dimStrList[1]), int(dimStrList[2]))

dimStr = "2x3x4"  
ProcessString(dimStr)

Upvotes: 0

Views: 40

Answers (2)

AlexV
AlexV

Reputation: 590

Your question is more likely to fit on Code Review and not Stack Overflow.

As your task is a little challenge, I would not tell you an exact solution, but give you a hint towards the split method of Python strings (see the documentation).

Additionally, you should check the style of your code against the recommendation in PEP8, e.g. Python usually has function/variable names in all lowercase letters, words separated by underscores (like calc_area_box).

Upvotes: 0

computational_linguist
computational_linguist

Reputation: 113

You could use split on your string

#remove any x and put in list of ints
dims = [int(dim) for dim in dimStrList.split('x')]
#Feed the list to CalcAreaBox
CalcAreaBox(dims[0], dims[1], dims[2])

Of course you will want to consider handling the cases where there are not exactly two X's in the string

Upvotes: 1

Related Questions