공지: 기존 사이트는 old.codingdojang.com에서 확인할 수 있으며, 2026년 8월 3일 종료됩니다.
이 페이지는 코딩도장 데이터의 읽기 전용 정적 보관본입니다.

487-3229

http://poj.org/problem?id=1002 (미국의 워털루 대학에서 있었던 icpc 문제)

회사원들은 외우기 좋은 전화번호를 갖고 싶어한다. 전화번호를 외우기 쉽도록 만드는 한 방법은 기억하기 좋은 단어나 구절이 되도록 하는 것이다. 예를 들어, 워털루 대학의 전화는 TUT-GLOP으로 전화를 걸 수 있다. 때때로 번호의 일부만이 단어를 쓰기 위해 사용될 수 있다. Gino에서 피자를 주문하기 위해 310-GINO로 전화를 거는 식이다. 전화번호를 외우기 좋도록 하는 또다른 방법은 숫자들을 기억하기 좋은 방법으로 묶는 것이다. 3-10-10-10 (Three-tens)으로 전화를 걸면 피자헛에 주문을 할 수 있다.

전화번호의 표준형은 세 번째 번호와 네 번째 번호 사이에 하이픈(-)을 삽입한 7개의 숫자로 구성되어 있다. (예: 888-1200). 전화기의 키패드는 다음과 같은 글자 대 숫자의 대응을 지닌다.

A, B, C -> 2
D, E, F -> 3
G, H, I -> 4
J, K, L -> 5
M, N, O -> 6
P, R, S -> 7
T, U, V -> 8
W, X, Y -> 9

Q와 Z에 대한 대응관계는 존재하지 않는다. 하이픈은 전화기에 입력되지 않으며 필요에 따라 추가되거나 빠질 수 있다. TUT-GLOP의 표준형은 888-4567이고, 310-GINO의 표준형은 310-4466, 3-10-10-10의 표준형은 310-1010이다.

만약 어떤 두 전화번호가 같은 표준형을 지니면 그들은 같은 번호이다.

여러분의 회사는 지역 회사원들의 전화번호를 정리하고 있다. 품질 관리 과정의 일환으로, 여러분은 정리된 전화번호부의 번호 중에 같은 것이 둘 이상 있지 않은지 확인하고 싶다.

Input

입력은 하나의 테스트 케이스로 구성된다. 입력의 첫 줄은 전화번호의 갯수(<=100,000)로 이뤄져 있다. 남은 줄들은 전화번호부 내의 전화번호들이 한 줄에 하나씩 들어 있다. 각 전화번호는 십진 숫자들과 대문자(Q,Z 제외), 하이픈으로 구성된 문자열로 이뤄져 있다. 문자열 내에서 정확히 7개의 문자들이 숫자 또는 알파벳 문자이다.

Output

한 번 이상 등장한 전화번호들이 출력을 구성한다. 각 줄은 표준형으로 표현된 전화번호와 출현 횟수가 하나의 공백 문자로 구분되어 있다. 출력되는 전화 번호들은 증가하는 사전식 순서로 되어 있어야 한다. 만약 입력으로 들어온 전화번호 중에 중복이 없다면 "No duplicates."를 출력한다.

Sample Input

12
4873279
ITS-EASY
888-4567
3-10-10-10
888-GLOP
TUT-GLOP
967-11-11
310-GINO
F101010
888-1200
-4-8-7-3-2-7-9-
487-3279

Sample Output

310-1010 2
487-3279 4
888-4567 3

2014/03/26 17:09

Kim Jaeju

73개의 풀이가 있습니다.

각라인을 변환하고, 변환된 결과를 키로 하는 사전에서 개수를 카운트하도록 했습니다.

def main(input):
    AZ = "ABCDEFGHIJKLMNOPRSTUVWXY"
    table = {}
    for a in range(0, 8):
        for c in AZ[a*3:a*3+3]:
            table[c] = str(a+2)

    result = {}
    for line in input.split()[1:]:
        source = line.strip().replace("-", "")
        transformed = "".join(([table.get(x, x) for x in list(source)]))
        result[transformed] = result.get(transformed, 0) + 1

    for print_line in sorted(result.keys()):
        print print_line[:3]+"-"+print_line[3:],\
            (result[print_line] if result[print_line] else "No duplicates.")

2014/12/11 18:54

룰루랄라

+1 AZ = "ABCDEFGHIJKLMNOPRSTUVWXY" table = {} for c n AZ: table[c] = AZ.index(c)/3+2 요렇게 해도 될듯합니다. - 상파, 2016/01/22 01:44
훨씬 간결해지는군요! - 룰루랄라, 2016/04/22 22:44
+1 AZ = "ABCDEFGHIJKLMNOPRSTUVWXY" table = {} for c n AZ: table[c] = int(AZ.index(c)/3)+2 이렇게 int함수 처리를 하면 될 것 같습니다. - kim ih, 2020/08/02 16:13

python 2.7

M = {
    'ABC':'2',
    'DEF':'3',
    'GHI':'4',
    'JKL':'5',
    'MNO':'6',
    'PRS':'7',
    'TUV':'8',
    'WXY':'9',
}


#
# alpha to number: A -> 2, B -> 2, J -> 5
#
def alpha2num(alpha):
    for k in M.keys():
        if alpha in k: return M[k]


#
#  memorable word to phone number: TUT-GLOP -> 888-4567
#
def memorable2num(s):
    s = s.replace("-", "")
    result = []
    for n in list(s):
        if not n.isdigit():
            n = alpha2num(n)
        result.append(n)
    r = "".join(result)
    return "%s-%s" % (r[:3], r[3:])


def check_duplicate(src):
    src = src.strip()
    result = {}
    for s in src.split("\n"):
        r = memorable2num(s)
        if r in result: 
            result[r] += 1
        else:
            result[r] = 1

    found = False
    for k in sorted(result.keys()):
        if result[k] > 1:
            print k, result[k]
            found = True

    if not found:
        print  "No duplicates."


check_duplicate("""4873279
ITS-EASY
888-4567
3-10-10-10
888-GLOP
TUT-GLOP
967-11-11
310-GINO
F101010
888-1200
-4-8-7-3-2-7-9-
487-3279""")

2014/03/26 23:44

pahkey

JAVA

package phonenumber;
public class Ph {
    String S=""; int n=0, re=0;
}
package phonenumber;
import java.util.Scanner;
public class Phonenum {

    public static void main(String[] args) {
        Scanner in=new Scanner(System.in);
        int i,j,k,tempN,tempRe,re=0, N=in.nextInt(); //input the number of phonenumbers : N
        String input,tempS;
        String[] AtoN={"ABC","DEF","GHI","JKL","MNO","PRS","TUV","WXY"};
        Ph[] P=new Ph[N];

        for(i=0;i<N;i++){
            input=in.next(); //input each phonenumber
            input=input.replace("-","");
            P[i]=new Ph();
            for(j=0;j<input.length();j++) //Change from a character to a number
                for(k=0;k<8;k++)
                    if(AtoN[k].contains(input.charAt(j)+"")){
                        input=input.substring(0,j)+((k+2)+"")+input.substring(j+1);
                        break;
                    }
            P[i].S=input;
            for(k=0;k<i;k++)
                if(P[i].S.equals(P[k].S)){
                    P[k].re++;
                    if(P[k].re==1) re++;
                    break;
                    }   
        }
        //for(i=0;i<N;i++) System.out.println(P[i].S+" "+P[i].re); System.out.println();

        Ph[] P_re=new Ph[re];
        for(i=0, j=0;j<re;i++){ //Finding only repeated phonenumbers
            if(P[i].re>0){
                P_re[j]=new Ph();
                P_re[j].S=P[i].S; P_re[j].re=P[i].re;
                for(k=0;k<P[i].S.length();k++){
                    if((int)P[i].S.charAt(k)<48||(int)P[i].S.charAt(k)>57) break;
                }
                if(k!=P[i].S.length()) P_re[j].n=0;
                else P_re[j].n=Integer.parseInt(P_re[j].S);
                j++;
            }
        }

        for(i=0;i<re;i++){ //Ordering the repeated phonenumbers
            for(j=i+1;j<re;j++){
                if(P_re[i].n>P_re[j].n){
                    tempS=P_re[i].S; tempN=P_re[i].n; tempRe=P_re[i].re;
                    P_re[i].S=P_re[j].S; P_re[i].n=P_re[j].n; P_re[i].re=P_re[j].re;
                    P_re[j].S=tempS; P_re[j].n=tempN; P_re[j].re=tempRe;
                }
            }
        }

        //Print
        if(re==0) System.out.println("No duplicates.");
        else for(i=0;i<re;i++) if(P_re[i].n>0)
            System.out.println(P_re[i].S.substring(0,3)+"-"+P_re[i].S.substring(3,7)+" "+(P_re[i].re+1));
    }
}

2014/04/15 15:13

Katherine

data = '''\
4873279
ITS-EASY
888-4567
3-10-10-10
888-GLOP
TUT-GLOP
967-11-11
310-GINO
F101010
888-1200
-4-8-7-3-2-7-9-
487-3279\
'''

repl = [['[ABC]', '2'],
    ['[DEF]', '3'],
    ['[GHI]', '4'],
    ['[JKL]', '5'],
    ['[MNO]', '6'],
    ['[PRS]', '7'],
    ['[TUV]', '8'],
    ['[WXY]', '9'],
    ['-', '']]

import re
from collections import Counter

result = Counter()
# 코드 치환
for re1, re2 in repl:
    data = re.sub(re1,re2,data)
# 데이터 카운트    
for l in data.split('\n'):
    result[l[:3]+'-'+l[3:]] += 1
# 데이터 정렬해서 출력
for i in sorted(result.keys()):
    if(result[i] != 1): print(i, result[i])

#Output:
# 310-1010 2
# 487-3279 4
# 888-4567 3

2018/07/04 21:12

재즐보프

허접한 코드 올려봅니다. 자바스크립트입니다.

function getNumFromAlpha (alpha) {
    var map = ['ABC', 'DEF', 'GHI', 'JKL', 'MNO', 'PRS', 'TUV', 'WXY'];

    for(var i in map)
        if(map[i].indexOf(alpha) !== -1) return +i+2;

    return -1;
};

function findDuplicate (input) {
    var elem = input.split("\n"),
        count = {},
        countKeys = [],
        isFound = false;


    for(var i = 0 ; i <= elem[0] ; i++) {
        var stripped = elem[i].replace(/\-/g, '');
        var filtered = "";
        for(var j = 0 ; j < stripped.length ; j++)
            filtered += stripped[j].match(/[a-z]/gi) ? (getNumFromAlpha(stripped[j])) : stripped[j];

        if(! count[filtered]) {
            count[filtered] = 0;
            countKeys.push(filtered);
        }

        count[filtered]++;
    }

    countKeys = countKeys.sort();
    for(var i in countKeys) {
        if(count[ countKeys[i] ] > 1) {
            isFound = true;
            console.log(countKeys[i].substr(0,3) + "-" + countKeys[i].substr(3,4) + " " + count[ countKeys[i] ]);
        }
    }

    if(! isFound) console.log("No duplicates.");
};


var testData = "12\n4873279\nITS-EASY\n888-4567\n3-10-10-10\n888-GLOP\nTUT-GLOP\n967-11-11\n310-GINO\nF101010\n888-1200\n-4-8-7-3-2-7-9-\n487-3279";
findDuplicate(testData);

2014/03/31 05:28

Lee MooYeol

Ruby

class String
  def to_num
    case self
    when /[ABC]/
      return "2"
    when /[DEF]/
      return "3"
    when /[GHI]/
      return "4"
    when /[JKL]/
      return "5"
    when /[MNO]/
      return "6"
    when /[PRS]/
      return "7"
    when /[TUV]/
      return "8"
    when /[WXY]/
      return "9"
    when /([0-9])/
      return $1
    when "-"
      return nil
    end
  end

  def to_phone_number
    self.scan(/./).
      map{|c| c.to_num}.compact.
      map.with_index{|item, i| i == 2 ? item + "-" : item}.join
  end
end

def result(phone_numbers)
  sum = phone_numbers.
    map{|item| item.to_phone_number}.
    sort.group_by{|item| item}.
    delete_if{|k,v| v.count < 2}

  sum.size == 0 ? ("No Duplicates.") : sum.map{|k,v| k+ " " + v.size.to_s}
end

Test

require 'test/unit'
extend Test::Unit::Assertions

sample_phone_numbers = %w(4873279
ITS-EASY
888-4567
3-10-10-10
888-GLOP
TUT-GLOP
967-11-11
310-GINO
F101010
888-1200
-4-8-7-3-2-7-9-
487-3279)

assert_equal result(sample_phone_numbers), ["310-1010 2", "487-3279 4", "888-4567 3"] 

2014/04/05 11:59

nacyot

// SP_IneEditApart.cpp : 콘솔 응용 프로그램에 대한 진입점을 정의합니다.
//

#include "stdafx.h"
#include <map>
using namespace std;

map<int,int> m1;
typedef pair <int,int> Int_Pair;


char chTest[][32] = 
{
"4873279"
,"ITS-EASY"
,"888-4567"
,"3-10-10-10"
,"888-GLOP"
,"TUT-GLOP"
,"967-11-11"
,"310-GINO"
,"F101010"
,"888-1200"
,"-4-8-7-3-2-7-9-"
,"487-3279"
};


void AddMap(int nPhoneNo)
{
    map<int,int> ::iterator iter = m1.find(nPhoneNo);
    if(iter != m1.end())
    {
        iter ->second++;
    }else
    {
        m1.insert(Int_Pair(nPhoneNo,1));
    }
}

int _tmain(int argc, _TCHAR* argv[])
{
    char chInput[32];
    for(int n = 0; n < 12 ; n ++)
    {
        strcpy(chInput,chTest[n]);
        if(chInput[0] == '~')break;
        char chPhoneNo[32];     int nIndex = 0;
        for(int iter = 0 ; iter < strlen(chInput) ; iter ++)
        {
            if(chInput[iter] == '-')                continue;
            if(chInput[iter] <= '9')                chPhoneNo[nIndex++] = chInput[iter];
            else chPhoneNo[nIndex++] = (chInput[iter] - 'A' - ((chInput[iter] > 'Q') ? 1 : 0))/3 + '2';
        }
        chPhoneNo[nIndex] = 0;
        AddMap(atoi(chPhoneNo));
    }
    bool bNoDup = true;
    for(map<int,int> ::iterator iter = m1.begin() ; iter != m1.end(); iter ++)
    {
        char count[32];     
        if(iter->second > 1 )
        {
            bNoDup = false;
            printf("%d-%d %d\n",iter->first/10000,iter->first%10000,iter->second );
        }
    }
    if(bNoDup)
    {
        printf("No Dupl");
    }


    return 0;
}

2014/06/02 17:09

김 영남

이런 경우는 regexp보다는 tr을 사용하는 게 나은 것 같아요.

TRANSRATORS = [
  "ABC", "2",
  "DEF", "3",
  "GHI", "4",
  "JKL", "5",
  "MNO", "6",
  "PRS", "7",
  "TUV", "8",
  "WXY", "9",
  "-", ""
]

def to_phone_number(str)
  TRANSRATORS.each_slice(2) { |f, t| str.tr!(f, t) }
  "#{str[0, 3]}-#{str[3, 4]}"
end

def counted_numbers(inputs)
  numbers = Hash.new(0)
  inputs.each do |input|
    number = to_phone_number(input)
    numbers[number] += 1
  end
  numbers
end

def print_dup_numbers(inputs)
  numbers = counted_numbers(inputs).select {|_, count| count > 1}

  if numbers.empty?
    puts "No duplicates."
  else
    numbers.each { |number, count| puts "#{number} #{count}" }
  end
end

print_dup_numbers %w[
  4873279
  ITS-EASY
  888-4567
  3-10-10-10
  888-GLOP
  TUT-GLOP
  967-11-11
  310-GINO
  F101010
  888-1200
  -4-8-7-3-2-7-9-
  487-3279
]

2014/12/12 22:09

Shim Won

Perl

$s.=$_ for(<>);
$_=uc($s);
s/[^A-Z0-9\n]//g;
s/(...)(....)/$1-$2/g;
s/[ABC]/2/g;
s/[DEF]/3/g;
s/[GHI]/4/g;
s/[JKL]/5/g;
s/[MNO]/6/g;
s/[PRS]/7/g;
s/[TUV]/8/g;
s/[WXY]/9/g;
@a=split(/\n/);
shift @a;
$b{$_}++ for(@a);
print "$_ $b{$_}\n" for(sort keys %b);

2015/01/04 19:58

*IDLE*

C#으로 작성했습니다. 두번째로 작성한 코드는 Dictionary를 이용하여서 조금 더 간편하게 작성했습니다. O(n^2) 입니다.

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;

namespace CodingDojang
{

    class CodingDojang
    {
        static void Main(string[] args)
        {
            Telephone.Answer();
        }
    }

    public class Telephone
    {

        public static void Answer()
        {
            var n = int.Parse(Console.ReadLine());

            var inputs = new List<string>();

            for (int i = 0; i < n; i++)
            {
                var temp = Console.ReadLine().Replace("-", "");
                inputs.Add(temp);
            }

            var telephone = Telephone(inputs);
            var sortedList = telephone
                .Where(t => telephone.Count(t.Contains) > 1)
                .OrderBy(t => t)
                .GroupBy(t => t)
                .Select(t => t.Key).ToList();
            if (sortedList.Count == 0) Console.WriteLine("No duplicates");
            foreach (var sorted in sortedList)
            {
                var count = telephone.Count(sorted.Contains);
                Console.WriteLine(sorted + " " + count);
            }

        }

        public static List<string> Telephone(List<string> inputs)
        {
            var telephone = new List<string>();
            foreach (var input in inputs)
            {
                var check = 0;
                var output = string.Empty;
                foreach(var i in input)
                {
                    var verification = int.TryParse(i.ToString(), out check);
                    if (i.ToString() == "A" || i.ToString() == "B" || i.ToString() == "C") output += "2";
                    else if (i.ToString() == "D" || i.ToString() == "E" || i.ToString() == "F") output += "3";
                    else if (i.ToString() == "G" || i.ToString() == "H" || i.ToString() == "I") output += "4";
                    else if (i.ToString() == "J" || i.ToString() == "K" || i.ToString() == "L") output += "5";
                    else if (i.ToString() == "M" || i.ToString() == "N" || i.ToString() == "O") output += "6";
                    else if (i.ToString() == "P" || i.ToString() == "R" || i.ToString() == "S") output += "7";
                    else if (i.ToString() == "T" || i.ToString() == "U" || i.ToString() == "V") output += "8";
                    else if (i.ToString() == "W" || i.ToString() == "X" || i.ToString() == "Y") output += "9";
                    else if (verification) output += i.ToString();
                }
                output = output.Insert(3, "-");
                telephone.Add(output);
            }
            return telephone;
        }

        public Dictionary<string, int> Initialize()
        {
            var dictionary = new Dictionary<string, int>();
            dictionary.Add("ABC", 2);
            dictionary.Add("DEF", 3);
            dictionary.Add("GHI", 4);
            dictionary.Add("JKL", 5);
            dictionary.Add("MNO", 6);
            dictionary.Add("PRS", 7);
            dictionary.Add("TUV", 8);
            dictionary.Add("WXY", 9);
            return dictionary;
        }

        public void Telephone(Dictionary<string, int> dictionary, List<string> inputs)
        {
            var outputs = new Hashtable();
            foreach (var input in inputs)
            {
                var update = input.Replace("-", "").Trim();
                var output = string.Empty;
                foreach (var c in update)
                {
                    if (char.IsDigit(c)) output += Convert.ToChar(c);
                    else if (c == 'Q' || c == 'Z') break;
                    else output += dictionary.FirstOrDefault(d => d.Key.Contains(c)).Value;
                }
                if(output.Length == 7) 
                    outputs[output] = outputs.ContainsKey(output) ? (int) outputs[output] + 1 : 1;
            }
        }

    }

}

2015/09/08 23:03

Straß Böhm Jäger

python 3.4입니다

from collections import Counter

source = 'ABCDEFGHIJKLMNOPRSTUVWXY'
output = '222333444555666777888999'
trans = str.maketrans(source, output, '-')

def normalize(text):
    translated_text = text.translate(trans)
    return translated_text[:3] + '-' + translated_text[3:]

def get_duplicates(numbers):
    normalized_numbers = [normalize(x) for x in numbers]
    duplicates_list =  [(key, value) for key, value in Counter(normalized_numbers).items() if value > 1]
    return sorted(duplicates_list)

if __name__ == '__main__':
    num_count = int(input('>'))
    numbers = []

    for _ in range(num_count):
        numbers.append(input('>'))

    dupl = get_duplicates(numbers)
    print()

    if dupl:
        for key, value in dupl:
            print(key, value)
    else:
        print('No duplicates.')

2016/01/04 00:35

투플러스

가독성 신경써서 코드 짜봤습니다.

#-*- coding: utf-8 -*-
d={ 'A':'2','B':'2','C':'2',
    'D':'3','E':'3','F':'3',
    'G':'4','H':'4','I':'4',
    'J':'5','K':'5','L':'5',
    'M':'6','N':'6','O':'6',
    'P':'7','R':'7','S':'7',
    'T':'8','U':'8','V':'8',
    'W':'9','X':'9','Y':'9',
    '1':'1','2':'2','3':'3','4':'4','5':'5',
    '6':'6','7':'7','8':'8','9':'9','0':'0',
    '-':''   }
line_num = input()
phone_book= {}
for i in range(line_num):
    line = raw_input()
    phone = ''.join(d[x] for x in line) #위 사전을 이용하여 변환
    phone = phone[:3]+'-'+phone[3:] #중간에 하이픈 삽입
    if phone_book.has_key(phone):phone_book[phone] += 1
    else: phone_book[phone] = 1
temp = zip(phone_book.keys(), phone_book.values())
phone_list = filter(lambda x:x[1]>1, temp) # 갯수가 1개 초과하는 것만 필터링
phone_list.sort(key=lambda x:x[0])
if phone_list:
    for p,n in phone_list:
        print p,n
else:
    print 'No duplicates'

2016/01/22 01:46

상파

Ruby

matches = [*"A".."Y"].join.gsub(/(...)/).zip("2".."9")
p_num = ->str { str.delete("-").insert(3,"-").tap {|e| matches.each{|f,n| e.tr!(f,n)} } }
dups = ->texts { texts.map(&p_num).group_by{|e|e}.reject {|_,v| v.size<2 } }
check = ->texts { sum=dups[texts]; sum.size>0? sum.map {|k,v| [k,v.size]*' ' } : "No dups" }

Test

dups_set = %w[4873279 ITS-EASY 888-4567 3-10-10-10 888-GLOP TUT-GLOP 
            967-11-11 310-GINO F101010 888-1200 -4-8-7-3-2-7-9- 487-3279]
no_dups_set = %w[123-4567 487-3279]
expect(check[dups_set]).to eq ["487-3279 4", "888-4567 3", "310-1010 2"]
expect(check[no_dups_set]).to eq "No dups"

2016/03/27 21:00

rk

while __name__ == '__main__':
    li = []; rs = {}
    for x in range(int(input('>>>'))):
        li.append(input('>>>>>>'))
    for i, x in enumerate(li):
        r = ''
        for y in x:
            if len(r) == 3: r = r+'-'
            if y == '-':continue
            try:
                y = int(y)
            except ValueError:
                y = ord(y.lower())-97
                if y > 16: y -= 1
                y = y//3 + 2
            r = r + str(y)
        try:
            rs[r] += 1
        except KeyError:
            rs[r] = 1
    is_no_duple = True
    for key in rs:
        if rs[key] != 1: print(key, rs[key]); is_no_duple = False
    if is_no_duple: print("No duplicates")

파이썬 3.5.1

2016/04/17 21:15

Flair Sizz

#파이썬 3.5.1
n = int(input())
phonenums = []
for i in range(n):
    phonenums.append(input())
answer = []
for s in phonenums:
    s = s.replace('-','')
    a = 2
    for i in 'ABCDEFGHIJKLMNOPRSTUVWXY':
        s = s.replace(i,str(a))
        if 'ABCDEFGHIJKLMNOPRSTUVWXY'.index(i) % 3 == 2:
            a += 1
    s = s[:3]+'-'+s[3:]
    answer.append(s)
result = {}
for r in answer:
    result[r] = answer.count(r)
for r in sorted(result):
    if result[r] >= 2:
        print(r,result[r])

2016/04/30 21:46

차우정

Python 3.4.4

alpha_table = {
    'ABC': '2',
    'DEF': '3',
    'GHI': '4',
    'JKL': '5',
    'MNO': '6',
    'PRS': '7',
    'TUV': '8',
    'WXY': '9'
}


def easy_number(number):
    number = number.replace('-', '')
    number_list = list(number)

    data = []
    for n in number_list:
        data.append(n)
        for key, value in alpha_table.items():
            for k in key:
                if n == k:
                    data.pop()
                    data.append(value)

    return '{}-{}'.format(''.join(data[:3]), ''.join(data[3:]))


out = []

data = ['4873279', 'ITS-EASY', '888-4567', '3-10-10-10', '888-GLOP',
        'TUT-GLOP', '967-11-11', '310-GINO', 'F101010', '888-1200',
        '-4-8-7-3-2-7-9-', '487-3279']

for x in range(int(input())):
    # out.append(easy_number(input()))
    out.append(easy_number(data[x]))

out.sort()

while len(out) > 0:
    if out.count(out[0]) == 1:
        del out[0]
        continue
    print('{} {}'.format(out[0], out.count(out[0])))
    [out.remove(out[0]) for x in range(out.count(out[0]))]

2016/05/20 15:09

SanghoSeo

GCC

char**a,**b,d[2];main(j,n,p,i){scanf("%d\n",&n);a=(char**)malloc(4*n);b=(char**)malloc(4*n);for(;++i<n;){b[i]=(char*)malloc(n*99);a[i]=(char*)malloc(n*99);gets(a[i]);*b[i]=0;for(j=-1;p=a[i][++j];p>64&&p<91&&(p<80&&(*d=(p+1)/3+28),p>79&&p<84&&p-81&&(*d=55),p>83&&(*d=p/3+28),strcat(b[i],d)))p>47&&p<58&&(*d=p,strcat(b[i],d));}for(;--i;)for(j=p=0;j<n&&*b[i];j++,p>1&&printf("%c%c%c-%s %d\n",b[i][0],b[i][1],b[i][2],b[i]+3,p,n=0))if(!strcmp(b[i],b[j])){p++;if(i-j)*b[j]=0;}n&&puts("No duplicate");}

2016/06/27 19:36

Lotion

c++ 입니다 좀더 편하게 만들수 있을거 같은데 c++을 지금 아직 배우는 중이라.. 배열을 이용해 만들었습니다.

#include <iostream>
#include <cstring>
#include <windows.h>
using namespace std;

class Phone_Num{
private:
    char**c;
    int count_num;
    bool d;
public:
    Phone_Num(){
        count_num=0;
        d=false;
    }
    ~Phone_Num(){
        for(int i=0;i<count_num;i++)
            delete c[i];
        delete c;
    }
    void Get_Input(int n){
        char ch[20];
        c=new char*[n];
        count_num=n;
        for(int i=0;i<n;i++)
        {
            c[i]=new char[20];
            cin>>ch;
            Change_form(ch,c[i]);
        }
        system("cls");
        Ordering_Ph();
        Check_Duplicate();
    }
    void Change_form(char*ch,char*c){
        char st[8];
        int i=0;
        while(*ch!='\0'||i<8)
        {
            if(*ch!='Q' && *ch!='Z'){
                if(i==3){
                    st[i]='-';
                    i++;
                }
                else{
                    if(*ch>='A'&&*ch<='C')
                        st[i]='2';
                    else if(*ch>='D'&&*ch<='F')
                         st[i]='3';
                    else if(*ch>='G'&&*ch<='I')
                        st[i]='4';
                    else if(*ch>='J'&&*ch<='L')
                        st[i]='5';
                    else if(*ch>='M'&&*ch<='O')
                        st[i]='6';
                    else if(*ch>='P'&&*ch<='S')
                        st[i]='7';
                    else if(*ch>='T'&&*ch<='V')
                        st[i]='8';
                    else if(*ch>='W'&&*ch<='Y')
                        st[i]='9';
                    else if(*ch!='-')
                        st[i]=*ch;
                    else
                        i--;
                    i++;
                    ch++;
                }
            }
            else{
                cout<<"Error"<<endl;
                break;
            }
        }
        if(i>7)
            st[i]='\0';
        strcpy(c,st);
    }

    void Ordering_Ph()
    {
        char tmp[20];
        for(int i=0;i<count_num-1;i++)
        {
            for(int j=i+1;j>0;j--){
                if(c[j-1][0]>=c[j][0]){
                    strcpy(tmp,c[j]);
                    strcpy(c[j],c[j-1]);
                    strcpy(c[j-1],tmp);
                }
            }
        }
    }
    void Check_Duplicate()
    {
        int Count=0;
        for(int i=0;i<count_num;i++)
        {   Count=1;
            if(strcmp(c[i],"0")!=0)
            {
                for(int j=i+1;j<count_num;j++)
                {

                    if(strcmp(c[i],c[j])==0){
                        strcpy(c[j],"0");
                        Count++;
                    }
                }
                if(Count>1){//Print
                    cout<<c[i]<<" "<<Count<<endl;
                    d=true;
                }
            }
        }
       if(d==false)
            cout<<"No Duplicates"<<endl;
    }
    void Get_Array(){
        for(int i=0;i<count_num;i++)
            cout<<c[i]<<" ";
        cout<<endl;
    }
};
int main()
{
    Phone_Num s;
    int n;
    cin>>n;
    s.Get_Input(n);
    return 0;
}

2016/09/18 17:24

leye195

import re
from itertools import groupby

def convert_phone_num(src):
    # 필요없는 문자 제거
    src = re.sub(r'[^0-9a-pr-yA-PR-Y\n]', '', src.strip())
    # 영문을 ASCII로 변환하여 2,3,4,5,6,7,8,9로 Mapping
    src = re.sub(r'([a-zA-Z])'
                 , lambda m:(lambda x:str((x if x < 16 else x - 1) // 3 + 2))(ord(m.group().upper()) - 65)
                 , src)
    p = re.compile(r'^(\d{3})')
    list_ = [p.sub(r'\1-', x) for x in (src.split('\n')[1:])]
    list_.sort()
    for k, g in groupby(list_):
        l = len(list(g))
        print(k, 'No duplicates.' if l == 1 else l)

convert_phone_num('''
12
4873279
ITS-EASY
888-4567
3-10-10-10
888-GLOP
TUT-GLOP
967-11-11
310-GINO
F101010
888-1200
-4-8-7-3-2-7-9-
487-3279
''')

Python 3.5.2에서 작성하였습니다.

2016/12/01 14:21

Yeo HyungGoo

_dict = {'A':'2','B':'2','C':'2',\
         'D':'3','E':'3','F':'3',\
         'G':'4','H':'4','I':'4',\
         'J':'5','K':'5','L':'5',\
         'M':'6','N':'6','O':'6',\
         'P':'7','R':'7','S':'7',\
         'T':'8','U':'8','V':'8',\
         'W':'9','X':'9','Y':'9',\
         }
_list = [input() for x in range(int(input()))]
for x in range(len(_list)):
    _list[x] = _list[x].replace('-','')
    for y in range(len(_list[x])):
        if not _list[x][y].isnumeric():
            _list[x] = _list[x].replace(_list[x][y],_dict[_list[x][y]])
_list.sort()
for call_num in _list:
    count = _list.count(call_num)
    if count > 1:
        print(call_num[:3]+'-'+call_num[3:],count)
        for x in range(count):
            _list.remove(call_num)

#### 2016.12.30 D-419 ####

2016/12/30 23:55

GunBang

#include  <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_COLS 10000

struct Output {
    char* num;
    int count;
}* out;

void main() {
    FILE* f = fopen("input.txt","rt");
    char s[MAX_COLS];

    int size;
    int init = 0;
    int oindex=0;
    while(fgets(s, MAX_COLS, f)) {
        char temp[50]="";
        int index=0;
        if(!init) {
            out = (Output*) malloc (sizeof(Output) * atoi(s));
            size = atoi(s);
            for(int i=0 ;i<=size; i++)
                out[i].num = (char*) malloc (sizeof(char) * 50);
            for(int i=0 ;i<=size; i++)
                out[i].count = 1;
            init = 1;
            continue;
        }
        //printf("%s", s);
        int len = strlen(s);
        s[len]='\0';
        for(int i=0;i<len;i++) {
            if(s[i]=='-') continue;
            else if(s[i]=='A' || s[i]=='B' || s[i]=='C') temp[index] = '2';
            else if(s[i]=='D' || s[i]=='E' || s[i]=='F') temp[index] = '3';
            else if(s[i]=='G' || s[i]=='H' || s[i]=='I') temp[index] = '4';
            else if(s[i]=='J' || s[i]=='K' || s[i]=='L') temp[index] = '5';
            else if(s[i]=='M' || s[i]=='N' || s[i]=='O') temp[index] = '6';
            else if(s[i]=='P' || s[i]=='R' || s[i]=='S') temp[index] = '7';
            else if(s[i]=='T' || s[i]=='U' || s[i]=='V') temp[index] = '8';
            else if(s[i]=='W' || s[i]=='X' || s[i]=='Y') temp[index] = '9';
            else  temp[index] = s[i];
            index++;
        }
        bool insert = true;
        for(int i=0;i<=size; i++) {
            if(!strcmp(temp, out[i].num)) {
                out[i].count++;
                insert = false;
                break;
            }
        }
        if(insert) {
            strcpy(out[oindex].num, temp);
            oindex++;
        }
    }

    for(int i=0;i<=size; i++) 
        if(out[i].count>1)
            printf("%s %d\n", out[i].num, out[i].count);
}

2017/01/25 15:39

코딩초보

def simple(data):
    result=""
    A=["0","1",'ABC2','DEF3','GHI4','JKL5','MNO6','PRS7','TUV8','WXY9']
    data=data.split("-")
    for i in data:
        for k in i:
            for j in range(10):
                if k in A[j]:
                    result+=str(j)
    return result[0:3]+"-"+result[3:]
def numbering(data):
    data=data[1]
    dic={}
    n=0
    for i in data:
        if simple(i) in dic.keys():
            dic[simple(i)]+=1
        else:
            dic[simple(i)]=1
    keys=sorted(list(dic.keys()))
    for i in keys:
        if dic[i]>1:
            print("%s %d" %(i, dic[i]))
            n+=1
        if n==0:
            print("No duplicates")
numbering([12,['4873279','ITS-EASY','888-4567','3-10-10-10','888-GLOP','TUT-GLOP','967-11-11','310-GINO','F101010','888-1200','-4-8-7-3-2-7-9-','487-3279']])

2017/02/19 21:12

김구경

import java.io.File;
import java.io.FileNotFoundException;
import java.text.MessageFormat;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
import java.util.function.Function;
import java.util.stream.Collector;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class PhoneNumber {

    public static final Collector<String, ?, Map<String, Long>> STRING_MAP_COLLECTOR = Collectors.groupingBy(String::new, Collectors.counting());

    static Map<String, Integer> table = new HashMap<>();

    static {
        table.put("A", 2);
        table.put("B", 2);
        table.put("C", 2);

        table.put("D", 3);
        table.put("E", 3);
        table.put("F", 3);

        table.put("G", 4);
        table.put("H", 4);
        table.put("I", 4);

        table.put("J", 5);
        table.put("K", 5);
        table.put("L", 5);

        table.put("M", 6);
        table.put("N", 6);
        table.put("O", 6);

        table.put("P", 7);
        table.put("R", 7);
        table.put("S", 7);

        table.put("T", 8);
        table.put("U", 8);
        table.put("V", 8);

        table.put("W", 9);
        table.put("X", 9);
        table.put("Y", 9);
    }


    public static void main(String[] args) throws FileNotFoundException {
        String path = PhoneNumber.class.getResource("").getPath();
        Scanner sc = new Scanner(new File(path + "PhoneNumber.txt"));
        int n = sc.nextInt();
        String[] numbers = new String[n];
        for (int i = 0; i < n; i++) {
            numbers[i] = sc.next();
        }

        Map<String, Long> map = Stream.of(numbers)
                .map(i -> i.replaceAll("-", ""))
                .map(i -> MessageFormat.format("{0}{1}{2}-{3}{4}{5}{6}", Stream.of(i.split("")).map(getStringStringFunction()).toArray())).collect(STRING_MAP_COLLECTOR);
        System.out.println(map);
    }

    private static Function<String, String> getStringStringFunction() {
        return s -> {
            if (s.matches("[A-Y]")) {
                return String.valueOf(table.get(s));
            }
            return s;
        };
    }
}

2017/04/29 01:08

genius.choi

python 전화번호는 txt 파일에 저장하여 읽임. re 모듈 & collections.Counter 사용

import re
from collections import Counter

#keypad dictionaries
keypad = {'A':'2', 'B':'2', 'C':'2',
          'D':'3', 'E':'3', 'F':'3',
          'G':'4', 'H':'4', 'I':'4',
          'J':'5', 'K':'5', 'L':'5',
          'M':'6', 'N':'6', 'O':'6',
          'P':'7', 'R':'7', 'S':'7',
          'T':'8', 'U':'8', 'V':'8',
          'W':'9', 'X':'9', 'Y':'9'}

#read telephone number list file
f = open('tel_no_list.txt', 'r')
lines = f.readlines()
tel_no = [re.sub(r"[^0-9A-Z]", "", line) for line in lines]

#print original telephone number
print(len(lines))
for num in tel_no:
    print(num)

#replace numeric to alphabet
for i in range(len(tel_no)):
    for j in range(7):
        if bool(re.search('[A-Z]', tel_no[i][j])):
            tel_no[i] = tel_no[i].replace(tel_no[i][j], keypad.get(tel_no[i][j]))
    tel_no[i] = tel_no[i][0:3] + '-' + tel_no[i][3:]

#count same numbers and print    
result = dict(Counter(tel_no))
for t in sorted(result.items(), key=lambda x: (x[1],x[0])):
    if t[1] == 1: print(t[0], "No Duplicate")
    else: print("%s %d" % t)

2017/06/08 03:14

예강효빠

javascript

var standard = function(phoneno) {
    return phoneno.replace(/-/g, "")
                  .replace(/[ABC]/g, "2")
                  .replace(/[DEF]/g, "3")
                  .replace(/[GHI]/g, "4")
                  .replace(/[JKL]/g, "5")
                  .replace(/[MNO]/g, "6")
                  .replace(/[PRS]/g, "7")
                  .replace(/[TUV]/g, "8")
                  .replace(/[WXY]/g, "9")
                  .replace(/(...)(....)/g,"$1-$2");
};

var input =
`12
4873279
ITS-EASY
888-4567
3-10-10-10
888-GLOP
TUT-GLOP
967-11-11
310-GINO
F101010
888-1200
-4-8-7-3-2-7-9-
487-3279`;

var main = function(input) {
    var inputs = input.split("\n").map(v => v.trim());
    var standards = [];
    for (let i = 1; i <= inputs[0]; i++) {
        let s = standard(inputs[i]);
        standards[s] ? standards[s]++ : standards[s] = 1;
    }

    Object.keys(standards)
          .sort()
          .forEach(k => standards[k] > 1 && console.log(`${k} ${standards[k]}`));
};

main(input);

2017/06/19 12:30

funnystyle

// 전화번호 - C#
using System;
using System.Collections.Generic;
namespace Phonecall
{
    class Program
    {
        static string alphabet(string a)
        {
            a = a.Replace("A", "2");
            a = a.Replace("B", "2");
            a = a.Replace("C", "2");
            a = a.Replace("D", "3");
            a = a.Replace("E", "3");
            a = a.Replace("F", "3");
            a = a.Replace("G", "4");
            a = a.Replace("H", "4");
            a = a.Replace("I", "4");
            a = a.Replace("J", "5");
            a = a.Replace("K", "5");
            a = a.Replace("L", "5");
            a = a.Replace("M", "6");
            a = a.Replace("N", "6");
            a = a.Replace("O", "6");
            a = a.Replace("P", "7");
            a = a.Replace("R", "7");
            a = a.Replace("S", "7");
            a = a.Replace("T", "8");
            a = a.Replace("U", "8");
            a = a.Replace("V", "8");
            a = a.Replace("W", "9");
            a = a.Replace("X", "9");
            a = a.Replace("Y", "9");
            a = a.Insert(3, "-");
            return a;
        }
        static void Main(string[] args)
        {
            Console.WriteLine("Ready>>>");
            string[] texts = new string[int.Parse(Console.ReadLine())];
            for (int i = 0; i < texts.Length; i++)
            {
                texts[i] = Console.ReadLine();
                texts[i] = texts[i].Replace("-", "");
            }
            Dictionary<string, int> result = new Dictionary<string, int>();
            for (int i = 0; i < texts.Length; i++)
            {
                texts[i] = alphabet(texts[i]);
                if (result.ContainsKey(texts[i]))
                    result[texts[i]]++;
                else
                    result.Add(texts[i], 1);
            }
            foreach (KeyValuePair<string, int> i in result)
            {
                if (i.Value != 1)
                    Console.WriteLine("{0} {1}", i.Key, i.Value);
            }
        }
    }
}

2017/07/15 01:26

Jeong Hoon Lee

C#

C# 네이밍 규칙은 도저히 못 지키겠음-_-; 답답해서..

리스트를 스캔해서 A, A, B 와 같이 연속될 때 A를 카운트하도록 했습니다.

리스트 마지막 부분 처리를 위해 끝에 dummy를 추가했습니다.

using static System.Console;
using System.Collections.Generic;
using System.Linq;

class ContactList
{
    // 유효하지 않은 입력은 없다고 가정
    public static string standardize(string s)
    {
        string alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        string aton = "22233344455566670778889990";

        s = s.Replace("-", "");
        foreach (char a in alpha)
        {
            s = s.Replace(a, aton[a - 'A']);
        }

        return s.Insert(3, "-");
    }

    static void Main(string[] args)
    {
        string[] data = { "4873279", "ITS-EASY", "888-4567", "3-10-10-10", "888-GLOP", "TUT-GLOP", "967-11-11", "310-GINO", "F101010", "888-1200", "-4-8-7-3-2-7-9-", "487-3279" };
        List<string> contacts = new List<string>();
        foreach (string s in data)
        {
            contacts.Add(standardize(s));
        }

        contacts.Sort();
        contacts.Add("dummy");
        bool nodup = true;
        for (int i = 0; i < contacts.Count - 2; i++)
        {   
            if (contacts[i] == contacts[i+1] && contacts[i] != contacts[i+2])
            {                
                WriteLine("{0} {1}", contacts[i], contacts.Count(x => x == contacts[i]));
                nodup = false;
            }
        }
        if (nodup)
        {
            WriteLine("No duplicates");
        }
    }
}

2017/07/25 23:16

Noname

Python3

문제가 어렵진 않은데 코드를 예쁘게 만들려고 고민을 좀 하게 되네요. 어느 모듈에 reduce가 있었던 거 같은데..

따로 저장하지 않고 집합으로 만든 후 정렬해서 하나하나 카운트했습니다.

def stdform(con):
    aton = "22233344455566670778889990"
    con = con.replace('-', '')
    con = [aton[ord(ch) - ord('A')] if ch.isalpha() else ch for ch in con]
    con.insert(3, '-')
    return ''.join(con)

std = [stdform(con) for con in data.split('\n')[1:]]

nodup = True
for con in sorted(set(std)):
    cnt = std.count(con)
    if cnt >= 2:
        print(con, cnt)
        nodup = False

if nodup:
    print("No duplicates")

2017/07/25 23:59

Noname

import re

arr1_1 = {'A':'2','B':'2','C':'2',
          'D':'3','E':'3','F':'3',
          'G':'4','H':'4','I':'4',
          'J':'5','K':'5','L':'5',
          'M':'6','N':'6','O':'6',
          'P':'7','R':'7','S':'7',
          'T':'8','U':'8','V':'8',
          'W':'9','X':'9','Y':'9'}

def f(phone_lst):
    phone_lst = list(map((lambda x:x.replace('-','')), phone_lst))
    for i1 in range(0, len(phone_lst)):
        for i2 in range(0, len(phone_lst[i1])):
            if re.search('[A-Z]', phone_lst[i1][i2]):
                phone_lst[i1] = phone_lst[i1].replace(phone_lst[i1][i2], arr1_1[phone_lst[i1][i2]])
    phone_lst = {x[:3] + '-' + x[3:]:phone_lst.count(x) for x in phone_lst}
    for k1 in phone_lst.keys():
        print(k1, (lambda x:'No duplicates.' if x == 1 else x)(phone_lst[k1]))

f([
    '4873279',
    'ITS-EASY',
    '888-4567',
    '3-10-10-10',
    '888-GLOP',
    'TUT-GLOP',
    '967-11-11',
    '310-GINO',
    'F101010',
    '888-1200',
    '-4-8-7-3-2-7-9-',
    '487-3279'])

2017/09/01 14:20

piko

def transC(c):
    char = 'ABCDEFGHIJKLMNOPRSTUVWXY1234567890'
    digi = '2223334445556667778889991234567890'
    return '' if c == '-' else digi[char.index(c)]

def transNum(s):
    num = ''
    for c in s:
        num += transC(c)
    return num[:3] + '-' + num[3:]

def makeTelList(inp):
    telList = {}
    for s in inp.split('\n'):
        telNum = transNum(s)
        if telNum in telList:
            telList[telNum] = telList[telNum] + 1
        else:
            telList[telNum] = 1
    return telList


inp = """4873279
ITS-EASY
888-4567
3-10-10-10
888-GLOP
TUT-GLOP
967-11-11
310-GINO
F101010
888-1200
-4-8-7-3-2-7-9-
487-3279"""


tellist = makeTelList(inp)

if max(tellist.values()) == 1:
    print('No duplicates')
else:
    for num in sorted(tellist.keys()):
        if tellist[num] > 1:
            print(num, tellist[num])

2017/09/22 14:35

songci

import string

# create a dictionary
letter = list(string.ascii_lowercase)
letter.remove('q')
letter.remove('z')
d = dict()
rst_d = dict()

cnt = 2
for i in range(len(letter)):
    d[letter[i]] = cnt
    if (i+1) % 3 == 0:
        cnt += 1

def store_in_dict(s):
    s = list(s)
    s.insert(3, '-')
    s = ''.join(s)
    rst_d[s] = rst_d.get(s, 0) + 1

def get_rid_of_hypen(s):
    s = ''.join(s.split('-')).lower()
    rst = ''
    for letter in s:
        rst += str(d.get(letter, letter))
    store_in_dict(rst)

get_rid_of_hypen('4873279')
get_rid_of_hypen('ITS-EASY')
get_rid_of_hypen('888-4567')
get_rid_of_hypen('3-10-10-10')
get_rid_of_hypen('888-GLOP')
get_rid_of_hypen('TUT-GLOP')
get_rid_of_hypen('967-11-11')
get_rid_of_hypen('310-GINO')
get_rid_of_hypen('F101010')
get_rid_of_hypen('888-1200')
get_rid_of_hypen('-4-8-7-3-2-7-9-')
get_rid_of_hypen('487-3279')


# printing
flag = False
for i in sorted(rst_d.keys()):
    if rst_d[i] > 1:
        print(i, rst_d[i])
        flag = True
if not flag:
    print('no dups')

2017/11/29 17:37

Sung Kim

def trans(n):
    A={
            '2':'ABC',
            '3':'DEF',
            '4':'GHI',
            '5':'JKL',
            '6':'MNO',
            '7':'PRS',
            '8':'TUV',
            '9':'WXY'
            }
    tmp=n.replace('-', '')
    for i in A.keys():
        for j in tmp:
            if j in A[i]: tmp=tmp.replace(j, i)
    return(tmp[:3]+'-'+tmp[3:])

nums=[
        12
        ,'4873279'
        ,'ITS-EASY'
        ,'888-4567'
        ,'3-10-10-10'
        ,'888-GLOP'
        ,'TUT-GLOP'
        ,'967-11-11'
        ,'310-GINO'
        ,'F101010'
        ,'888-1200'
        ,'-4-8-7-3-2-7-9-'
        ,'487-3279']
nums.pop(0)

result=[]
for i in nums:
    result.append(trans(i))
for i in sorted(list(set(result))):
    if result.count(i)!=1:
        print('{} {}'.format(i, result.count(i)))

2017/12/15 05:09

빗나감

파이썬 3.6

def inputdata(datalist):
    s = ''
    try:
        data = int(input(''))
        for i in range(data):
            s = input('')
            if s == '':
                return
            else:
                datalist.append(s)
    except ValueError:
        return

def changestr(data):
    data = list(data)
    newdata = []
    for i in data:
        if i.isdigit():
            newdata.append(i)
        elif i == '-':
            pass
        elif i in 'ABC':
            newdata.append('2')
        elif i in 'DEF':
            newdata.append('3')
        elif i in 'GHI':
            newdata.append('4')
        elif i in 'JKL':
            newdata.append('5')
        elif i in 'MNO':
            newdata.append('6')
        elif i in 'PRS':
            newdata.append('7')
        elif i in 'TUV':
            newdata.append('8')
        elif i in 'WXY':
            newdata.append('9')
    return ''.join(newdata)

def main(datalist):
    changelist = []
    sortlist = []
    stdnum =''
    for data in datalist:
        changelist.append(changestr(data))
    changelistset = set(changelist)
    sortlist =sorted(list(changelistset))
    for std in sortlist:
        stdnum = std[:3]+'-'+std[3:]
        if changelist.count(std) == 1:
            print(stdnum,' ',"No duplicates.")
        else:
            print(stdnum,' ',changelist.count(std) )

if __name__ == "__main__":
    datalist = []
    inputdata(datalist)
    print("\n")
    main(datalist)
  • 결과값
12
4873279
ITS-EASY
888-4567
3-10-10-10
888-GLOP
TUT-GLOP
967-11-11
310-GINO
F101010
888-1200
-4-8-7-3-2-7-9-
487-3279


310-1010   2
310-4466   No duplicates.
487-3279   4
888-1200   No duplicates.
888-4567   3
967-1111   No duplicates.

2018/01/09 15:50

justbegin

# 파이썬

input_sample = """12
4873279
ITS-EASY
888-4567
3-10-10-10
888-GLOP
TUT-GLOP
967-11-11
310-GINO
F101010
888-1200
-4-8-7-3-2-7-9-
487-3279"""


def opn(s):
    s = s.split("\n")
    sl = dict()
    for t in s[1:]:
        standard = ""
        for u in t:
            if u in "ABC": standard += "2"
            elif u in "DEF": standard += "3"
            elif u in "GHI": standard += "4"
            elif u in "JKL": standard += "5"
            elif u in "MNO": standard += "6"
            elif u in "PRS": standard += "7"
            elif u in "TUV": standard += "8"
            elif u in "WXY": standard += "9"
            elif u in "1234567890": standard += u
        if standard not in sl: sl[standard] = 1
        else: sl[standard] += 1
    overlap = []
    for u in sl.keys():
        if sl[u] > 1: overlap.append(int(u))
    overlap.sort()
    for v in overlap:
        v = str(v)
        print(v[0:3]+"-"+v[3:], sl[v])


opn(input_sample)

2018/02/08 00:13

olclocr

def standard(n):
    a = ''
    for i in range(len(n)):
        if n[i] in '0123456789':
            a += n[i]
        elif n[i] in 'ABC':
            a += '2'
        elif n[i] in 'DEF':
            a += '3'
        elif n[i] in 'GHI':
            a += '4'
        elif n[i] in 'JKL':
            a += '5'
        elif n[i] in 'MNO':
            a += '6'
        elif n[i] in 'PRS':
            a += '7'
        elif n[i] in 'TUV':
            a += '8'
        elif n[i] in 'WXY':
            a += '9'
    a = a[:3]+'-'+a[3:]
    return a


b = int(input())
c = list()
while 1:
    c.append(input())
    if len(c) == b:
        break
d = list(map(standard, c))
d.sort()
e = list(set(d))
e.sort()
f = list()
if d == e:
    print("No duplicate")
else:
    for i in e:
        if d.count(i) == 1:
            pass
        else:
            f.append((i, d.count(i)))
print(f)

2018/02/11 21:47

김동하

def alphabet_to_num(alphabet):
    if alphabet=='A' or alphabet=='B' or alphabet=='C':
        return '2'
    elif alphabet=='D' or alphabet=='E' or alphabet=='F':
        return '3'
    elif alphabet=='G' or alphabet=='H' or alphabet=='I':
        return '4'
    elif alphabet=='J' or alphabet=='K' or alphabet=='L':
        return '5'
    elif alphabet=='M' or alphabet=='N' or alphabet=='O':
        return '6'
    elif alphabet=='P' or alphabet=='R' or alphabet=='S':
        return '7'
    elif alphabet=='T' or alphabet=='U' or alphabet=='V':
        return '8'
    elif alphabet=='W' or alphabet=='X' or alphabet=='Y':
        return '9'

def solve(phone_num):           #전화번호를 7자리 이어진 숫자로 바꾸는 함수
    phone_num=phone_num.replace('-','')
    for_change=[]
    for string in phone_num:
        if string.isalpha()==True:
            for_change.append(string)
    for alphabet in for_change:
        phone_num=phone_num.replace(alphabet,alphabet_to_num(alphabet))
    return phone_num

N=int(input("전화번호부 갯수를 입력하세요: "))
if N>1000:
    N=int(input("다시 입력하세요: "))
phone_book_list=[]
for line in range(N):
    phone_book_list.append(input("전화번호를 입력하세요: "))

new_phone_book_list=[]

for phone_number in phone_book_list:
    new_phone_book_list.append(solve(phone_number))

new_phone_book_list.sort()

ans_dic={}
for phone_number2 in new_phone_book_list:
    if phone_number2 in ans_dic.keys():
        continue
    counter=new_phone_book_list.count(phone_number2)
    if counter!=1:
        phone_number2=phone_number2[:3]+'-'+phone_number2[3:]
        ans_dic[phone_number2]=counter

for ans in ans_dic.items():
    print(ans)



2018/02/19 06:07

D B

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Scanner;
import java.util.Set;
import java.util.regex.Pattern;

public class PhoneNumber {

    static Map<String, Integer> result1 = new HashMap<>();

    public static void execute(String phoneNumber){
        String[] num = phoneNumber.split(""); //한글자씩 분해
        Pattern p = Pattern.compile("[0-9]");

        for(int i=0; i<num.length; i++){
            if(!num[i].equals("-")){ //하이픈이 아니면 숫자로 변환

                if(!p.matcher(num[i]).find()){ // 숫자가 아니면
                    if(num[i].equals("A") || num[i].equals("B") || num[i].equals("C")){
                        num[i] = "2";
                    }else if(num[i].equals("D") || num[i].equals("E") || num[i].equals("F")){
                        num[i] = "3";
                    }else if(num[i].equals("G") || num[i].equals("H") || num[i].equals("I")){
                        num[i] = "4";
                    }else if(num[i].equals("J") || num[i].equals("K") || num[i].equals("L")){
                        num[i] = "5";
                    }else if(num[i].equals("M") || num[i].equals("N") || num[i].equals("O")){
                        num[i] = "6";
                    }else if(num[i].equals("P") || num[i].equals("R") || num[i].equals("S")){
                        num[i] = "7";
                    }else if(num[i].equals("T") || num[i].equals("U") || num[i].equals("V")){
                        num[i] = "8";
                    }else if(num[i].equals("W") || num[i].equals("X") || num[i].equals("Y")){
                        num[i] = "9";
                    }

                }else{ // 숫자이면

                }
            }else{ // 하이픈이면

            }
        }
        String phone = "";
        for(int i = 0; i <num.length; i++){
            if(!num[i].equals("-")){
                phone += num[i];
            }
            if(phone.length() == 3){ // 4번째 인덱스에 하이픈 넣어주기
                phone += "-";

            }

        }

        if(!result1.containsKey(phone)){ // 같은 키가 없다면
            result1.put(phone, 1);
        }else{ // 같은키가 있다면
            result1.replace(phone, result1.get(phone)+1);
        }

    }


    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Scanner sc = new Scanner(System.in);
        int testCase = Integer.parseInt(sc.nextLine().trim());

        for(int i=0; i<testCase; i++){
            execute(sc.nextLine());
        }
        sc.close();
        Set<Entry<String, Integer>> s = result1.entrySet();

        if(s.size() == testCase){
            System.out.println("No duplicates.");
        }else{
            Iterator<Entry<String, Integer>> iter = s.iterator();

            while(iter.hasNext()){
                Entry<String, Integer> e = iter.next();
                int count = (int) e.getValue();
                if(count >1){
                    System.out.println(e.getKey() + " " + e.getValue());
                }
            }
        }

    }

}

2018/04/18 23:36

김태훈

Swift입니다.

import Foundation

var numberMap = [String:Int]()
let map = ["A":"2","B":"2","C":"2","D":"3","E":"3","F":"3",
           "G":"4","H":"4","I":"4","J":"5","K":"5","L":"5",
           "M":"6","N":"6","O":"6","P":"7","R":"7","S":"7",
           "T":"8","U":"8","V":"8","W":"9","X":"9","Y":"9",
           "1":"1","2":"2","3":"3","4":"4","5":"5","6":"6",
           "7":"7","8":"8","9":"9","0":"0"]

func translate(_ numberString: String) -> String {
    var number = numberString.uppercased().reduce("", {$1 == "-" ? $0 : $0 + map[String($1)]!})
    number.insert("-", at:number.index(number.startIndex, offsetBy: 3))
    return number
}

func checkPhoneNumbers() {
    let inputCount = Int(readLine()!)!

    for _ in 0..<inputCount {
        let numberString = readLine()!
        let translated = translate(numberString)
        if let numberCount = numberMap[translated] {
            numberMap[translated] = numberCount + 1
        } else {
            numberMap[translated] = 1
        }
    }

    print("\n-------\n")
    for (number, count) in numberMap.sorted(by: {$0.0 < $1.0}) {
        if count == 1 {
            print("\(number) : No duplicates")
        } else {
            print("\(number) : \(count)")
        }        
    }
}

checkPhoneNumbers()

결과는...

12
4873279
ITS-EASY
888-4567
3-10-10-10
888-GLOP
TUT-GLOP
967-11-11
310-GINO
F101010
888-1200
-4-8-7-3-2-7-9-
487-3279

-------

310-1010 : 2
310-4466 : No duplicates
487-3279 : 4
888-1200 : No duplicates
888-4567 : 3
967-1111 : No duplicates

2018/04/20 05:50

졸린하마

파이썬입니다.

import re
n = int(input("총 전화번호의 수를 입력하세요 : "))
x = ['000-0000']*n
dic = {}
for i in range(65, 81): dic[i] = str((i+1)//3 - 20)
for i in range(82, 90): dic[i] = str(i//3 - 20)
for i in range(n):
    x[i] = ''.join(re.findall('[0-9A-PR-Y]*', input("%d번째 전화번호 : " % (i+1)))).translate(dic)
    x[i] = x[i][:3] + '-' + x[i][3:]
    if len(x[i]) != 8: x[i] = 'error'
y = sorted(list(set(x) - {'error'}))
z = [x.count(t) for t in y]
for a, b in zip(y, z): print(a, b if b != 1 else 'No duplicates')
print('error :', x.count('error'))

2018/05/09 18:06

Hyuk

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Scanner;
import java.util.Set;
import java.util.regex.Pattern;

public class PhoneNumber {

    static Map<String, Integer> result1 = new HashMap<>();

    public static void execute(String phoneNumber){
        String[] num = phoneNumber.split(""); //한글자씩 분해
        Pattern p = Pattern.compile("[0-9]");

        for(int i=0; i<num.length; i++){
            if(!num[i].equals("-")){ //하이픈이 아니면 숫자로 변환

                if(!p.matcher(num[i]).find()){ // 숫자가 아니면
                    if(num[i].equals("A") || num[i].equals("B") || num[i].equals("C")){
                        num[i] = "2";
                    }else if(num[i].equals("D") || num[i].equals("E") || num[i].equals("F")){
                        num[i] = "3";
                    }else if(num[i].equals("G") || num[i].equals("H") || num[i].equals("I")){
                        num[i] = "4";
                    }else if(num[i].equals("J") || num[i].equals("K") || num[i].equals("L")){
                        num[i] = "5";
                    }else if(num[i].equals("M") || num[i].equals("N") || num[i].equals("O")){
                        num[i] = "6";
                    }else if(num[i].equals("P") || num[i].equals("R") || num[i].equals("S")){
                        num[i] = "7";
                    }else if(num[i].equals("T") || num[i].equals("U") || num[i].equals("V")){
                        num[i] = "8";
                    }else if(num[i].equals("W") || num[i].equals("X") || num[i].equals("Y")){
                        num[i] = "9";
                    }

                }else{ // 숫자이면

                }
            }else{ // 하이픈이면

            }
        }
        String phone = "";
        for(int i = 0; i <num.length; i++){
            if(!num[i].equals("-")){
                phone += num[i];
            }
            if(phone.length() == 3){ // 4번째 인덱스에 하이픈 넣어주기
                phone += "-";

            }

        }

        if(!result1.containsKey(phone)){ // 같은 키가 없다면
            result1.put(phone, 1);
        }else{ // 같은키가 있다면
            result1.replace(phone, result1.get(phone)+1);
        }

    }


    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Scanner sc = new Scanner(System.in);
        int testCase = Integer.parseInt(sc.nextLine().trim());

        for(int i=0; i<testCase; i++){
            execute(sc.nextLine());
        }
        sc.close();
        Set<Entry<String, Integer>> s = result1.entrySet();

        if(s.size() == testCase){
            System.out.println("No duplicates.");
        }else{
            Iterator<Entry<String, Integer>> iter = s.iterator();

            while(iter.hasNext()){
                Entry<String, Integer> e = iter.next();
                int count = (int) e.getValue();
                if(count >1){
                    System.out.println(e.getKey() + " " + e.getValue());
                }
            }
        }

    }

}

2018/05/21 17:07

배혁남

import java.util.Arrays;

public class S4873229 {
    public static void main(String[] args) {
        String[] sample = { "4873279", "ITS-EASY", "888-4567", "3-10-10-10", "888-GLOP", "TUT-GLOP", "967-11-11",
                "310-GINO", "F101010", "888-1200", "-4-8-7-3-2-7-9-", "487-3279" };
        String strNum = "ABCDEFGHIJKLMNOPRSTUVWXY";
        for (int i = 0; i < sample.length; i++) {
            for (int j = 0; j < strNum.length(); j++)
                if (sample[i].contains(strNum.substring(j, j + 1)))
                    sample[i] = sample[i].replaceAll(strNum.substring(j, j + 1), j / 3 + 2 + "");
            sample[i] = sample[i].replaceAll("[^0-9]", "");
        }
        for (int i = 0; i < sample.length; i++) {
            int count = 0;
            for (int j = i; j < sample.length; j++)
                if (sample[i].equals(sample[j])) {
                    count++;
                    if (i != j)
                        sample[j] = "";
                }
            if (count > 1)
                sample[i] = sample[i] + " " + count;
        }
        Arrays.sort(sample);
        for (int i = 0; i < sample.length; i++)
            if (sample[i].length() > 8)
                System.out.println(sample[i]);
    }
}

2018/05/31 16:19

김지훈

Python

import operator
match = ["ABC","DEF","GHI","JKL","MNO","PRS","TUV","XWY"]
n = int(input())
phone = dict()
for _ in range(n):
    num = input().strip()
    num = num.replace("-","")
    tmp_num = ""
    for c in num:
        for i, cap in enumerate(match):
            if c in cap:
                tmp_num += str(i+2)
                break
        else:
            tmp_num += c
    tmp_num = tmp_num[:3]+"-"+tmp_num[3:]
    if tmp_num in phone:
        phone[tmp_num] += 1
    else:
        phone[tmp_num] = 1
phone = sorted(phone.items(), key=operator.itemgetter(0))
chk = False
for key, value in phone:
    if value > 1:
        print(key, value)
        chk = True
if chk is False:
    print("No duplicates")

2018/06/07 14:35

Taesoo Kim

mydic={'A':2,'B':2,'C':2,'D':3,'E':3,'F':3,'G':4,'H':4,'I':4,'J':5,'K':5,'L':5,'M':6,'N':6,'O':6,'P':7,'R':7,'S':7,'T':8,'U':8,'V':8,'W':9,'X':9,'Y':9}
n=int(input())

numberlist=[ input() for t in range(n)]
resultlist=[]
printlist=[]
for numberli in numberlist:
    numli=list(numberli)
    for num in numli:
        if num=='-':
            numli.remove(num)
    tel=''
    for li in numli:
        if 'A'<=li<='P' or 'R'<=li<='Y':
            tel+=str(mydic[li])
        else:
            tel+=li
    resultlist.append(tel)

for resultli1 in resultlist:
    count=0
    for resultli2 in resultlist:
        if resultli1==resultli2:
            count+=1
    if count>=2:
        a=resultli1
        printlist.append([int(a),count])
        while count:
            resultlist.remove(a)
            count-=1
if len(printlist)==0:
    print('No duplicates')
else:
    printlist.sort()
    for printli in printlist:
        a=str(printli[0])
        print(a[:3]+'-'+a[3:],printli[1])

2018/06/07 22:30

박종범

import re
def call_number(n):
    cn = 'ABCDEFGHIJKLMNOPRSTUVWXY'
    n = n.replace('-','')
    for i in range(2, 10): n = re.sub('['+cn[i*3-6:i*3-3]+']',str(i),n)
    return n[:3]+'-'+n[3:]

numlist = ['4873279', 'ITS-EASY', '888-4567', '3-10-10-10', '888-GLOP', 'TUT-GLOP', '967-11-11', '310-GINO', 'F101010', '888-1200', '-4-8-7-3-2-7-9-', '487-3279']
for i in range(len(numlist)): numlist[i] = call_number(numlist[i])
ans = {}
for i in numlist:
    if numlist.count(i) > 1: ans[i] = numlist.count(i)

if ans == {}: print('No duplicates.')
else:
    for i in sorted(ans.keys()): print(f'{i} {ans[i]}')
310-1010 2
487-3279 4
888-4567 3

2018/07/14 23:56

Creator

// 487-3229
package com.company;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        String[] strArr = new String[n];
        for(int i = 0; i < n; i++)
        {
            strArr[i] = sc.next();
        }
        get(strArr);
    }

    public static void get(String[] strArr)
    {
        int dupcnt = 1;
        boolean dup = false;
        ArrayList<String> newArr = new ArrayList<>();
        for(int i = 0; i < strArr.length; i++)
        {
            newArr.add(getNum(strArr[i])); // 전화번호 형태로 변환
        }
        Collections.sort(newArr); // 정렬
        for(int k = 0; k < newArr.size() - 1; k++) // 중복확인
        {
            if(newArr.get(k).equals(newArr.get(k+1))) // 다음원소와 같으면 중복카운트증가 및 중복true
            {
                dup = true;
                dupcnt++;
                if(k == newArr.size() - 2)
                    System.out.printf("%s %d\n", newArr.get(k), dupcnt); // 출력
            }
            if((dupcnt > 1) && !newArr.get(k).equals(newArr.get(k+1))) // 중복카운트가 > 1 이고 다음원소랑 다르면
            {
                System.out.printf("%s %d\n", newArr.get(k), dupcnt); // 출력
                dupcnt = 1; // 중복카운트 초기화
            }
        }
        if(dup == false)
            System.out.println("NO duplicates");
    }

    public static String getNum(String str) // 전화번호 형태로 변환
    {
        StringBuffer newStr = new StringBuffer();
        int len = str.length();
        for(int i = 0; i < len; i++)
        {
            switch(str.charAt(i))
            {
                case 'A':
                case 'B':
                case 'C':
                    newStr.append('2');
                    break;
                case 'D':
                case 'E':
                case 'F':
                    newStr.append('3');
                    break;
                case 'G':
                case 'H':
                case 'I':
                    newStr.append('4');
                    break;
                case 'J':
                case 'K':
                case 'L':
                    newStr.append('5');
                    break;
                case 'M':
                case 'N':
                case 'O':
                    newStr.append('6');
                    break;
                case 'P':
                case 'R':
                case 'S':
                    newStr.append('7');
                    break;
                case 'T':
                case 'U':
                case 'V':
                    newStr.append('8');
                    break;
                case 'W':
                case 'X':
                case 'Y':
                    newStr.append('9');
                    break;
                case '-':
                    break;
                default:
                    newStr.append(str.charAt(i)); // 숫자
            }
        }
        newStr.insert(3, '-');
        return String.valueOf(newStr);
    }
}

2018/07/24 13:03

이동수

C#

using System;
using System.Linq;
using System.Text;
using System.IO;

namespace CD054
{

    class Program
    {
        static void Main()
        {
            // read input & convert phone numbers
            string path = @"C:\Temp\PhoneNumbers.txt";
            StreamReader f = new StreamReader(path);
            int numLines = int.Parse(f.ReadLine());
            string[] input = new string[numLines];
            for (int line = 0; line < numLines; line++)
            {
                input[line] = (new PhoneNumber(f.ReadLine())).CnvNumber;
            }
            f.Close();
            // 입력 내용을 번호, 반복회수로 사전타입에 저장
            var result = input.OrderBy(e => e)
                .GroupBy(e => e).ToDictionary(e => e.Key, e => e.Count());
            bool hasDuplicates = false; // 반복 발생 여부
            foreach (var e in result)
            {
                if (e.Value > 1)
                {
                    Console.WriteLine($"{e.Key} {e.Value}");
                    hasDuplicates = true;
                }
            }
            if (!hasDuplicates) { Console.WriteLine("No duplicates."); }
        }
    }

    class PhoneNumber
    {
        private enum PL { ABC = 2, DEF, GHI, JKL, MNO, PRS, TUV, WXY };

        // 생성자
        public PhoneNumber(string aString) => CnvNumber = StringToNumber(aString);

        public string CnvNumber { get; } = string.Empty; // 변환된 전화번호

        // 키패드 문자가 포함된 문자열을 숫자로 구성된 전화번호 형식으로 변환
        private static string StringToNumber(string aString)
        {
            StringBuilder sb = new StringBuilder();
            foreach (char c in aString)
            {
                if (!Char.IsLetterOrDigit(c)) continue; // 숫자 또는 문자가 아닌 경우 제외
                if (Char.IsLetter(c)) // 문자일 경우
                {
                    foreach (var key in Enum.GetNames(typeof(PL)))
                    {
                        if (key.Contains(c))
                        {
                            sb.Append((int)Enum.Parse(typeof(PL), key)); // 해당 숫자로 변환
                            break;
                        }
                    }
                }
                else { sb.Append(c); } // 숫자일 경우
            }
            string result = sb.ToString();
            return $"{result.Substring(0, 3)}-{result.Substring(3)}";
        }
    }
}

2018/09/17 17:44

mohenjo

def phonenum(n):

    pnums = []

    for x in range(n):
        pnums.append(list(x for x in input() if x != '-'))

    for pn in pnums:
        for x in range(len(pn)):
            if not pn[x].isdigit():
                pn.insert(x,str((ord(pn[x])+(1,0)[ord(pn[x]) > 80])//3-20))
                del pn[x+1]

        pn.insert(3,'-')

    pnums = list(''.join(pn) for pn in pnums)
    for x in set(list(x+str(pnums.count(x)) for x in pnums if pnums.count(x) > 1)):
        print(''.join(x[:-1]),x[-1])

    if len(pnums) != set(pnums):
        print('No duplicates')

2019/01/28 11:29

김영성

x = int(input())
xtemp = []
for i in range(x):
    a = input()
    xtemp.append(a)

table = str.maketrans('ABCDEFGHIJKLMNOPRSTUVWXY', '222333444555666777888999')
tempnumlist = []
for i in xtemp:
    numtemp = i.translate(table)
    tempnumlist.append(numtemp)

numlist = []
for i in tempnumlist:
    i = i.replace('-','')
    numlist.append(i[0:3] + '-' + i[3:7])

setnumlist = set(numlist)

result = []
for i in setnumlist:
    count = 0
    for j in numlist:
        if i == j:
            count += 1
    if count > 1:
        result.append('{} {}'.format(i, count))
result.sort()

for i in result:
    print(i)

2019/01/29 14:44

D.H.

sample = '''12
4873279
ITS-EASY
888-4567
3-10-10-10
888-GLOP
TUT-GLOP
967-11-11
310-GINO
F101010
888-1200
-4-8-7-3-2-7-9-
487-3279
'''

mod = ''
modCnt = 0
outputData = []

for l in sample :
    if l == '-' :
        continue
    elif l == "\n" :
        outputData.append(mod)
        mod = ''
        modCnt = 0
    else :
        if modCnt == 3 :
            mod += '-'
        if l == 'A' or l == 'B' or l == 'C' :
            mod += '2'
        elif l == 'D' or l == 'E' or l == 'F' :
            mod += '3'
        elif l == 'G' or l == 'H' or l == 'I' :
            mod += '4'
        elif l == 'J' or l == 'K' or l == 'L' :
            mod += '5'
        elif l == 'M' or l == 'N' or l == 'O' :
            mod += '6'
        elif l == 'P' or l == 'R' or l == 'S' :
            mod += '7'
        elif l == 'T' or l == 'U' or l == 'V' :
            mod += '8'
        elif l == 'W' or l == 'X' or l == 'Y' :
            mod += '9'
        else :
            mod += l
        modCnt += 1
outputData.append(mod)

output = set(outputData)
for i in output :
    outputCnt = outputData.count(i)
    if outputCnt > 1 :
        print(i, outputCnt)
        Duplicates = True
if not Duplicates :
    print("No duplicates.")

2019/02/21 23:36

좋은나쎔

f = open('data1.txt', 'r')
phone = f.read().splitlines()
f.close()

phonelist = []
for list in phone:
    phonelist.append(list.replace('-', ''))
phoneNumber=[]
checkDict={}

for data in phonelist:
    if len(data) == 7:
        if data.isdigit() is False:
            for i, c in enumerate(data):
                if c in ['A','B','C']:
                    data=data.replace(c,'2')
                elif c in ['D','E','F']:
                    data=data.replace(c,'3')
                elif c in ['G','H','I']:
                    data=data.replace(c,'4')
                elif c in ['J','K','L']:
                    data=data.replace(c,'5')
                elif c in ['M','N','O']:
                    data=data.replace(c,'6')
                elif c in ['P','R','S']:
                    data=data.replace(c,'7')
                elif c in ['T','U','V']:
                    data=data.replace(c,'8')
                elif c in ['W','X','Y']:
                    data=data.replace(c,'9')
        phoneNumber.append(data[0:3]+'-'+data[3:])

for key in phoneNumber:
    if key in checkDict.keys():
        checkDict[key] += 1
    else:
        checkDict[key] = 1

resultDict={}
for key, val in checkDict.items():
    if val > 1:
        resultDict[key] = val

result = sorted(resultDict.items())

for i in result:
    print(i[0],i[1])

2019/04/16 15:37

Chang Hwan Kim

정말 무식하네요.. ㅠㅠ - Chang Hwan Kim, 2019/04/16 15:38
test_num=int(input());testL=[]

for i in range(test_num):
    s=input();s=s.replace('-','',s.count('-'))

    ss=''
    for i in s:
        if ord('0')<=ord(i)<=ord('9'):
            ss+=i
        else:
            if i=='A' or i=='B' or i=='C':
                ss+='2'
            elif i=='D' or i=='E' or i=='F':
                ss+='3'
            elif i=='G' or i=='H' or i=='I':
                ss+='4'
            elif i=='J' or i=='K' or i=='L':
                ss+='5'
            elif i=='M' or i=='N' or i=='O':
                ss+='6'
            elif i=='P' or i=='R' or i=='S':
                ss+='7'
            elif i=='T' or i=='U' or i=='V':
                ss+='8'
            elif i=='W' or i=='X' or i=='Y':
                ss+='9'

    testL.append(ss)

ansD={testL[i]:0 for i in range(len(testL))}

#print('')   보기 좋아보려고 추가하여 보았읍니다.

ddl=list(ansD.keys())
for i in range(len(ddl)):
    ansD[ddl[i]]+=testL.count(ddl[i])

for i in range(len(ansD)):
    if ansD[ddl[i]]==1:
        continue
    else:
        print(ddl[i][:3]+'-'+ddl[i][3:],ansD[ddl[i]])

2019/05/04 17:59

암살자까마귀

alps = 'ABCDEFGHIJKLMNOPRSTUVWXY'
nums = '222333444555666777888999'
def alp_to_num(x):
    if x.isdigit():
        return x
    else:
        return nums[alps.index(x)]

def to_numbers(s):
    L = list(s.replace('-',''))
    L = list(map(alp_to_num, L))
    L.insert(3, '-')
    return ''.join(L)


numbers = []
n = int(input())
for i in range(n):
    numbers.append(input())

numbers = list(map(to_numbers, numbers))
S = list(set(numbers))

for s in S:
    if numbers.count(s) > 1:
        print(s, numbers.count(s))

2019/05/21 19:20

messi

num_of_nums = int(input("Enter the amount of numbers : "))

def converter(string):
    num_dict = {'A' : 2, 'B' : 2, 'C' : 2, 'D' : 3, 'E' : 3, 'F' : 3,
'G':4, 'H':4, 'I':4, 'J':5, 'K' : 5, 'L':5,
'M':6, 'N':6, 'O':6, 'P':7, 'R':7, 'S': 7,
'T':8, 'U': 8, 'V':8, 'W' :9, 'X': 9, 'Y':9 }
    converted_string = ""
    for let_or_num in string:
        if len(converted_string)==3:
            converted_string+='-'
        if let_or_num == '-':
            converted_string+=""
        elif let_or_num in num_dict:
            converted_string+=str(num_dict[let_or_num])
        else:
            converted_string+=let_or_num
    return converted_string

num_list = []
counter_dict = {}
for x in range(num_of_nums):
    number = input("Enter number or letters : ")
    converted_number = converter(number)
    num_list.append(converted_number)
num_list.sort()
for num in num_list:
    if num not in counter_dict:
        counter_dict[num] = 1
    else:
        counter_dict[num]+=1

duplicate_counter =0
for x in counter_dict:
    if counter_dict[x]>=2:
        duplicate_counter+=1
        print(x,end=' ')
        print(counter_dict[x])
if duplicate_counter ==0:
    print("No duplicates")

2019/05/21 20:30

박범수

List = {"A":"2", "B":"2", "C":"2","D":"3", "E":"3", "F":"3","G":"4", "H":"4", "I":"4","J":"5", "K":"5", "L":"5","M":"6", "N":"6", "O":"6","P":"7", "R":"7", "S":"7","T":"8", "U":"8","V":"8","W":"9", "X":"9", "Y":"9"}
Phone = ["4873279","ITS-EASY","888-4567","3-10-10-10","888-GLOP","TUT-GLOP","967-11-11","310-GINO","F101010","888-1200","-4-8-7-3-2-7-9-","487-3279"]

List_Phone = []
Mult_Phone = []

for i in range(len(Phone)) :
    Str_Phone =""
    for j in range(len(Phone[i])):
        if  48<= ord(Phone[i][j]) <=57 :
            Str_Phone += Phone[i][j]
        elif  65<= ord(Phone[i][j]) <=90 :
            Str_Phone += List.get(Phone[i][j])
    Str_Phone = Str_Phone[0:3] + "-"+Str_Phone[3:7]
    List_Phone.append(Str_Phone)

cnt=0
for k in List_Phone:    
    if List_Phone.count(k) >=2 :
        Mult_Phone.append(k)
Mult_Phone =list(set(Mult_Phone))

for num in Mult_Phone:
    print("{}, {}".format(num,List_Phone.count(num)))

2019/10/31 23:58

semipooh

import java.util.*;

public class 미국워털루대학icpc문제 {

    public static void main(String[] args) {

        Scanner scan = new Scanner(System.in);
        int n = scan.nextInt();
        Scanner scan2 = new Scanner(System.in);
        ArrayList<String> list = new ArrayList<String>();
        for(int i=0; i<n; i++) {
            list.add(scan2.nextLine());
        }
        for(int j =0; j<n; j++) {
            StringBuffer sb = new StringBuffer();
            String[] line =  list.get(j).split("");
            for(int k=0; k<line.length; k++) {
                if(line[k].equals("A")||line[k].equals("B")||line[k].equals("C")) {
                    line[k] = "2";
                }
                else if(line[k].equals("D")||line[k].equals("E")||line[k].equals("F")) {
                    line[k]="3";
                }
                else if(line[k].equals("G")||line[k].equals("H")||line[k].equals("I")) {
                    line[k]="4";
                }
                else if(line[k].equals("J")||line[k].equals("K")||line[k].equals("L")) {
                    line[k]="5";
                }
                else if(line[k].equals("M")||line[k].equals("N")||line[k].equals("O")) {
                    line[k]="6";
                }
                else if(line[k].equals("P")||line[k].equals("R")||line[k].equals("S")) {
                    line[k]="7";
                }
                else if(line[k].equals("T")||line[k].equals("U")||line[k].equals("V")) {
                    line[k]="8";
                }
                else if(line[k].equals("W")||line[k].equals("X")||line[k].equals("Y")) {
                    line[k]="9";
                }
                else if(line[k].equals("-")) {
                    line[k]="";
                }
            }
            sb.append(String.join("", line));
            sb.insert(3, "-");
            String s = sb.toString();
            list.set(j, s);
            sb = null;
        }
        ArrayList<String> list2 = new ArrayList<String>();
        String[] liststr = list.toArray(new String[list.size()]);
        Arrays.sort(liststr);
        int count = 0;
        for(int l=0; l<liststr.length; l++) {
            count = 1;
            for(int u=l+1; u<liststr.length; u++) {
                if(!liststr[l].equals("")&&liststr[l].equals(liststr[u])) {
                count++;
                liststr[u] = liststr[u].replace(liststr[u], "");
                }
        }
        if(count>1) {
                System.out.println(liststr[l]+" "+ count);
            }
            }
    }
}

2019/11/21 16:56

big Ko

파이썬 3입니다.

전화번호의 문자를 숫자로 대체한 다음, 얼마나 겹치는지 계산해서 출력했습니다.

(sub 함수를 사용할 줄 몰라서 노가다를 뛰었습니다.)

from re import sub

# 입력 부

n = int(input())

Number = []
for _ in range(n):
    Number.append(sub('-', '', input()))


# 문자 --> 숫자

def Str_to_num(string):
    string = sub('[WXY]', '9', sub('[TUV]', '8', sub('[PRS]', '7', sub('[MNO]', '6', sub('[JKL]', '5', sub('[GHI]', '4',
                  sub('[DEF]', '3', sub('[ABC]', '2', string))))))))
    return string


Number = list(map(lambda x: Str_to_num(x), Number))
Num_sort = sorted(list(set(Number)))

# 출력

for num in Num_sort:
    if len(Number) == len(Num_sort):
        print('No duplicates.')
        break
    if Number.count(num) == 1:
        continue
    print('{}-{} {}'.format(num[0:3], num[3:], Number.count(num)))

2020/01/21 22:10

우재용

import re
from collections import Counter

M = {
    'ABC':'2',
    'DEF':'3',
    'GHI':'4',
    'JKL':'5',
    'MNO':'6',
    'PRS':'7',
    'TUV':'8',
    'WXY':'9',
}

def trans(input):
    total = []
    for data in input:
        trans_num = ''
        data = re.sub('-', '', data)
        for i in range(0, len(data)):
            if data[i].isalpha():
                for key in M.keys():
                    if data[i] in key:
                        trans_num += M[key]
                        break
            else:
                trans_num += data[i]
        total.append(trans_num)
    return sorted(total)

def dupl_sort(num):
    dic = dict(Counter(num))
    out = {key: value for key, value in dic.items() if value > 1}
    return out

def main():
    data = ['4873279', 'ITS-EASY', '888-4567', '3-10-10-10', '888-GLOP',
            'TUT-GLOP', '967-11-11', '310-GINO', 'F101010', '888-1200',
            '-4-8-7-3-2-7-9-', '487-3279']
    number = trans((data))
    for key, value in dupl_sort(number).items():
        print('{}-{} {}'.format(key[:3], key[3:], value))

if __name__ == '__main__':
    main()

2020/04/17 17:42

Hwaseong Nam

#파이썬

def out_num(x):
    temp=[]
    for i in range (len(x)):
        if ord(x[i])>=48 and ord(x[i])<=57:
            temp.append(str(int(x[i])))
        elif x[i] in ('A', 'B','C'):
            temp.append('2')
        elif x[i] in ('D', 'E','F'):
            temp.append('3')
        elif x[i] in ('G', 'H','I'):
            temp.append('4')
        elif x[i] in ('J', 'K','L'):
            temp.append('5')
        elif x[i] in ('M', 'N','O'):
            temp.append('6')
        elif x[i] in ('P', 'R','S'):
            temp.append('7')
        elif x[i] in ('T', 'U','V'):
            temp.append('8')
        elif x[i] in ('W', 'X','Y'):
            temp.append('9')        
    temp.insert(3,'-')
    temp=''.join(temp)
    return (temp)


numbers="""4873279
ITS-EASY
888-4567
3-10-10-10
888-GLOP
TUT-GLOP
967-11-11
310-GINO
F101010
888-1200
-4-8-7-3-2-7-9-
487-3279""".split('\n')

out_dic={}
for i in range (len(numbers)):
    temp=out_num(numbers[i])
    print (numbers[i],'--->',temp)
    if temp in out_dic:
        out_dic[temp]+=1
    else:
        out_dic[temp]=1

print()
for key in out_dic:
    print (key,' : ',out_dic[key])

2020/05/01 14:14

Buckshot

<결과> 4873279 ---> 487-3279 ITS-EASY ---> 487-3279 888-4567 ---> 888-4567 3-10-10-10 ---> 310-1010 888-GLOP ---> 888-4567 TUT-GLOP ---> 888-4567 967-11-11 ---> 967-1111 310-GINO ---> 310-4466 F101010 ---> 310-1010 888-1200 ---> 888-1200 -4-8-7-3-2-7-9- ---> 487-3279 487-3279 ---> 487-3279 487-3279 : 4 888-4567 : 3 310-1010 : 2 967-1111 : 1 310-4466 : 1 888-1200 : 1 - Buckshot, 2020/05/01 14:17
all_str = ''
for i in str(input()).split():
    num = i
    str_ = ''
    count = 0
    for i in range(0, len(num)):
        if num[i] in ('A', 'B', 'C'):
            str_ += '2'
        elif num[i] in ('D', 'E', 'F'):
            str_ += '3'
        elif num[i] in ('G', 'H', 'I'):
            str_ += '4'
        elif num[i] in ('J', 'K', 'L'):
            str_ += '5'
        elif num[i] in ('M', 'N', 'O'):
            str_ += '6'
        elif num[i] in ('P', 'R', 'S'):
            str_ += '7'
        elif num[i] in ('T', 'U', 'V'):
            str_ += '8'
        elif num[i] in ('W', 'X', 'Y'):
            str_ += '9'
        else:
            try:
                int(num[i])
                str_ += num[i]
            except ValueError:
                continue
    all_str += (" "+str_)

real_all_str = all_str.split()
num_cnt = dict() 
for number in real_all_str: 
    if number not in num_cnt.keys(): 
        num_cnt[number] = 1 
    else: 
        num_cnt[number] += 1
for number in real_all_str: 
    if num_cnt[number] == 1:
        num_cnt[number] = "No duplitcates"
    else:
        continue
print(num_cnt)

인풋은 띄어쓰기로 구분해주시면 됩니다

실력이 부족해 정말 지저분한 코딩이 되었군요,,,더욱 노력하겠습니다


2020/05/12 15:32

Money_Coding

Python3.7 대문자 숫자 맵핑을 논리로 구현했습니다. ABCDEFGHI . . . 222333444

num = str(input()).split()
cnt = int(num[0])
maps = [x for x in range(65, 90)]
maps.remove(81)
dic = {}
ll = []
[dic.setdefault(maps[j], i) for i in range(2, 10)
                            for j in range(0+(i-2)*3, 3+(i-2)*3)]

for i in range(1, cnt+1):
    #del la[:]
    la = []
    for j in num[i]:
        a = ord(j)
        if a == 45:
            pass
        elif 65<=a and a<=90:
            la.append(dic.get(a))
        else:
            la.append(a-48)

    ll.append(int(''.join([chr(x+48) for x in la])))

if ll.count(3101010)>0:
    print('310-1010',ll.count(3101010))
if ll.count(4873279)>0:
    print('487-3279',ll.count(4873279))
if ll.count(8884567)>0:
    print('888-4567',ll.count(8884567))

2020/06/02 01:49

김태준

def translate(words):

  for_return=[]

  for i in range(len(words)):

    if words[i] != '-':

      if words[i] in ['2','A','B','C']:

        for_return.append('2')

      elif words[i] in ['3','D','E','F']:

        for_return.append('3')

      elif words[i] in ['4','G','H','I']:

        for_return.append('4')

      elif words[i] in ['5','J','K','L']:

        for_return.append('5')

      elif words[i] in ['6','M','N','O']:

        for_return.append('6')

      elif words[i] in ['7','P','R','S']:

        for_return.append('7')

      elif words[i] in ['8','T','U','V']:

        for_return.append('8')

      elif words[i] in ['9','W','X','Y']:

        for_return.append('9')

      elif words[i] in ['1','0']:

        for_return.append(words[i])

  worda="".join(for_return)

  return worda

def program():

  number=int(input("write number <=100,000"))

  for_answer={}

  for i in range(number):

    word=input("write phone number :")

    words=translate(word)

    if words in for_answer:

      for_answer[words]+=1

    else :

      for_answer[words]=1

  if max(for_answer.values())<2:

    print("No duplicates")

  else:

    for i in for_answer.keys():

      if for_answer[i]>1:

        print('{0}  {1}'.format(i,for_answer[i]))

program()

2020/12/19 16:05

전준혁

## Function 1 : 문자 - 숫자로 대응
# A, B, C -> 2
# D, E, F -> 3
# G, H, I -> 4
# J, K, L -> 5
# M, N, O -> 6
# P, R, S -> 7
# T, U, V -> 8
# W, X, Y -> 9

def converter(text):
    temp = list(text)
    for bb in temp: 
        if bb == '-': del temp[temp.index('-')]

    for aa in temp:
        if aa in list('ABC'):
            temp[temp.index(aa)] = '2'
        elif aa in list('DEF'):
            temp[temp.index(aa)] = '3'
        elif aa in list('GHI'):
            temp[temp.index(aa)] = '4'
        elif aa in list('JKL'):
            temp[temp.index(aa)] = '5'
        elif aa in list('MNO'):
            temp[temp.index(aa)] = '6'
        elif aa in list('PRS'):
            temp[temp.index(aa)] = '7'
        elif aa in list('TUV'):
            temp[temp.index(aa)] = '8'
        elif aa in list('XYZ'):
            temp[temp.index(aa)] = '9'

    return ''.join(temp)
# print(converter('310-GI-NO'))

result = {}
## Function 2 : 전화번호 입력
def generate(text):
    try:
        # print(result.keys())
        if converter(text) in result.keys():
            result[converter(text)] += 1
        else:
            result[converter(text)] = 1
    except:
        result[converter(text)] = 1

## Function 3 : 전화번호 출력
def print_result():
    temp_result = []
    for aa in result.keys():
        # list(aa).insert(3, '-')
        if result[aa] >= 2:
            temp_result.append(aa[0:3] + '-' + aa[3:] + '+' + str(result[aa]))
    temp_result.sort()

    for mem in temp_result:
        print(mem.split('+')[0], mem.split('+')[1])


generate('4873279')
generate('ITS-EASY')
generate('888-4567')
generate('3-10-10-10')
generate('888-GLOP')
generate('TUT-GLOP')
generate('967-11-11')
generate('310-GINO')
generate('F101010')
generate('888-1200')
generate('-4-8-7-3-2-7-9-')
generate('487-3279')

print_result()

2020/12/21 08:57

DSHIN

def jeon(j):
    Alpha = {'A':2,'B':2,'C':2,'D':3,'E':3,'F':3,'G':4,'H':4,'I':4,'J':5,'K':5,'L':5,'M':6,'N':6,'O':6,'P':7,'R':7,'S':7,'T':8,'U':8,'V':8,'W':9,'X':9,'Y':9,
    '-':'-','1':1,'2':2,'3':3,'4':4,'5':5,'6':6,'7':7,'8':8,'9':9,'0':0,'10':10}
    c=[]
    count=0
    cnt = {}
    for d in j:
        b=''
        for i in d:
            b+=str(Alpha[i])
        if len(b)>8:
            d = b.replace('-','')
            e = d[:3]+'-'+d[3:]
            c.append(e)
        elif len(b)<8:
            d = b[:3]+'-'+b[3:]
            c.append(d)
        else:
            c.append(b)
        count+=1
    for w in c:
        try: cnt[w]+=1
        except: cnt[w]=1
    revers = {}
    for k,v in cnt.items():
        revers[v]=k
    del revers[1]
    cnt = {}
    for k, v in revers.items():
        cnt[v]=k
    print(cnt)

jeon(['4873279',
'ITS-EASY',
'888-4567',
'3-10-10-10',
'888-GLOP',
'TUT-GLOP',
'967-11-11',
'310-GINO',
'F101010',
'888-1200',
'-4-8-7-3-2-7-9-',
'487-3279'])

2021/03/14 22:23

fox.j


num_dict = {
'2': ['A', 'B', 'C'],
'3': ['D', 'E', 'F'],
'4': ['G', 'H', 'I'],
'5': ['J', 'K', 'L'],
'6': ['M', 'N', 'O'],
'7': ['P', 'R', 'S'],
'8': ['T', 'U', 'V'],
'9': ['W', 'X', 'Y']
}


tel_list = ['4873279','ITS-EASY','888-4567','3-10-10-10','888-GLOP','TUT-GLOP','967-11-11','310-GINO','F101010','888-1200','-4-8-7-3-2-7-9-','487-3279']

tel_dict = {}

for i in tel_list:
    tel_no = ''
    for j in i:
        if (ord(j) >= 48 and ord(j) <= 57):
            tel_no += j
        elif (ord(j) >= 65 and ord(j) <= 90):
            for k, v in num_dict.items():
                if j in v:
                    tel_no += k
        else:
            continue

    if tel_no not in tel_dict.keys():
        tel_dict[tel_no] = 1
    else:
        tel_dict[tel_no] += 1

cnt = 0
for k, v in tel_dict.items():
    if v > 1:
        print(f'{k[:3]}-{k[4:]}', v)
        cnt += 1   

if cnt == 0:
    print('no duplicate')


올리고 나서 다른 분들 코드를 보는 항상 부끄럽네요...그래도 올려봅니다 ^^;;

2021/04/13 12:32

잘해보자

def makeAns(str_):
    dic1 = {"A": 2, "B": 2, "C": 2, "D": 3, "E": 3, "F": 3, "G": 4, "H": 4, "I": 4, "j": 5, "K": 5, "L": 5,
            "M": 6, "N": 6, "O": 6, "P": 7, "R": 7, "S": 7, "T": 8, "U": 8, "V": 8, "W": 9, "X": 9, "Y": 9,
            "0": 0, "1": 1, "2": 2, "3": 3, "4": 4, "5": 5, "6": 6, "7": 7, "8": 8, "9": 9}

    def readLine(str2_):
        list1 = []
        for i in range(0, len(str2_)):
            try:
                list1.append(str(dic1[str2_[i]]))
            except:
                pass
        return "".join(list1)

    list2 = str_.split("\n")
    dic2 = {}
    for tmp in list2:
        tmp_ = readLine(tmp)[:3] + "-" +readLine(tmp)[3:]
        if tmp_ in dic2:
            dic2[tmp_] = dic2[tmp_] + 1
        else:
            dic2[tmp_] = 1

    for tmp2 in dic2:
        if dic2[tmp2] == 1:
            dic2[tmp2] = "No duplicates."
        print (tmp2, dic2[tmp2])




str__ = """4873279
ITS-EASY
888-4567
3-10-10-10
888-GLOP
TUT-GLOP
967-11-11
310-GINO
F101010
888-1200
-4-8-7-3-2-7-9-
487-3279"""

makeAns(str__)

결과
487-3279 4
888-4567 3
310-1010 2
967-1111 No duplicates.
310-4466 No duplicates.
888-1200 No duplicates.

2021/04/29 17:56

와장창

input = """12
4873279
ITS-EASY
888-4567
3-10-10-10
888-GLOP
TUT-GLOP
967-11-11""".splitlines()

glo={ "A": 2, "B": 2, "C": 2, "D": 3, "E": 3, "F": 3, "G": 4, "H": 4,
 "I": 4, "j": 5, "K": 5, "L": 5,"M": 6, "N": 6, "O": 6, "P": 7, "R": 7,
  "S": 7, "T": 8, "U": 8, "V": 8, "W": 9, "X": 9, "Y": 9}

input2 = []
for i in input:
    input2.append(''.join(i.split('-')))
input3 = []
for i2 in input2:
    q = []
    for ii in i2:
        if ii.isalpha(): q.append(str(glo[ii]))
        else : q.append(ii)
    input3.append(''.join(q))

input4 = []
for d in input3:
    if len(d)==7 : input4.append(f'{d[:3]}-{d[3:]}')

count = {}
for c in input4:
    try : count[c] += 1
    except : count[c]=1
print(count)

2021/05/27 14:14

약사의혼자말

#codingdojing_487_3299

from collections import defaultdict
import sys

tel_rule = {'A':2, 'B':2, 'C':2, 'D': 3,'E':3, 'F':3, 'G': 4, 'H':4, 'I':4,
'J':5, 'K':5, 'L':5, 'M':6, 'N' :6, 'O':6, 'P':7, 'R':7, 'S':7, 'T':8, 'U': 8,
'V':8, 'W':9, 'X':9, 'Y':9 }

n = eval(input("total tel: "))
tel_dic = defaultdict(int)

for i in range(n):
    tel = input()
    tel_num = ''
    for s in tel:
        if s.isdigit(): tel_num += s
        elif s.isalpha(): tel_num += str(tel_rule[s.upper()])

    tel_dic[tel_num[:3]+'-'+tel_num[3:]] += 1 #전화번호 추가

if 1 in tel_dic.values() and len(tel_dic.values()) == n: #value가 1뿐이면 / values()는 1뿐이어도 여러개
    print("No duplicates")
    sys.exit()

for n in sorted(tel_dic):
    if tel_dic[n] != 1: print(n, tel_dic[n])

2021/08/02 15:40

Jaeman Lee

숫자변환

def numbering (a) : if a=="A"or a=="B" or a=="C": a="2" elif a=="D"or a=="E" or a=="F": a="3" elif a=="G"or a=="H" or a=="I": a="4" elif a=="J"or a=="K" or a=="L": a="5" elif a=="M"or a=="N" or a=="O": a="6" elif a=="P"or a=="R" or a=="S": a="7" elif a=="T"or a=="U" or a=="V": a="8" elif a=="W"or a=="X" or a=="Y": a="9" return a

표준화

def standard (a) : arr = list(a) while "-" in arr : arr.remove("-") for i in range(len(arr)) : if ord(arr[i])<48 or ord(arr[i])>58: arr.insert(i,numbering(arr[i])) arr.pop(i+1) arr.insert(3,"-") return "".join(arr)

중복 CNT

def cnt (a) : b = set(a) c =[] if len(a)==len(b) : print("No duplicates") for k in b : n =a.count(k) if n >1: c.append([k,n]) sorted(c) for i in c: print(i[0]," ",i[1])

n = int(input("몇개의 전화번호?"))

num_arr =[] stand_num_arr =[]

for k in range(n): a = input("전화번호입력") if standard(a) ==8: num_arr.append(a)

for j in num_arr : stand_num_arr.append(standard(j))

cnt(stand_num_arr)

2021/12/27 03:31

양캠부부

count = int(input())
_input_list = []

#입력
for i in range(0,count):
    _input_list.append(input())

#출력
def phone(string):
    result=""
    for i in string:
        if i == '-' : pass
        elif i in ['A','B','C'] : result += '2'
        elif i in ['D','E','F'] : result += '3'
        elif i in ['G','H','I'] : result += '4'
        elif i in ['J','K','L'] : result += '5'
        elif i in ['M','N','O'] : result += '6'
        elif i in ['P','R','S'] : result += '7'
        elif i in ['T','U','V'] : result += '8'
        elif i in ['W','X','Y'] : result += '9'
        else :result += i

        if len(result) == 3 : result += '-'
    return result

_input_list = list(map(phone,_input_list))
_input_no_dup = list(set(_input_list))


for i in _input_no_dup:
    print(i,end = " ")
    if _input_list.count(i) == 1 : print("No duplicates")
    else :print(_input_list.count(i))

2022/01/15 19:57

강태호

a = 'ABCDEFGHIJKLMNOPRSTUVWXY'
b = ''.join([str(2+x//3) for x in range(len(a))])
c = dict(zip(a,b))

def assign(a):
    return a if a.isdigit() else c[a]

def word(s):
    return ''.join([assign(x) for x in s[:3]] + ['-'] + [assign(x) for x in s[-4:]])

s = '''12
4873279
ITS-EASY
888-4567
3-10-10-10
888-GLOP
TUT-GLOP
967-11-11
310-GINO
F101010
888-1200
-4-8-7-3-2-7-9-
487-3279'''

s2 = s.replace('-','').split('\n')

s3 = [word(s2[i]) for i in range(1,len(s.replace('-','').split('\n')))]
s4 = set(s3)

for x in s4:
    if s3.count(x) > 1:
        print(x, s3.count(x))

2022/02/10 14:59

로만가

package org.javaturotials.ex;
import java.util.*;
import java.util.stream.Collectors;

public class test {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int num =sc.nextInt();
        int sum=0;
        String[] arr = new String[num];
        for(int i=0; i<num; i++) {
        String str = sc.next();
        String re = str.replaceAll("[A-C]", "2").replaceAll("[D-F]", "3").replaceAll("[G-I]", "4").replaceAll("[J-L]", "5").replaceAll("[M-O]", "6").replaceAll("[P-S]", "7").replaceAll("[T-V]", "8").replaceAll("[W-Y]", "9").replaceAll("-", "");
        if(re.length()!=7) { i--;}
        if(re.length()==7) {
            arr[i] = re;}
        }
        for(int i=0; i<num; i++) {
            int count=0;
            for(int j=0; j<num; j++) {
                    if(arr[i].equals(arr[j])==true) {
                        count++;
                        sum+=1;
                }
            }
            if(sum>num) {System.out.println(arr[i] + " " + count);}
            }
            if(sum==num) {
            System.out.println("NO duplicates.");   
        }

            }
    }

2022/02/23 14:55

Kkubuck

a='''4873279 ITS-EASY 888-4567 3-10-10-10 888-GLOP TUT-GLOP 967-11-11 310-GINO F101010 888-1200 -4-8-7-3-2-7-9- 487-3279'''.replace("-","").split("\n") li=[] for i in a: for j in i: if j=='A' or j=="B" or j=="C": j=2 elif j=='D' or j=="E" or j=="F": j=3 elif j=='G' or j=="H" or j=="I": j=4 elif j=='J' or j=="K" or j=="L": j=5 elif j=='M' or j=="N" or j=="O": j=6 elif j=='P' or j=="R" or j=="S": j=7 elif j=='T' or j=="U" or j=="V": j=8 elif j=='X' or j=="Y" or j=="W": j=9 li.append(str(j)) print(a) b="".join(li) count=0 li1=[] for i in b: li1.append(i) count+=1 if count%7==0: li1.append(",") c="".join(li1).split(",") dic={i:0 for i in c} for i in dic: print(i) for j in c: if i==j: dic[i]+=1 print(dic)

2022/04/22 14:28

yunjae

def makeNum(snum):
    alphas = "ABCDEFGHIJKLMNOPRSTUVWXY"
    res = ""
    for n in snum:
        if not n.isdigit():
            n = str(alphas.index(n)//3 + 2)
        res += n
    return res


def transformToStandard(inp):
    dict = {}
    for tel in inp.split('\n'):
        snum = ""
        for s in tel:
            if s=='-' or s==' ':
                continue
            snum += s
        num = makeNum(snum)
        if num not in dict.keys():
            dict[num] = 0
        dict[num] += 1

    for k in dict:
        if dict[k]>1:
            print("%s-%s  %d" %(k[:3], k[3:], dict[k]))


transformToStandard("""4873279
ITS-EASY
888-4567
3-10-10-10
888-GLOP
TUT-GLOP
967-11-11
310-GINO
F101010
888-1200
-4-8-7-3-2-7-9-
487-3279""")

2023/12/22 20:49

insperChoi

목록으로