📌  相关文章
📜  国际空间研究组织 | ISRO CS 2007 |问题 6(1)

📅  最后修改于: 2023-12-03 15:37:13.815000             🧑  作者: Mango

ISRO CS 2007 - Question 6

This is a question from the Indian Space Research Organization (ISRO) Computer Science 2007 exam. It is a programming question that requires the implementation of a function.

Problem Statement

Write a function unique(A) that takes a list A of integers as its parameter and returns another list containing only the unique elements of A. The order of the elements in the output list should be the same as the order of their first appearance in the input list.

Example
Input: A = [2, 6, 1, 2, 4, 6, 7, 8]
Output: [2, 6, 1, 4, 7, 8]
Solution

We can solve this problem by iterating over the elements of the input list A and adding each element to a new list B, only if it has not been added previously. We can check for duplicates by maintaining a set of elements that have already been added to B. Here's the code:

def unique(A):
    B = []
    seen = set()
    for x in A:
        if x not in seen:
            B.append(x)
            seen.add(x)
    return B

The seen set keeps track of the elements that have already been added to B. The if x not in seen condition checks if the current element x has not been added before, in which case we add it to B and also add it to seen. Finally, we return the new list B that contains only the unique elements of the input list.

Markdown
## ISRO CS 2007 - Question 6

This is a question from the Indian Space Research Organization (ISRO) Computer Science 2007 exam. It is a programming question that requires the implementation of a function.

### Problem Statement

Write a function `unique(A)` that takes a list `A` of integers as its parameter and returns another list containing only the unique elements of `A`. The order of the elements in the output list should be the same as the order of their first appearance in the input list.

### Example

```
Input: A = [2, 6, 1, 2, 4, 6, 7, 8]
Output: [2, 6, 1, 4, 7, 8]
```

### Solution

We can solve this problem by iterating over the elements of the input list `A` and adding each element to a new list `B`, only if it has not been added previously. We can check for duplicates by maintaining a set of elements that have already been added to `B`. Here's the code:

```python
def unique(A):
    B = []
    seen = set()
    for x in A:
        if x not in seen:
            B.append(x)
            seen.add(x)
    return B
```

The `seen` set keeps track of the elements that have already been added to `B`. The `if x not in seen` condition checks if the current element `x` has not been added before, in which case we add it to `B` and also add it to `seen`. Finally, we return the new list `B` that contains only the unique elements of the input list.