Recent Changes - Search:

Oktatás

* Programozás 1
  + feladatsor
  + GitHub oldal

* Szkriptnyelvek
  + feladatsor
  + quick link

Teaching

Programming 1 (BI)
  ▸ exercises
  ▸ quick link

teaching assets


Félévek

* 2025/26/2
* archívum


Linkek

* kalendárium
* tételsorok
* jegyzetek
* szakdolgozat / PhD
* ösztöndíjak
* certificates
* C lang.
* C#
* D lang.
* Java
* Nim
* Nim2
  + exercises
* XC=BASIC
* old
  ✦C++, ✦Clojure, ✦Scala


[ edit | logout ]
[ sandbox | passwd ]

remove duplicates

Let's solve this exercise:

"Consider the following list: [5, 2, 3, 5, 1, 4, -200, 5, 1, 3, 2, 2, 5] . Remove the duplicates, i.e. an element should be present in the list maximum once. Let the result be a sorted list."

Solution 1 (arbitrary order)

If we need to remove the duplicates, then we can immediately think of using a set.

import std/sequtils    # toSeq(iter), map, filter
import std/algorithm   # sorted(seq), reversed(seq)
import std/sets


let
  li = @[5, 2, 3, 5, 1, 4, -200, 5, 1, 3, 2, 2, 5]
  result = sorted(li.toHashSet.toSeq)

echo result  # @[-200, 1, 2, 3, 4, 5]

Solution 2 (keep order)

If we have a seq and we want to remove the duplicates, then there's a seq method for this (link):

func deduplicate[T](s: openArray[T]; isSorted: bool = false): seq[T]

It removes the duplicates AND keeps the original order of the elements.

In this case, it's not necessary to convert the seq to a set and then back to a seq.

import std/sequtils    # toSeq(iter), map, filter
import std/algorithm   # sorted(seq), reversed(seq)

let
  li = @[5, 2, 3, 5, 1, 4, -200, 5, 1, 3, 2, 2, 5]

echo li.deduplicate()        # @[5, 2, 3, 1, 4, -200] ; the order is kept

echo sorted(li.deduplicate)  # @[-200, 1, 2, 3, 4, 5]
Cloud City

  

Blogjaim, hobbi projektjeim

* The Ubuntu Incident
* Python Adventures
* @GitHub
* heroku
* extra
* haladó Python
* YouTube listák


Debrecen | la France


[ edit ]

Edit - History - Print *** Report - Recent Changes - Search
Page last modified on 2026 June 03, 10:47