Add solution to problem 6
This commit is contained in:
71
Problem6_2.py
Normal file
71
Problem6_2.py
Normal file
@@ -0,0 +1,71 @@
|
||||
def printList(numbersList: list[list[int]], symbolsList: list[str]) :
|
||||
for line in numbersList :
|
||||
print(f"{line}")
|
||||
print(f"{symbolsList}")
|
||||
|
||||
def parseInput() :
|
||||
numbers: list[list[int]] = [[]]
|
||||
for colNum in range(len(rawInput[0])) :
|
||||
numStr = ""
|
||||
for rowNum in range(len(rawInput) - 1) :
|
||||
char = rawInput[rowNum][colNum]
|
||||
if char != " " :
|
||||
numStr += char
|
||||
if len(numStr) > 0 :
|
||||
numbers[-1].append(int(numStr))
|
||||
elif len(numbers[-1]) > 0:
|
||||
numbers.append([])
|
||||
if len(numbers[-1]) == 0 :
|
||||
numbers.pop()
|
||||
|
||||
symbols: list[str] = []
|
||||
for sym in rawInput[-1].split(" ") :
|
||||
if len(sym.replace(" ", "")) == 0:
|
||||
continue
|
||||
symbols.append(sym.replace(" ", ""))
|
||||
return numbers, symbols
|
||||
|
||||
def getValue(col: list[int], symbol: str) :
|
||||
if symbol == "+" :
|
||||
value = sum(col)
|
||||
else :
|
||||
value = prod(col)
|
||||
print(f"list = {col}, sym = {symbol}, Value = {value}")
|
||||
return value
|
||||
|
||||
def prod(list: list[int]) :
|
||||
if len(list) == 0 :
|
||||
return 0
|
||||
value = 1
|
||||
for val in list :
|
||||
value *= val
|
||||
return value
|
||||
|
||||
|
||||
testInput = [
|
||||
"123 328 51 64 ",
|
||||
" 45 64 387 23 ",
|
||||
" 6 98 215 314",
|
||||
"* + * + "
|
||||
]
|
||||
|
||||
def readFile() :
|
||||
ary = []
|
||||
with open("files/Problem6.txt", "r") as file :
|
||||
for line in file :
|
||||
ary.append(line.replace("\n", ""))
|
||||
return ary
|
||||
|
||||
|
||||
#rawInput = testInput
|
||||
rawInput = readFile()
|
||||
numbers, symbols = parseInput()
|
||||
#printList(numbers, symbols)
|
||||
values: list[int] = []
|
||||
for colNum in range(len(numbers)) :
|
||||
value = getValue(numbers[colNum], symbols[colNum])
|
||||
values.append(value)
|
||||
|
||||
print(f"Sum = {sum(values)}")
|
||||
|
||||
#Sum = 9770311947567
|
||||
Reference in New Issue
Block a user