how to find the output from the list1 when reversed it should be excluded from the output
example: 32 reverse is 23 which is already in list l1 so that should be excluded. Similarly 98 reverse is 89 hence output shud be as below.
l1=[32,48,98,76,23,89]
output as [48,76]
tried this
l2=[]
x=[str(x) for x in l1]
print(x)
for var in x:
print(var,var[::-1])
o/p as below
32 23
48 84
98 89
76 67
23 32
89 98
if the reverse 32 is 23 then exclude it..
CodePudding user response:
You have successfully reversed the items in the input list. Now all you need to do is check if the reversed items are present in the input list or not. If not, then append those items to an output list. Try this.
l1=[32,48,98,76,23,89, 470, 74]
l2=[]
x=[str(x) for x in l1]
print(x)
out = []
for var in x:
# print(var,var[::-1])
if int(var[::-1]) not in l1:
out.append(int(var))
print(out) #[48, 76, 74]
Another approach without typecasting to string is below:
l1=[32,48,98,76,23,89, 470, 74]
out = []
for num in l1:
rev = 0
curr = num
while curr >0:
rev = rev*10 curr
curr = curr//10
if rev not in l1:
out.append(num)
print(out) # [48, 76, 74]
Note that both these approaches work only when the list contains whole numbers only. Also this will also work for a number that ends in 0. For example: if the input list contains 470 and 74, then 470 will be excluded from the output. As reverse of '470' = '074' and int('074') = 74, hence this item will be excluded.