-7
n=int(input())
c={}
for i in range(n):
    name=str(input())
    c[name]=list(input().split())
print(c)
query=input()
query_scores=c[query]
print(sum(query_scores))

The sum function is not working. It shows:

TypeError: unsupported operand type(s) for +: 'int' and 'str'

Omar Einea
  • 2,478
  • 7
  • 23
  • 35
  • 1
    `query_scores=c[query]` - those are strings. how do you sum up strings? `query_scores=map(int,c[query])` _might_ work, if the contained list only contains numbers that can be converted to int - else it will throw you ValueErrors - I feel as if hackerrank related questions provide > 80% of the bad questions coming in ... – Patrick Artner Mar 03 '18 at 10:49
  • 2
    Happy Coding. Please go over [how to ask](https://stackoverflow.com/help/how-to-ask) and [on-topic](https://stackoverflow.com/help/on-topic). Read,live and breathe [how to debug small programs](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/) as well - and start using a debugger. – Patrick Artner Mar 03 '18 at 10:50

2 Answers2

1

From sum's description:

Sums start and the items of an iterable from left to right and returns the total. start defaults to 0. The iterable’s items are normally numbers, and the start value is not allowed to be a string.

Since the sum starts to 0 (by default), you need to cast the elements you want to sum to something that can be added to 0. strings cannot. You need to do something like this:

print(sum(int(x) for x in query_scores))

or, if you want to use floating numbers,

print(sum(float(x) for x in query_scores))
lr1985
  • 1,085
  • 1
  • 9
  • 21
  • do not encourage bad questions – Patrick Artner Mar 03 '18 at 10:53
  • I understand the first part of your comment and I apologise for that (and will delete the answer if that's better), but how does my answer not address the question? – lr1985 Mar 03 '18 at 10:56
  • 1
    Sorry, did not read far enough. It does address the problem. -1 to +0 but still, please dont answer bad questions. The Q was already answered in the comment about 4 minutes before your post, but I guess you were already writing your answer up and editing it at that point so you did not see that. – Patrick Artner Mar 03 '18 at 10:58
0

You have to convert the list items into any numeric type. The split function returns the string type and you are performing the sum in the str type

c[name]=list(input().split())

Can be changed into

c[name] = [ int(i) for i in input().split()]