This code is supposed to read two files and calculate the potential cost of all its characters. The file with costs (lettercosts.txt) looks like this:
- a 1
- b 3
- c 2 etc...
Here I was trying to make this all work, but I so far it is all unsuccessfully. Any hint where is the problem with the code?
def generate_cost_dict():
letter_costs_dict = {}
file = open("lettercosts.txt")
with open("lettercosts.txt") as file:
letter_cost_dict = {letter: int(cost)
for letter, cost in map(str.split, file)}
return letter_costs_dict
def calculate_cost(article, lc_dict):
with open("news1.txt") as x:
for char in x.read():
return sum(letter_cost_dict.get(char, 0)
with open("news2.txt") as y:
for char in y.read():
return sum(letter_cost_dict.get(char, 0)
def main():
# Generating the mapping from letters to their USD costs
lc_dict = generate_cost_dict()
# Calculating the costs of the sample articles
x = calculate_cost( "news1.txt", lc_dict )
y = calculate_cost( "news2.txt", lc_dict )
print("news1.txt costs",x,"USD.")
print("news2.txt costs",y,"USD.")
if __name__ == '__main__':
main()