Home > Net >  write a program to add two lists, Input is A=[1,2,3] ,B=[9,4,1] , output = [1,0,6,4].. i.e 123 941 =
write a program to add two lists, Input is A=[1,2,3] ,B=[9,4,1] , output = [1,0,6,4].. i.e 123 941 =

Time:11-29

'''The below code works fine when i give input like 1,2,3 and 4,5,6 in the codeforces editor,but how can i take input like [1,2,3] and [4,5,6] . Please help me out thank u :)'''

list1 = list(map(int,input().split(',')))

list2 = list(map(int,input().split(',')))

slist1 = [str(i) for i in list1]

slist2 = [str(i) for i in list2]

slist1_join = "".join(slist1)

slist2_join = "".join(slist2)

total =  int(slist1_join)   int(slist2_join)

final = list(str(total))

final1 = [int(i) for i in final]

print(final1)

CodePudding user response:

This can be done using the eval() function.

list1 =  eval(input())
list2 =  eval(input())
slist1 = [str(i) for i in list1]
slist2 = [str(i) for i in list2]
slist1_join = "".join(slist1)
slist2_join = "".join(slist2)
total = int(slist1_join)   int(slist2_join)
final = list(str(total))
final1 = [int(i) for i in final]
print(final1)

Output

[1,2,3]
[4,5,6]
[5, 7, 9]

CodePudding user response:

list1 = list(map(int,input()[1:][:-1].split(',')))

list2 = list(map(int,input()[1:][:-1].split(',')))

The [1:] will remove the first character (the "["), and the [:-1] will remove the last character (the "]"). Note that this will also accept input such as "a6,8,5%" and work with it correctly.

  • Related