set(集合)型を使う

30分プログラム、その205。新しめの機能であるset(集合)型を使ってみる。
名前から分かるように重複が許されていない。それ以外のインターフェースは、シーケンス型に似ている。

使い方

# 重複の削除
>>> uniq("aba")
['a', 'b']
>>> uniq("ab")
['a', 'b']

# 重複のチェック
>>> isDup("aa")
True
>>> isDup("ab")
False

ソースコード

#! /usr/bin/python
# -*- mode:python; coding:utf-8 -*-
#
# uniq.py -
#
# Copyright(C) 2007 by mzp
# Author: MIZUNO Hiroki / mzpppp at gmail dot com
# http://howdyworld.org
#
# Timestamp: 2007/12/17 22:54:45
#
# This program is free software; you can redistribute it and/or
# modify it under MIT Lincence.
#

def uniq(xs):
    """Remove duplicate element in xs. This method does not preserve order"""
    return [x for x in frozenset(xs)]

def isDup(xs):
    """Test if xs has duplicate element"""
    return len(frozenset(xs)) != len(xs)