I found this on HackerRank.
I had to type the no. of students (say n). Then the following n lines each had Student name, and marks of three subjects to be input by the user. The next line consisted of the name of any of the students. Based on that input, I had to calculate the average of that student's marks.I had to provide an input like this(according to the testcases):
4
nameA 50 50 50
nameB 69 78 45
nameC 56 47 45
nameD 57 49 30
nameC
As I had to give mutiple type inputs on the same line, while I tried to append the list, it gave me an 'invalid literal' error. So I used input().split(" ")
. This is my code:
if __name__ == '__main__':
n = int(input())
list1 = []
for i in range(0,n):
a = input().split(" ")
b = input().split(" ")
c = input().split(" ")
d = input().split(" ")
b = float(b)
c = float(c)
d = float(d)
list1.append(a)
list1.append(b)
list1.append(c)
list1.append(d)
name = input().split()
avg = 0.00
inn = list1.index(name)
avg = (list1[inn+1]+list1[inn+2]+list2[inn+3])/3
print(avg)
But this was the error displayed:
Traceback (most recent call last):
File "solution.py", line 11, in <module>
b = float(b)
TypeError: float() argument must be a string or a number, not 'list'
ON the other hand if I simply give the input using input()
, there is the 'invalid literal with base 10' error again.
What is going wrong with typecasting? And how can I give different types of inputs in a single line(i.e using spaces). I tried to do this question using nested lists, too. But if I have to append the nested list, what must be the syntax?
b = input().split(" ")
b variable is of type list
, split()
method make list of values, you can do something like this
#for example variable `a` is [1,2,3,4]
# make new list with `float`
a_float_lst = [float(x) for x in a]
# and now concatenate with our `list_1` list
list_1 += a_float_lst
Update
if __name__ == '__main__':
lst = []
for i in range(int(input())):
student, b, c, d = input().split()
lst.append([student, float(b), float(c), float(d)])
name = input()
inn = None
for x in lst:
if name in x:
inn = x
avg = (inn[1] + inn[2] + inn[3]) / 3
print('{:.2f}'.format(avg))
Input
2
nameA 50 50 50
nameB 69 78 45
nameA
Output
50.0