0

I'm asking the user to input a keyword and then remove any duplicate characters.

Example:

Input: balloon

Output: balon

I've tried this solution: List of all unique characters in a string? but it marks it as a syntax error.

Any ideas?

Community
  • 1
  • 1
kaozbender
  • 95
  • 3
  • 8

5 Answers5

7

Try:

In [4]: from collections import OrderedDict
In [5]: def rawInputTest():
   ...:    x = raw_input(">>> Input: ")
   ...:    print ''.join(OrderedDict.fromkeys(x).keys())

In [6]: rawInputTest()
>>> Input: balloon
balon
Aaron
  • 2,383
  • 3
  • 22
  • 53
3

For your answer, order is important. Here is a one line solution:

word = raw_input()
reduced_word = ''.join(
    [char for index, char in enumerate(word) if char not in word[0:index]])
Andrew Carter
  • 371
  • 1
  • 4
  • OrderedDict is the most straight-forward, efficent answer. I was just puzzle-challenging myself and seeing if I could create a one-liner only using builtins to solve the problem! – Andrew Carter Mar 03 '15 at 04:16
0

You can use OrderedDict:

In [15]: from collections import OrderedDict

In [16]: s="ballon"

In [17]: od = OrderedDict.fromkeys(s).keys()

In [18]: print(od)
['b', 'a', 'l', 'o', 'n']

In [19]: "".join(od)
Out[19]: 'balon'
Marcin
  • 215,873
  • 14
  • 235
  • 294
  • Do I need to import something to use OrderedDict? – kaozbender Mar 03 '15 at 03:12
  • 1
    Yep, forgot about `from collections import OrderedDict` – Marcin Mar 03 '15 at 03:12
  • print(od) comes out as follows: KeysView(OrderedDict([('b', None), ('a', None), ('l', None), ('o', None), ('n', None)])). – kaozbender Mar 03 '15 at 03:14
  • 1
    It might be because I use ipython. However, the print result does not matter much IMO. What matters more is that it the answer preserves the order of characters, and the resulting string after `join` is correct. – Marcin Mar 03 '15 at 03:16
0

You are performing a set operation. If order is not import, just insert each character into a set and print the contents of the set when done. If the order is important, then create a set. For each character, if it is not in the set append it to a list and insert it into the set. Print the contents of the list in order when done.

Fred Mitchell
  • 2,145
  • 2
  • 21
  • 29
0
dict1 = {"cat":6,"rat":7,"dog":4,"elephent":20,"lion":15,"cow":9,"bat":4,"hen":2,"bird":2}

dic_values= dict1.values()

unique_val = set(dic_values)

print("dic_val :",dic_values)

print("unique_dict_valu :",unique_val)
4b0
  • 21,981
  • 30
  • 95
  • 142