Home > Software design >  Mapping digits to their appearances in a list of numbers
Mapping digits to their appearances in a list of numbers

Time:02-21

I need to take in a sequence of numbers. The last number in this sequence gives a sequence of digits. For each digit, I need to create a list of all the numbers that contain that digit. If no numbers contain that digit, the list should contain 0 rather than an empty list.

Input:

 96 23 43 113 6 
 315

I need output like this:

[[23,43,113],[113],0]

need to store:
 1st element in k is 3 -> [23,43,113]
 2nd element in k is 1 -> [113]
 3rd element in k is 5 -> 0 (No 5 in any element in LIST(l))

I tried the following:

l=list(map(str,input().split()))
k=input()
ans=[[l[j]] for i in range(len(k)) for j in range(0,len(l)) if k[i] in l[j]]
print(ans)  

but received the following output:

[['23'], ['43'], ['113'], ['113'], ['113']]

CodePudding user response:

You're overcomplicating it:

>>> l = input().split()
96 23 43 113 6
>>> k = input()
315
>>> [[i for i in l if c in i] or 0 for c in k]
[['23', '43', '113'], ['113'], 0]
  • You don't need to map str over input().split(), because split() already gives you a list of strings.
  • The answer is just a simple nested comprehension:
    • c is each character in k
    • [i for i in l if c in i] gives you the elements of l that contain c
    • or 0 replaces any "falsey" item on the left (i.e. an empty list) with 0

Avoid doing iterations over things like range(len(l)) -- as this example illustrates, it's usually much simpler to just iterate over the contents directly!

CodePudding user response:

You should clean up your variable names -- it makes it much easier to identify and fix bugs. With that in mind, we can use two list comprehensions to get the following:

input_list = list(map(str, input().split()))
n = input()
ans = [[num for num in input_list if digit in num] for digit in n]
ans = [inner_list if (len(inner_list) > 0) else 0 for inner_list in ans]
print(ans) # Prints [['23', '43', '113'], ['113'], 0]

CodePudding user response:

Why don't you just do it not in one line, This way it would be more transparent:

goal = []
for char in list(k):
    temp = [element for element in l if char in element]
    temp = temp if temp else 0
    goal.append(temp)

But if you still want your code to be short in one line:

goal = [[element for element in l if char in element] or 0 for char in k]

CodePudding user response:

There are a lot of good methods already, but I would like to offer mine as well:

s1 = '96 23 43 113 6'
s2='315'
l = s1.split(" ")

l2 = [[target for target in l if set(target)&set(elem)] for elem in s2]

final = [e if e != [] else 0 for e in l2 ]

print(final)

Output:

[['23', '43', '113'], ['113'], 0]
  • Related