0

I have :

  • 1 array input (A)
  • 1 array (B) for compare (comparing A to B)
  • 1 array output
I want the data to be like this :
    data array A    data array B      output array
    Alpha           Alpha             Alpha*
    Delta           Beta              Beta
    Fanta           Charlie           Charlie    
                    Delta             Delta*
                    Echo              Echo
                    Fanta             Fanta*

What I want is, whenever there is a same data in array A and B, "the data" marked by *. I'm sorry if my english is not easy to understand.

Thanks in advance

4
  • What you want in this do you want to merge the two arrays with same element appearing once ? list(set(arr1 + arr2)) Commented Aug 31, 2020 at 6:46
  • Please include what you have tried already to give us a start. SO is not a code writing service that will provide code from scratch. Commented Aug 31, 2020 at 6:47
  • The question is not clear to me: do you want the output array to be a union of the input arrays, but the items that show up in the intersection to be modified to have a '*' concatenated to them ? Commented Aug 31, 2020 at 6:47
  • I'm sorry if the question is not clear, I have modified my question. Commented Aug 31, 2020 at 6:59

1 Answer 1

1

I hope I understood your question right: you want to merge two arrays, and each element should appear only once (assuming sorted lists a and b):

from heapq import merge
from itertools import groupby

a = ['Alpha', 'Delta', 'Fanta']
b = ['Alpha', 'Beta', 'Charlie', 'Delta', 'Echo']

c = [v for v, _ in groupby(merge(a, b))]

print(c)

Prints:

['Alpha', 'Beta', 'Charlie', 'Delta', 'Echo', 'Fanta']

EDIT: To mark duplicate elements with *, you can do:

from heapq import merge
from itertools import groupby

# assuming sorted `a` and `b`:
a = ['Alpha', 'Delta', 'Fanta']
b = ['Alpha', 'Beta', 'Charlie', 'Delta', 'Echo', 'Fanta']

c = ['{}*'.format(v) if len(list(g)) > 1 else v for v, g in groupby(merge(a, b))]

print(c)

Prints:

['Alpha*', 'Beta', 'Charlie', 'Delta*', 'Echo', 'Fanta*']
Sign up to request clarification or add additional context in comments.

6 Comments

why not use list(set(a+b))
@DeepakTripathi set() is unordered structure and I think OP wants sorted output.
@AndrejKesely i run your code with a = ['Alpha', 'Delta', 'Fanta','Alpha'] (note 2 'alpha' in the array a) so it produce output as ['Alpha', 'Beta', 'Charlie', 'Delta', 'Echo', 'Fanta', 'Alpha']
@vgeorge I assumed sorted lists a and b. If they aren't sorted, you need to do a = sorted(a) and for b too before merge.
yea, i want a sorted output, and if there is a same data in array A and B, "the data" marked by *.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.