출처 : http://okjsp.net/bbs?seq=92230
주어진 문자열(공백 없이 쉼표로 구분되어 있음)을 가지고 아래 문제에 대한 프로그램을 작성하세요.
이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌
618개의 풀이가 있습니다.
1번문제 김씨와 이씨 각각 카운트 해야한다는 지적 감사합니다~ 수정했어요.
names = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌".split(",")
#1
a=[ i[0] for i in names ]
print("김씨 : %d\n이씨 : %d\n"%(a.count("김"), a.count("이")))
#2
print(names.count("이재영"))
#3
uniq_names = list(set(names))
print(uniq_names)
#4
uniq_names.sort()
print(uniq_names)
import java.util.ArrayList;
import java.util.Arrays;
public class Prob410 {
public static void main(String[] args) {
String input = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌";
String[] names = input.split(",");
int count_kim = 0;
int count_lee = 0;
int count_ljy = 0;
ArrayList<String> name_list = new ArrayList<String>();
for(int i = 0; i < names.length; i++) {
if(names[i].startsWith("김"))
count_kim++;
if(names[i].startsWith("이"))
count_lee++;
if(names[i].equals("이재영"))
count_ljy++;
if(!name_list.contains(names[i]))
name_list.add(names[i]);
}
String[] name_arr = name_list.toArray(new String[name_list.size()]);
System.out.println("김 씨: " + count_kim);
System.out.println("이 씨: " + count_lee);
System.out.println("이재영 씨: " + count_ljy);
System.out.println("중복을 제거한 이름: ");
for(int i = 0; i < name_arr.length; i++)
System.out.print(name_arr[i] + ((name_arr.length == i + 1)?"\n":", "));
Arrays.sort(name_arr);
System.out.println("중복을 제거한 이름을 오름차순으로: ");
for(int i = 0; i < name_arr.length; i++)
System.out.print(name_arr[i] + ((name_arr.length == i + 1)?"\n":", "));
}
}
Python
names = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌"
#리스트로 변환
list_names = names.split(',')
cnt_k=0 #김씨 카운터
cnt_l=0 #이씨 카운터
cnt_j=0 #이재영 카운터
#각각 카운터
for name in list_names:
if name[0] == '김':
cnt_k += 1
if name[0] == '이':
cnt_l += 1
if name == '이재영':
cnt_j += 1
print("1. 김씨와 이씨는 각각 몇 명 인가요? 김씨: "+ str(cnt_k)+"명, 이씨: "+ str(cnt_l)+"명")
print("2. 이재영 이란 이름이 몇 번 반복되나요? "+ str(cnt_j) + "번")
#집합으로 변환하여 중복 제거
set_names = set(list_names)
print("3. 중복을 제거한 이름을 출력하세요.")
#중복제거 출력
for name in set_names:
print(name)
print("4. 중복을 제거한 이름을 오름차순으로 정렬하여 출력하세요.")
#오름차순 정렬 출력
for name in sorted(set_names):
print(name)
import re
aalist = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌"
aaresult = aalist.split(',')
countNm = 0
for nm in aaresult:
m = re.search('(이|김).*',nm)
if m:
countNm = countNm + 1
print("1.김씨와 이씨는 각각 몇 명 인가요: ",countNm)
print("2.\"이재영\"이란 이름이 몇 번 반복되나요?: ",aaresult.count("이재영"))
resultList = list(set(aaresult))
print("3.중복을 제거한 이름을 출력하세요.: ", ",".join(resultList))
resultList.sort()
print("4.중복을 제거한 이름을 오름차순으로 정렬하여 출력하세요.: ", ",".join(resultList))
요즘 파이썬에 놀라운 간결함에 빠진 자바개발자 입니다. 초짜수준의 실력이지만 처음으로 달아봅니다
package test;
import java.util.ArrayList;
import java.util.Arrays;
public class Prob0825 {
public static void main(String[] args) {
String names = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌";
String[] namelist = names.split(",");
ArrayList<String> rm_name = new ArrayList<String>();
int count_kim = 0, count_lee = 0;
int count_name = 0;
int count_rm = 0;
System.out.println("배열 총 개수는 "+namelist.length);
for (int i = 0;i<namelist.length;i++){
if(namelist[i].matches("김.*"))
count_kim++;
if(namelist[i].matches("이.*"))
count_lee++;
if(namelist[i].matches("이재영"))
count_name++;
if(!rm_name.contains(namelist[i])){
rm_name.add(namelist[i]);
count_rm++;
}
}
String[] sort_name = rm_name.toArray(new String[rm_name.size()]);
System.out.println("김씨는 " + count_kim+"명 입니다.");
System.out.println("이씨는 " + count_lee+"명 입니다.");
System.out.println("이재영은 "+count_name+"번 반복됩니다.");
System.out.println("중복제거 후, "+count_rm+"명 : "+rm_name);
Arrays.sort(sort_name);
System.out.println("중복제거 및 정렬 후 : "+Arrays.toString(sort_name));
}
}
arr = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌".split(",")
print('김씨:', len(list(filter(lambda x:x[0]=='김', arr))))
print('이씨:', len(list(filter(lambda x:x[0]=='이', arr))))
print('이재영:', len(list(filter(lambda x:x=='이재영', arr))))
arr1 = list(set(arr))
print('중복을 제거한 이름:',arr1)
arr1.sort()
print('중복을 제거한 이름을 오름차순으로 정렬:',arr1)
(fn [name-src]
(let [name-seq (re-seq #"[가-힣]+" name-src)
name-group (group-by first name-seq)
unique-name-seq (distinct name-seq)])
(println "김씨의 수: " (count (get name-group \김)))
(println "이씨의 수: " (count (get name-group \이)))
(println "이재영의 수: " (count (filter #(= "이재영" %) name-seq)))
(println "중복 없는 명단: " unique-name-seq)
(println "정렬된 중복 없는 명단: " (sort-by #(.hashCode %) sorted-unique-name-seq)))
Clojure 코드입니다.
Ruby.
people = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌".split(",")
# 1
people.select{|i| i[0] =~ /[김|이]/}.group_by{|i| i[0]}.map{|k,v| {k => v.size}}
# 2
people.count{|i| i =~ /이재영/}
# 3
puts people.uniq
# 4
puts people.uniq.sort
자바입니다. 중복제거를 LinkedHashSet으로 처리했습니다.
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.StringTokenizer;
public class SortName {
public static void main(String[] args) {
final String input = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌";
String name;
StringTokenizer token;
int countKim=0;
int countLee=0;
int countLeejy=0;
ArrayList<String> nameArrList = new ArrayList<String>();
token=new StringTokenizer(input,",");
while(token.hasMoreTokens()){
name=token.nextToken();
nameArrList.add(name);
if(name.startsWith("김")) countKim++;
if(name.startsWith("이")) countLee++;
if("이재영".equals(name)) countLeejy++;
}
// 1,2 카운트
System.out.println("1. count Kim " + countKim + " count Lee " +countLee );
System.out.println("2. 이재영이란 이름은 몇번? " + countLeejy );
//3.중복제거
nameArrList = new ArrayList<String>(new LinkedHashSet<String>(nameArrList));
System.out.println("3. 중복제거 ");
int listSize = nameArrList.size();
for(int i=0;i<listSize;i++){
System.out.print(nameArrList.get(i)+((i==listSize-1)?"":","));
}
//4.중복제거 정렬
System.out.println("\n4. 중복제거 오름차순 ");
Collections.sort(nameArrList);
for(int i=0;i<listSize;i++){
System.out.print(nameArrList.get(i)+((i==listSize-1)?"":","));
}
}
}
펄입니다
use latest;$_=$ARGV[0];my $s=$ARGV[1];my ($kim,$lee,%names);chomp;
for(split/,/){if(/^김/){$kim++;}if(/^이/){$lee++}$names{$_}++}
say "김:$kim명 이:$lee명";say "이재영:$names{'이재영'}번";say "@{[keys %names]}";
static void Main(string[] args)
{
List<string> abc = new List<string>();
string here = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌";
string[] name = here.Split(',');
int kimcnt = 0, ecnt = 0, smecnt = 0;
for (int i = 0; i < name.Length; i++)
{
if (name[i].StartsWith("이"))
{
ecnt++;
}
else if (name[i].StartsWith("김"))
{
kimcnt++;
}
if (name[i] == "이재영")
{
smecnt++;
}
abc.Add(name[i]);
}
IEnumerable<string> yeb = abc.Distinct();
abc = yeb.ToList();
Console.WriteLine("김씨 : {0} 이씨 : {1}", kimcnt, ecnt);
Console.WriteLine("이재영이란 이름이 몇 번 반복되나요 ? {0}", smecnt);
Console.WriteLine("중복 제거");
foreach (string item in abc)
{
Console.Write("{0} ", item);
}
Console.WriteLine();
abc.Sort();
Console.WriteLine("정렬");
foreach (string item in abc)
{
Console.Write("{0} ", item);
}
Console.WriteLine();
}
피로가 극에 다달았더니 코드가 매우 더럽네요 ㅠㅠ 일단 하루 1문제 성공했으니 다른 퀘스트를 하고 어서 자고 싶습니다ㅏ악
C#으로 작성했습니다.
using System.Collections.Generic;
using System.Linq;
public List<string> PrintDuplicateRemoval(List<string> inputs)
{
var kim = inputs.Count(i => i.First() == '김');
var lee = inputs.Count(i => i.First() == '이');
var ljy = inputs.Count(i => i == "이재영");
var outputs = inputs.GroupBy(i => i).Where(i => i.Count() == 1).Select(i => i.Key).ToList();
return outputs.OrderBy(i => i).ToList();
}
names='이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌'
name_list=names.split(',')
names='이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌'
name_list=names.split(',')
from collections import Counter
count_kim=0
count_lee=0
#1.
for name in name_list:
if name.startswith("김"):
count_kim+=1
elif name.startswith("이"):
count_lee+=1
print("김씨 : " , count_kim)
print("씨 : " , count_lee)
#2.
Counter(name_list)['이재영']
#3.
unique=list(set(name_list))
print(unique)
#4.
unique.sort(reverse=True)
print(unique)
data='이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌'
import re
#1
Kim=re.compile('[김]\w{2}')
Lee=re.compile('[이]\w{2}')
print(len(Kim.findall(data)))
print(len(Lee.findall(data)))
#2
Lee_J_Y=re.compile('[이][재][영]')
print(len(Lee_J_Y.findall(data)))
#3
Tem=data.split(",")
Uni=list(set(Tem))
Uni_data=",".join(Uni)
print(Uni_data)
#4
Uni.sort()
print(Uni)
R로 풀어봤어요
txt="이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌"
name=unlist(strsplit(txt, ","))
#1
length(grep("^(김|이)", name))
#2
length(which("이재영"==name))
#3
unique(name)
#4
sort(unique(name))
clojure
(let [name-str "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌"
name-lst (clojure.string/split name-str #",")]
{:1 (->> name-lst
(filter #(let [family (first %)]
(or (= family \이)
(= family \김))))
count)
:2 (->> name-lst
(filter #{"이재영"})
count)
:3 (-> name-lst distinct)
:4 (-> name-lst distinct sort)})
파이썬 2.7.5 버전(윈도우용) 입니다. 한글 코드가 안나와서 힘들었는데, 꼭 이렇게 해야 되는 것인지, 다른 방법이 있는지 알고 싶습니다.
#_*_ coding: utf-8 _*_
import re
name_data = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌"
name_list = name_data.split(',')
count_sung = 0
for name in name_list:
sung = re.search('^(이|김)',name)
if sung:
count_sung = count_sung + 1
result_list = list(set(name_list))
print unicode("1. 김씨와 이씨는 각각 몇 명 인가요: %d" % count_sung)
print unicode("2. \"이재영\"이란 이름이 몇 번 반복되나요?: %d" % name_list.count("이재영"))
name_nojung = ", ".join(result_list)
print unicode("3. 중복을 제거한 이름을 출력하세요.: \n %s" % str(name_nojung).decode('string-escape'))
result_list.sort()
name_nojung_s = ", ".join(result_list)
print unicode("4. 중복을 제거한 이름을 오름차순으로 정렬하여 출력하세요.: \n %s \n" % str(name_nojung_s).decode('string-escape'))
결과 입니다.
1. 김씨와 이씨는 각각 몇 명 인가요: 8
2. "이재영"이란 이름이 몇 번 반복되나요?: 3
3. 중복을 제거한 이름을 출력하세요.:
김지완, 전경헌, 최승혁, 이유덕, 김재성, 이성연, 송정환, 강상희, 권종표, 이재영,
박영서, 박민호
4. 중복을 제거한 이름을 오름차순으로 정렬하여 출력하세요.:
강상희, 권종표, 김재성, 김지완, 박민호, 박영서, 송정환, 이성연, 이유덕, 이재영,
전경헌, 최승혁
Python 3.4
name = '이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌'
result = name.split(',')
n = len(result)
countK = countL = 0
for i in range(n-1):
if result[i][0] == '김': countK += 1
elif result[i][0] == '이': countL += 1
result3 = []
for i in range(n-1):
if result.count(result[i]) == 1: result3.append(result[i])
result4 = result3[:]
result4.sort()
print('#1: 김씨 %d명, 이씨 %d명' % (countK, countL))
print('#2: ', result.count('이재영'), '번')
print('#3: ', ", ".join(result3))
print('#4: ', ", ".join(result4))
Output
#1: 김씨 2명, 이씨 6명
#2: 3 번
#3: 권종표, 강상희, 김지완, 최승혁, 이성연, 박영서, 송정환, 김재성
#4: 강상희, 권종표, 김재성, 김지완, 박영서, 송정환, 이성연, 최승혁
파이썬 3.2.5 기준입니다.
string = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌"
name_list = string.split(",")
김씨 = 0
이씨 = 0
for name in name_list:
if name[0] == "김":
김씨 += 1
elif name[0] == "이":
이씨 += 1
name_set_list = list(set(name_list))
name_set_list.sort()
print("김씨 : {} 명".format(김씨))
print("이씨 : {} 명".format(이씨))
print(set(name_list))
print(name_set_list)
#-*- coding: utf-8 -*-
rawdata = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌"
name = rawdata.split(',')
k,l,c = 0,0,0
pre = ''
lst = []
for i in sorted(name):
if i[0]+i[1]+i[2] == '김': k += 1
if i[0]+i[1]+i[2] == '이': l += 1
if i == '이재영': c += 1
if i == pre: continue
else:
pre = i
lst.append(i)
print "1. k : ", k
print " l : ", l
print "2. c : ", c
print "3. list(sorted) : ",
for i in lst:
print i,
PHP 입니다.
$str = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌";
$arr = explode(',',$str);
$cnt = count($arr);
$ans1 = $ans2 = $ans3 = 0;
$ans4 = $ans5 = '';
for($i=0; $i<$cnt; $i++) {
$ans1 += (strpos($arr[$i], '김') === 0) ? 1 : 0;
$ans2 += (strpos($arr[$i], '이') === 0) ? 1 : 0;
$ans3 += ($arr[$i] === '이재영') ? 1 : 0;
}
$ans4 = implode(',',array_unique($arr));
sort($arr);
$ans5 = implode(',',array_unique($arr));
echo $ans1.'<br>';
echo $ans2.'<br>';
echo $ans3.'<br>';
echo $ans4.'<br>';
echo $ans5.'<br>';
/*
2
6
3
이유덕,이재영,권종표,박민호,강상희,김지완,최승혁,이성연,박영서,전경헌,송정환,김재성
강상희,권종표,김재성,김지완,박민호,박영서,송정환,이성연,이유덕,이재영,전경헌,최승혁
*/
자바입니다^^
import java.util.ArrayList;
import java.util.Collections;
public class DuplicatedString {
public static void main(String[] args) {
String data = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌";
String[] divided = data.split(",");
ArrayList<String> list = new ArrayList<String>(); // 정렬을 위한 자료구조 사용
int[] number = new int[divided.length]; // 횟수 저장
boolean check = false; // 중복 확인
int count = 0; // 문자열 횟수
for (int i = 0; i < divided.length; i++) {
// divided의 이름을 list에 저장하고
// 중복되면 저장안하고 count++
String temp = divided[i];
for(int j=0;j<list.size();j++){
if(list.get(j).equals(temp)){
check = true;
number[j]++;
}
}
if(check){
check = false;
}else{ // 중복이 아니면
number[count++]=1;
list.add(divided[i]);
}
}
// 1.김씨와 이씨는 각각 몇 명 인가요?
int kim=0,lee=0;
for(int i=0;i<divided.length;i++){
if(divided[i].charAt(0)=='이'){
lee++;
}else if(divided[i].charAt(0)=='김'){
kim++;
}
}
System.out.println("김씨는 " + kim + "명이고, " + "이씨는 " + lee + "명입니다.");
// 2."이재영"이란 이름이 몇 번 반복되나요?
int index = 0;
for(int i=0;i<list.size();i++){
if(list.get(i)=="이재영"){
index = i;
return;
}
}
System.out.println("이재영이란 이름은 " + number[index] + "번 반복됩니다.");
// 3.중복을 제거한 이름을 출력하세요.
System.out.println(list.toString());
// 4.중복을 제거한 이름을 오름차순으로 정렬하여 출력하세요. => Collections 를 사용할 수 있는 List를 사용해야 한다.
Collections.sort(list);
System.out.println(list.toString());
}
}
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class FindSearchArray {
public static void main(String[] args) {
String names = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌";
String kim = "김";
String lee = "이";
String leejaeyoung = "이재영";
int familyNameCount = 0;
int findHerNameCount = 0;
String[] split = names.split(",");
Set<String> nameSet = new HashSet<String>();
for(int i=0; i<split.length; i++){
// 1. 첫 글자가 모두 성씨인 것으로 가정
if(split[i].startsWith(kim) || split[i].startsWith(lee)){
familyNameCount ++;
}
boolean contains = split[i].contains(leejaeyoung);
if(contains){
findHerNameCount++;
}
nameSet.add(split[i]);
}
System.out.println("김씨와 이씨 몇 명? : " +familyNameCount);
System.out.println("이재영 몇 번 반복? : " + findHerNameCount);
System.out.println("중복 제거 이름 출력 : " + nameSet);
// 중복을 제거한 이름을 오름차순으로 정렬하여 출력하세요.
List<String> nameList = new ArrayList<String>(nameSet);
Collections.sort(nameList);
System.out.println("중복 제거 오름차순 정렬 : " + nameList);
}
}
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main()
{
string name[] = { "이유덕", "이재영", "권종표", "이재영", "박민호",
"강상희", "이재영", "김지완", "최승혁", "이성연",
"박영서", "박민호", "전경헌", "송정환", "김재성",
"이유덕", "전경헌" };
int arr_size = std::extent<decltype(name)>::value;
//1. 김씨와 이씨는 각각 몇 명 인가요?
int kim_count=0, lee_count=0, jaeyoung_count=0;
string fName;
for (int i = 0; i < arr_size; i++)
{
fName = name[i].substr(0, 2);
if (fName == "김") kim_count++;
if (fName == "이") lee_count++;
if (name[i].compare("이재영")==0) jaeyoung_count++;
}
cout << "김씨의 숫자 : " << kim_count << ", 이씨의 숫자 : " << lee_count << endl;
cout << "이재영이란 이름이 몇 번 나오는가 : " << jaeyoung_count << endl;
//3. 중복을 제거한 이름을 출력하세요.
vector<string> name2;
bool check = true;//중복체크
for (int i = 0; i < arr_size; i++)
{
check = true;
if (name2.empty())
{
name2.push_back(name[i]);
}
else
{
for (unsigned int j = 0; j < name2.size(); j++)
{
if (name2[j].compare(name[i])==0)
check = false;
}
if (check)
name2.push_back(name[i]);
}
}
//3번 답 출력
for (unsigned int i = 0; i < name2.size(); i++)
cout << name2[i] << ", ";
cout<<endl;
// 4. 중복을 제거한 이름을 오름차순으로 정렬하여 출력하세요.
string temp = "";
for (unsigned int i = 1; i < name2.size(); i++)
{
for (unsigned int j = 0; j < name2.size() - i; j++)
{
if (name2[j].compare(name2[j+1]) > 0)
{
temp = name2[j];
name2[j] = name2[j + 1];
name2[j + 1] = temp;
}
}
}
//4번 답 출력
for (unsigned int i = 0; i < name2.size(); i++)
cout << name2[i] << ", ";
cout << endl;
return 0;
}
너무 허접한거 같네요..ㅠ
// 언어 : Swift
import Foundation
var count = 0; // 1,2번문제 답 계산용 변수
var tmpMem = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌";
var restCount:Int = 0; // 몇명인지 세기위한 변수
var members: [String] = [] // 이름 저장할 배열
var x:Int; // 배열첨자용 변수
x = 0;
//////////////////////////////////////// 이름을 배열로 나누기
for rest in tmpMem
{
if( "," == rest ) { restCount++; }
} // 몇명이 있는지 계산
for count in tmpMem
{ // 이름하나당 하나의 인덱스에 저장
var tmp:String = Array(tmpMem)[x] + Array(tmpMem)[x+1];
tmp.append( Array(tmpMem)[x+2] );
members.append( tmp );
if( x >= (3*restCount) ) { break; } // 마지막 확인
x += 4;
} // 문자열 만들기
///////////////////////////////// 이,김 씨 찾기
var FamilyName = { // 문자열을 인자로, 정수형 반환
(currentMember:String) -> Int in
var tmp = Array(currentMember)[0]; // 문자열의 0번 인덱스 ( 첫글자 )
if ( "이" == tmp || "김" == tmp ) { return 1; } // 이,김 이면 1반환
return 0;
}
for member in members
{ // 이름이 들어있는 배열 차례로 조회
count += FamilyName(member); // 이,김씨이면 1이 더해진다.
}
println("이,김씨인사람은 \(count)명");
//////////////////////////////////// 이재영이란 이름찾기
count = 0;
var LJY = { // 문자열을 인자로, 정수형 반환
(currentMember:String) -> Int in
let tmp = "이재영";
if ( 0 == strcmp(tmp,currentMember) ) { return 1; }
return 0; // 이재영이면 1반환 아니면 0 반환
}
for member in members
{ // 이름이 들어있는 배열 차례로 조회
count += LJY(member); // 이재영이면 1 더해진다.
}
println("이재영이란 이름은 \(count)번 존재");
//////////////////////////////////// 중복제거후 이름출력
count = 0;
var NewMembers:[String] = []
var NameCmp = { // 문자열 비교
(st1:String, st2:String) -> Int in
if( 0 == strcmp(st1,st2) ) { return 1; }
return 0;
} // 같으면 1반환 다르면 0반환
for var x = 0; x < members.count-1; x++
{ // 인덱스 0~ 맨마지막 전까지
var result = 0;
for var y = x+1; y < members.count; y++
{ // 비교할 인덱스 기준으로 끝까지 모두 확인
result += NameCmp(members[x],members[y]);
}
if 0 == result { NewMembers.append(members[x]); }
} // 같은 문자열이라면 1이 반환되서 result가 0이 아니므로 저장취소
println("중복제거후");
for member in NewMembers
{
print("\(member) " );
}
println("");
//////////////////////////////////// 오름차순 정렬
// 설명: index 정수형 배열은 이름의 우선순위를 부여하는 배열이다.
// NewMembers[0] 의 우선순위는 index[0] 에 기록되어있고 나머지도 모두 동일
// 처음 우선순위는 모두0이지만 모든 이름을 하나씩 비교하며 우선순위가 낮은 이름에
// 1씩을 더해주면 비교완료후 index배열의 값은 0~10까지 정해지게된다.
// NewMembers 각 이름의 우선순위를 확인해서 맞는 위치를 찾아간다.
// 예) index[3] = 4 라면 NewMembers[3]의 우선순위는 4 이므로 저장될 위치는
// 결과저장될배열[4] 이다.
var index: [Int];(NewMembers.count) // 인원수만큼 정수형 배열 만들고 초기화
index = Array(count:NewMembers.count, repeatedValue: 0);
for var x = 0; x < NewMembers.count-1; x++
{
for var y = x+1; y < NewMembers.count; y++
{
var result = strcmp(NewMembers[x], NewMembers[y]);
// 모든 자료를 일일이 비교한다.
if 0 < result { index[x] += 1; }
else { index[y] += 1; }
}
} // 두개를 비교할때 둘중 우선순위가 낮은 자료에 1을 더한다.
// 모두 비교하면 우선순위가 0~10까지 생기게된다. 이숫자를 배열첨자로 활용
var SortMembers: [String];(NewMembers.count) // 결과 저장할 배열 만들고 초기화
SortMembers = Array(count:NewMembers.count, repeatedValue:"");
for var x = 0; x < NewMembers.count; x++
{
SortMembers[ index[x] ] = NewMembers[x];
} // 기존 배열의 0번 인덱스부터 차례로 위치를 찾아간다. 찾아갈 위치는
// index배열에 값으로 저장되어 있다.
for result in SortMembers{
print("\(result) ");
}
// 문자열 잘라낸후 복사하는 방법이 좀더 간편한게 있나 찾을 예정.
# -*- coding:utf-8 -*-
lst = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌"
kcnt, lcnt = 0, 0
lee = 0
names = []
new_names = []
names = lst.split(',')
for name in names:
if name[0] == '김':
kcnt += 1
if name[0] == '이':
lcnt += 1
if name == '이재영':
lee += 1
if name not in new_names:
new_names.append(name)
print (kcnt, lcnt, lee)
print (new_names)
new_names.sort()
print (new_names)
파이썬 3.4 입니다.
import re
def find_last_name(name_list,last_name):
count = 0
for x in name_list:
if bool(re.match(last_name,x)) == True:
count += 1
return count
name_str = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌"
name_list = name_str.split(',')
deduplicate = list(set(name_list))
last_one = "김"
last_two = "이"
print ("김씨와 이씨는 각기 %d명, %d명 입니다."%(find_last_name(name_list,last_one),find_last_name(name_list,last_two)))
print (""""이재영"이란 이름은 %d 번 반복됩니다."""%name_str.count("이재영"))
print ("중복을 제거한 이름 : %s"%",".join(deduplicate))
deduplicate.sort()
print ("중복을 제거한 오름차순 이름 : %s"%",".join(deduplicate))
java collection, String API 사용했습니다.
package my_test;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
public class T {
public static void main(String[] args) {
String str="이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌";
/*1번 */
String[] kim = str.split("김");
String[] lee = str.split("이");
int kimCt=-1;
int leeCt=-1;
for(int i=0;i<kim.length;i++){
kimCt++;
}
for(int i=0;i<lee.length;i++){
leeCt++;
}
System.out.println("1.김씨와 이씨는 각각 몇 명 인가요?\n >김씨:"+kimCt+ "명, 이씨:"+leeCt+"명");
/*2번*/
String[] ljy=str.split("이재영");
int ljyCt=-1;
for(int i=0;i<ljy.length;i++){
ljyCt++;
}
System.out.println("2.\"이재영\"이란 이름이 몇 번 반복되나요?\n >"+ljyCt+"번");
/*3번*/
String[] temp= str.split(",");
HashSet<String> set = new HashSet<String>();
String result="";
for(int i=0;i<temp.length;i++){
set.add(temp[i]);
}
for(String name:set){
result+=name+" ";
}
System.out.println("3.중복을 제거한 이름을 출력하세요.\n >"+result);
/*4번*/
System.out.print("4.중복을 제거한 이름을 오름차순으로 정렬하여 출력하세요.\n >");
ArrayList<String> list= new ArrayList<String>();
Iterator<String> it=set.iterator();
for(int i=0;i<set.size();i++){
list.add(it.next());
}
Collections.sort(list);//정렬
//오름 차순 출력
for(String name:list){
System.out.print(name+" ");
}
}
}
C# 입니다.
using System;
using System.Collections.Generic;
class Program
{
static string nameData = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌";
static void Main()
{
int kimCount = 0;
int leeCount = 0;
int leeJaeYoungCount = 0;
string[] names = nameData.Split(',');
List<string> nameList = new List<string>();
Console.WriteLine("이름 ========");
foreach (var aName in names)
{
if (aName.StartsWith("김"))
{
kimCount++;
}
else if (aName.StartsWith("이"))
{
leeCount++;
if (aName == "이재영")
{
leeJaeYoungCount++;
}
}
if (nameList.Contains(aName) == false)
{
nameList.Add(aName);
Console.WriteLine(aName);
}
}
Console.WriteLine("\n김씨 {0}명", kimCount);
Console.WriteLine("이씨 {0}명", leeCount);
Console.WriteLine("이재영 {0}명", leeJaeYoungCount);
nameList.Sort(CompareName);
Console.WriteLine("\n이름 정렬 ========");
foreach (var aName in nameList)
{
Console.WriteLine(aName);
}
}
static int CompareName(string x, string y)
{
return x.CompareTo(y);
}
}
#-*- coding: utf-8 -*-
def makeNameStack():
names = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌"
start = 0
for i in range(len(names)):
if(names[i] == ","):
nameStack.append(names[start:i])
start = i+1
def countLastName(s):
c = 0
for name in nameStack:
if name[0:3] == s:
c += 1
return c
def nameCount(s):
c = 0
for name in nameStack:
if name == s:
c+=1
return c
def removeDuplication():
for name in nameStack:
mark = 0
for dName in removedNameStack:
if dName == name:
mark = 1
break
if mark == 0:
removedNameStack.append(name)
def sorting():
for i in range(len(removedNameStack)):
for j in range(len(removedNameStack)):
if removedNameStack[i]<removedNameStack[j]:
temp = removedNameStack[i]
removedNameStack[i] = removedNameStack[j]
removedNameStack[j] = temp
nameStack = []
removedNameStack = []
makeNameStack()
leeCount = countLastName("이")
kimCount = countLastName("김")
leeJYCount = nameCount("이재영")
removeDuplication()
print leeCount, kimCount, leeJYCount
for name in removedNameStack:
print name,
sorting()
print "\n"
for name in removedNameStack:
print name,
파이썬 입니다
루비
people = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌".split(",")
kim = people.select{|i| i[0] == '김'}
lee = people.select{|i| i[0] == '이'}
# 1)
kim.count
lee.count
#2)
people.count("이재영")
#3)
people.uniq
#4)
people.uniq.sort
name='이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌'.split(',')
print(sum([1 for item in name if item[0]=='이' or item[0]=='김']))
print(name.count('이재영'))
print(set(name))
print(sorted(set(name)))
파이썬입니다.
#-*-coding:utf-8
names = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌"
print len([x for x in names.split(',') if x.startswith('김')])
print len([x for x in names.split(',') if x.startswith('이')])
print ",".join(set(names.split(',')))
print ",".join(sorted(set(names.split(','))))
names = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌".split(",")
# 1
names_by_last_name = names.group_by { |name| name[0] }
{"김" => names_by_last_name["김"].size, "이" => names_by_last_name["이"].size}
# 2
names.count("이재영")
# 3
names.uniq
# 4
names.uniq.sort
coding by python beginner
names = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌".split(',')
kimCnt = leeCnt = dupLjyCnt = 0
delDupNames = list( set(names) )
for name in names:
if name[0] == '김': kimCnt += 1
elif name[0] == '이': leeCnt += 1
if name == '이재영': dupLjyCnt+= 1
print('김씨: ' + str(kimCnt) + '명')
print('이씨: ' + str(leeCnt) + '명')
print('이재영 반복: ' + str(dupLjyCnt) + '번')
print('중복제거: ' + ', '.join(delDupNames) ); delDupNames.sort()
print('오름차순: ' + ', '.join(delDupNames) )
scala로 구현했습니다.
val input = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌"
val splited = input.split(",")
println(splited.count(_.matches("^[김|이].*")))
println(splited.count(_ == "이재영"))
println(splited.distinct.mkString(","))
println(splited.distinct.sorted.mkString(","))
package cynapsoft;
import java.util.ArrayList;
import java.util.Arrays;
public class cynapsoft {
public static void main(String[] args)
{
String input = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,"
+ "박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌";
String array[] = input.split(",");
//1번문제 김씨와 이씨는 각각 몇명인가
int c_kim=0, c_lee=0;
for(int i=0; i<array.length; i++){
if( array[i].substring(0, 1).equals("김") )
c_kim++;
if( array[i].substring(0, 1).equals("이") )
c_lee++;
}
System.out.println("김씨와 이씨는 각각 몇명일까요?: " + c_kim + "," + c_lee);
//2번문제 이재영이라는 이름은 몇번 반복되나
int leejaeyung = 0;
for(int i=0; i<array.length; i++){
if( array[i].equals("이재영") )
leejaeyung++;
}
System.out.println("\"이재영\"이라는 이름은 몇 번 반복되나요?: " + leejaeyung);
//3번문제 중복을 제거한 이름을 출력하세요
ArrayList<String> arraylist = new ArrayList<String>();
for(int i=0; i<array.length; i++){
//새로운 배열리스트에 넣을 이름이 있는지 검사후 없으면 더해줌
if( !arraylist.contains(array[i]) )
arraylist.add(array[i]);
} //배열리스트에 정리 된것을 다시 String배열에 넣어두고 String클래스함수 사용
String newarray[] = arraylist.toArray(new String[arraylist.size()]);
System.out.print("중복을 제거한 이름: ");
for(int i=0; i<newarray.length; i++)
System.out.print(newarray[i] + ((newarray.length == i + 1)?"\n":", "));
//4번문제 중복을 제거한 이름을 오름차순으로 정렬하세요
Arrays.sort(newarray);
System.out.print("중복을 제거한 이름을 오름차순으로: ");
for(int i=0; i<newarray.length; i++)
System.out.print(newarray[i] + ((newarray.length == i + 1)?"\n":", "));
}
}
Elixir
people = String.split("이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌", ",")
# 1
people
|> Enum.filter(&(Regex.match?(~r{김|이}, String.slice(&1,0,1))))
|> Enum.group_by(&(String.slice(&1,0,1)))
|> Enum.map(&([List.first(Tuple.to_list(&1)), length(List.last(Tuple.to_list(&1)))]))
# 2
people |> Enum.filter(&(&1 == "이재영")) |> length
# 3
people |> Enum.uniq
# 4
people |> Enum.uniq |> Enum.sort
swift로 작성하였습니다.
import Foundation
extension String {
subscript (i: Int) -> Character {
return self[advance(self.startIndex, i)]
}
subscript (i: Int) -> String {
return String(self[advance(self.startIndex, i)])
}
}
let nameStream = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌"
let nameTable:[String] = nameStream.componentsSeparatedByString(",")
// MARK: Problem 1
let y = nameTable.filter { $0[0] == "김" || $0[0] == "이" }
println("1.김씨와 이씨는 각각 몇 명 인가요? : \(y)")
// MARK: Problem 2
let x = nameTable
.filter { $0 == "이재영" }
.reduce(0) { (s0, s1) in s0 + 1 }
println("2.\"이재영\"이란 이름이 몇 번 반복되나요? \(x)")
// MARK: Problem 3
let removedDuplecateNameTable = NSSet(array: nameTable).allObjects as [String]
println("3.중복을 제거한 이름을 출력하세요. \n \(removedDuplecateNameTable)")
// MARK: Problem 4
let sortedRemovedDuplecateNameTable = sorted(removedDuplecateNameTable){ $0 < $1 }
println("4.중복을 제거한 이름을 오름차순으로 정렬하여 출력하세요. \n \(sortedRemovedDuplecateNameTable)")
name="이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌"
lkcnt=0
namel = name.split(',')
for n in namel:
if n[0] == "이" or n[0] == "김":
lkcnt+=1
print(lkcnt)
print(namel.count("이재영"))
print(set(namel))
print(sorted(set(namel)))
Using python
#-*- coding: euc-kr -*-
import re
name_list = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌"
name_list = name_list.split(',')
kcnt = 0
lcnt = 0
ljy = 0
for name in name_list:
if name[0:2] == "김":
kcnt +=1
elif name[0:2] == "이":
lcnt +=1
if name =="이재영":
ljy +=1
print "1.김씨와 이씨는 각각 몇 명 인가요: "+"이 씨 "+str(lcnt)+"명 김 씨 "+str(kcnt)+"명"
print "2.\"이재영\"이란 이름이 몇 번 반복되나요?: "+str(ljy)
print"3.중복을 제거한 이름을 출력하세요.: ","".join(set(name_list))
print"4.중복을 제거한 이름을 오름차순으로 정렬하여 출력하세요.: ","".join(sorted(set(name_list)))
NameList = ['이유덕' , '이재영', '권종표', '이재영', '박민호', '강상희', '이재영', '김지완', '최승혁', '이성연', '박영서', '박민호', '전경헌', '송정환', '김재성', '이유덕', '전경헌']
def CheckLastName(Last):
iter = 0
for i in NameList:
if i[0] == Last:
iter += 1
return iter
def CheckName(FullName):
iter = 0
for i in NameList:
if i == FullName:
iter += 1
return iter
print("박씨인 사람은 ", CheckLastName('박'), "명")
print("이씨인 사람은 ", CheckLastName('이'), "명")
print("이재영씨는 ", CheckName('이재영'), "명")
NewNameList = list(set(NameList))
print(NewNameList)
NewNameList.sort()
print(NewNameList)
Sub main()
Dim ns As New List(Of String)
ns.AddRange(Split(Console.ReadLine, ","))
Dim cnt_kim As Integer = 0
Dim cnt_e As Integer = 0
Dim cnt_ejy As Integer = 0
ns = ns.Select(
Function(n As String)
cnt_kim += IIf(n.StartsWith("김"), 1, 0)
cnt_e += IIf(n.StartsWith("이"), 1, 0)
cnt_ejy += IIf(n = "이재영", 1, 0)
Return n
End Function).Distinct.OrderBy(Function(n As String) n).ToList
Console.WriteLine("김씨: {0} 명", cnt_kim)
Console.WriteLine("이씨: {0} 명", cnt_e)
Console.WriteLine("이재영: {0} 명", cnt_ejy)
Console.WriteLine(String.Join(",", ns))
Console.ReadLine()
End Sub
// 1. 성에 해당하는 사람의 인원 계산
public static int searchSung(String names, String sung){
int num = 0;
StringTokenizer st = new StringTokenizer(names,",");
while(st.hasMoreTokens()){
String name = st.nextToken();
String first = name.substring(0,1);
if(sung.equals(first))
num++;
}
return num;
}
// 2. 해당하는 이름이 몇번 반복 되는지 계산
public static int findName(String names, String target) {
StringTokenizer st = new StringTokenizer(names,",");
int num = 0;
while(st.hasMoreTokens()){
String name = st.nextToken();
if(name.equals(target))
num++;
}
return num;
}
//3,4 중복을 제거한 이름 오름차순 정렬
public static void distinctStr(String names) {
StringTokenizer st = new StringTokenizer(names,",");
ArrayList<String> distinctNames = new ArrayList<String>();
while(st.hasMoreTokens()){
String name = st.nextToken();
if(!distinctNames.contains(name))
distinctNames.add(name);
}
// 오름차순 정렬
Collections.sort(distinctNames);
for(String name: distinctNames)
System.out.println(name);
}
음...메서드 세개나 만들었는데..
여기서 하나로 만드는거 보고 ㅂㄹ을 탁치고 갑니다.
static void Main(string[] args)
{
string probleam = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌";
List<string> list = probleam.Split(',').ToList();
Console.WriteLine("1.김씨와 이씨는 몇 명 인가요 ? {0}", count(0, '김', probleam) + count(0, '이', probleam));
Console.WriteLine("2.이재영 이라는 이름이 몇 번 반복되나요 ? {0}",count("이재영",probleam));
list = list.Distinct().ToList();
Console.WriteLine("3. 중복을 제거한 이름을 출력하세요 : ");
foreach(string s in list)
{
Console.WriteLine(s);
}
list.Sort();
Console.WriteLine("4.중복을 제거한 이름을 오름차순으로 정렬하여 출력하세요. :");
foreach (string s in list)
{
Console.WriteLine(s);
}
}
static int count(int index,char c,string s)
{
int count = 0;
string[] value = s.Split(',');
foreach(string str in value)
{
if(str[index] == c)
{
count++;
}
}
return count;
}
static int count(string c, string s)
{
int count = 0;
string[] value = s.Split(',');
foreach (string str in value)
{
if (str == c)
{
count++;
}
}
return count;
}
Using CSharp
using System;
using System.Collections.Generic;
using System.Linq;
namespace simsim {
class Program {
static void Main(string[] args) {
string names = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌";
string[] arrNames = names.Split(new char[]{','}, StringSplitOptions.RemoveEmptyEntries);
Console.WriteLine("Original Data : ");
foreach (string item in arrNames) {
Console.WriteLine(item);
}
int lastNameKimCnt = 0, lastNameLeeCnt = 0, nameIsLeeJaeYoungCnt = 0;
foreach (string item in arrNames) {
if (item[0] == '김') {
lastNameKimCnt++;
}
else if (item[0] == '이') {
lastNameLeeCnt++;
}
if (item.Contains("이재영"))
nameIsLeeJaeYoungCnt++;
}
Console.WriteLine("");
Console.WriteLine("Questions");
Console.WriteLine("0. Names all count number : {0}", arrNames.Length);
Console.WriteLine("1-1. Count number (Last name is Kim) : {0}", lastNameKimCnt);
Console.WriteLine("1-2. Count number (Last name is LEE) : {0}", lastNameLeeCnt);
Console.WriteLine("2. Count number (Name is LEE JAE YOUNG) : {0}", nameIsLeeJaeYoungCnt);
Console.WriteLine("press enter.");
Console.ReadLine();
IEnumerable<string> reduceDup = arrNames.Distinct();
Console.WriteLine("3. reduce duplication names : ");
foreach (string item in reduceDup) {
Console.WriteLine(item);
}
Console.WriteLine("press enter.");
Console.ReadLine();
reduceDup = reduceDup.OrderByDescending(item => item);
Console.WriteLine("4. order names : ");
foreach (string item in reduceDup) {
Console.WriteLine(item);
}
Console.WriteLine("press enter. program is over.");
Console.ReadLine();
}
}
}
echo -n "이씨는 "; echo -n "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌" | sed 's/,/\n/g' | grep -c "이";echo "명 입니다."; echo -n "김 씨는 "; echo -n "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌" | sed 's/,/\n/g' | grep -c "김";echo -n "명 입니다."
자바 연습입니다.
import java.util.HashSet;
import java.util.TreeSet;
public class ArrayListTest {
public static void main(String[] args) {
String name = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌";
String[] strArray = name.split(",");
HashSet<String> hs = new HashSet<String>();
TreeSet<String> ts = new TreeSet<String>();
int kim=0, lee = 0, ljy = 0;
for(int i=0; i<strArray.length; i++){
if( strArray[i].charAt(0)=='김' ) kim++;
else if(strArray[i].charAt(0) == '이') lee++;
if( strArray[i].contains("이재영")) ljy++;
hs.add(strArray[i]);
ts.add(strArray[i]);
}
System.out.println("1. 김씨는 "+kim+"명, 이씨는 "+lee+"명 입니다.");
System.out.println("2. 이재영씨의 이름은 총 "+ljy+"번 반복됩니다.");
System.out.println("3. 중복을 제거한 이름은 " + hs +"입니다." );
System.out.println("4. 중복을 제거한 이름을 오름차순으로 정렬하면 " + ts + "입니다.");
}
}
파이썬입니다.
names = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌"
names_list = names.split(',')
names_set = set(names_list)
def count(list, string):
cnt = 0
if len(string) == 1:
for name in list:
if name[0:1] == string:
cnt += 1
else:
cnt = list.count(string)
return cnt
print("1. 김씨와 이씨는 각각 몇 명 인가요?\n\t김씨: "
+ str(count(names_list, "김")) + "명, 이씨: "
+ str(count(names_list, "이")) + "명")
print("2. '이재영'이란 이름이 몇 번 반복되나요?\n\t"
+ str(count(names_list, "이재영")) + "번")
print("3. 중복을 제거한 이름을 출력하세요.\n\t" + str(names_set))
print("4. 중복을 제거한 이름을 오름차순으로 정렬하여 출력하세요.\n\t"
+ str(sorted(names_set)))
<?php
$var = '이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌';
$names = explode(',', $var);
$kim_cnt = 0;
$lee_cnt = 0;
$ljy_cnt = 0;
$arr = array();
foreach ($names as $index => $name) {
if(mb_substr($name, 0, 1, 'utf-8') == '김') {
$kim_cnt++;
}else if (mb_substr($name, 0, 1, 'utf-8') == '이') {
$lee_cnt++;
}
if($name == '이재영') $ljy_cnt++;
if(!in_array($name, $arr)) array_push($arr, $name);
}
echo '김씨 : '.$kim_cnt.'<br>';
echo '이씨 : '.$lee_cnt.'<br>';
echo '이재영 : '.$ljy_cnt.'<br>';
echo '중복제거 : ';
print_r($arr);
echo '<br>';
asort($arr);
echo '오름차순 : ';
print_r($arr);
?>
python3입니다.
#-*- coding: utf-8 -*-
names = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌"
names = names.split(",")
kims = list(filter(lambda x: x.startswith("김"), names))
lees = list(filter(lambda x: x.startswith("이"), names))
print ("%d %d" % (len(kims), len(lees)))
print ("%d" % names.count("이재영"))
print (set(names))
lst = list(set(names))
lst.sort()
print (lst)
#-*-coding:utf-8-*-
names = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌".split(",")
print(len(list(filter(lambda x:x[0] == "이" or x[0] == "김", names))))
print(names.count("이재영"))
uname = list(set(names))
print(uname)
uname.sort()
print(uname)
names = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌".split(",")
print(len(list(filter(lambda x:x[0]=="이" or x[0]=="김", names))))
print(names.count("이재영"))
uniq_names = list(set(names)) print(uniq_names)
uniq_names.sort() print(uniq_names)
names = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌".split(",")
print(len(list(filter(lambda x:x[0]=="이" or x[0]=="김", names))))
print(names.count("이재영"))
uniq_names = list(set(names)) print(uniq_names)
uniq_names.sort() print(uniq_names)
#-*- coding: utf-8 -*-
n='이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌'.split(',')
print "김씨:",sum(x[:3]=='김' for x in n)
print "이씨:",sum(x[:3]=='이' for x in n)
print "이재영의 반복횟수:",n.count('이재영')
print "중복제거:",','.join(set(n))
print "중복제거후 정렬:",','.join(sorted(list(set(n))))
으 사실 한국어 변형해서 풀어야 하는데... 한국어 변형법을 몰라서 영문으로 하였습니다.
# -*- coding: utf-8 -*-
def repeat1(input1):
a = input1.split(",")
count_lee = 0
count_kim = 0
for i in a:
if i[0] =='L':
count_lee +=1
if i[0] =="K":
count_kim +=1
return count_lee, count_kim
print repeat1(input1)
---------------------------------------
def howmanyrepeat(input2):
a = input1.split(",")
return a.count("LJY")
print howmanyrepeat(input2)
---------------------------------------
def deleterepeat(input3):
a = input1.split(",")
o=[]
for q in a:
if q not in o:
o.append(q)
o.sort(reverse=False)
return o
print deleterepeat(input3)
#coding: CP949
def counting1(): # 1번 풀이
data="이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌"
List=data.split(',')
num_Kim=""
num_Yi=""
for i in List:
if i[0] =="김":
num_Kim=num_Kim+i[0]
elif i[0] =="이":
num_Yi=num_Yi+i[0]
else:
continue
return ("김 씨는 %s명, 이 씨는 %s명." % (len(num_Kim),len(num_Yi)))
def counting2(): # 2번 풀이
data="이유덕,이재영,권종표,이재영,박민호\
,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌"
List=data.split(",")
n=0
for j in List:
if j == "이재영":
n=n+1
else:
continue
return ('이재영 사람 %d명.' % n)
def counting3(): # 3번 풀이
data="이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌"
List=data.split(",")
K=set(List)
return K
def counting4(): # 4번 풀이
data="이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌"
List=data.split(",")
K=set(List)
result=sorted(list(K))
return result
Python 초짜 댓글 달아봅니다
자바입니다.. 허접하지만..```{.java} @Test public void t1() { String[] arr = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌".split(",");
// 1번
int seq = 0;
for (String str : arr) {
char[] c = str.toCharArray();
if ('김' == c[0] || '이' == c[0]) {
seq++;
}
}
System.out.println(seq + "명");
// 2번
int seq2 = 0;
for (int i = 0; i < arr.length; i++) {
if ("이재영".contains(arr[i])) {
seq2++;
}
}
System.out.println(seq2 + "번");
// 3번
Map<String, String> map = new HashMap<>();
for (String str : arr) {
map.put(str, str);
}
Object[] arr2 = map.keySet().toArray();
for (int i = 0; i < arr2.length; i++) {
if (i != arr2.length -1) {
System.out.print(arr2[i] + ",");
} else {
System.out.println(arr2[i]);
}
}
// 4번
Arrays.sort(arr2);
for (int i = 0; i < arr2.length; i++) {
if (i != arr2.length -1) {
System.out.print(arr2[i] + ",");
} else {
System.out.print(arr2[i]);
}
}
}
```
s = '이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌'.split(',')
t1 = {'김':0,'이':0}; t2 = len(list(x for x in s if x=='이재영')); t3 = list(set(s)); t4 = sorted(t3)
for x in t3:
if x[0] == '김' or x[0] == '이':t1[x[0]] += 1
for i in range(1,5):eval('print(t'+str(i)+')')
순서대로 출력됩니다. 파이썬 3.5.1
//1. 김씨와 이씨는 각각 몇 명 인가요?
int[] findKimLee(String s) {
String [] arr = splitName(s);
int [] result = new int[2];
int kimCount = 0;
int leeCount = 0;
for(int i=0; i<arr.length; i++) {
if(arr[i].charAt(0) == '김') {
kimCount++;
}
else if(arr[i].charAt(0) == '이') {
leeCount++;
}
}
result[0] = kimCount;
result[1] = leeCount;
return result;
}
//2. "이재영"이란 이름이 몇 번 반복되나요?
int repeatNameCount(String s, String name) {
String [] arr = splitName(s);
int count = 0;
for(int i=0; i<arr.length; i++) {
System.out.println(arr[i]);
if(arr[i].equals(name)) {
count++;
}
}
return count;
}
//3. 중복을 제거한 이름을 출력하세요.
Set<String> romoveDupName(String s) {
String [] arr = splitName(s);
Set<String> nameSet = new HashSet<String>();
for(int i=0; i<arr.length; i++) {
nameSet.add(arr[i]);
}
return nameSet;
}
//4. 중복을 제거한 이름을 오름차순으로 정렬하여 출력하세요.
ArrayList<String> romoveDupNameAsc(String s) {
Set<String> nameSet = romoveDupName(s);
ArrayList<String> nameList = new ArrayList<String>(nameSet);
Collections.sort(nameList);
return nameList;
}
String[] splitName(String s) {
String [] arr = new String[s.length()];
arr = s.split(",");
return arr;
}
java 코드
```{.java} import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.Iterator; import java.util.List;
public class ddd {
public static void main(String[] args) {
String input="이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌";
HashSet<String> hs = new HashSet<String>();
int countK=0;
int countL=0;
int countLJY=0;
String []arr=input.split(",");
Arrays.sort(arr);
for(int i=0; i<arr.length; i++){
hs.add(arr[i]);
if(arr[i].startsWith("김")){
countK++;
}
else if(arr[i].startsWith("이")){
countL++;
}
if(arr[i].equals("이재영")){
countLJY++;
}
}
System.out.println("김씨="+countK+" 이씨="+countL+" 이재영="+countLJY);
List<String> sortedList = new ArrayList(hs);
Collections.sort(sortedList);
Iterator hi = sortedList.iterator();
while(hi.hasNext()){
System.out.print(hi.next()+" ");
}
System.out.println("");
}
}
초보자라 메모리 낭비하거나 불필요한 코드가 있다면 좋은 조언부탁드려요
파이썬3.4입니다.
a = '이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌'
#1
b = [x[0:1] for x in a.split(',')]
b.count('김')
b.count('이')
#2
a.count('이재영')
#3
set(a.split(',')) #중복제거는 집합함수인 set을 이용
#4
sorted(list(set(a.split(','))))
파이썬3.5.1
names = input().split(',')
c11 = 0
c12 = 0
for i in names:
if i[0] == '김':
c11 += 1
elif i[0] == '이':
c12 += 1
c2 = names.count('이재영')
newn = list(set(names))
newn2 = sorted(newn)
print('1. 김', c11, '번 / 이', c12, '번')
print('2. 이재영', c2, '번')
print('3.', ','.join(newn))
print('4.', ','.join(newn2))
'''
INPUT : 이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌
OUTPUT:
1. 김 2 번 / 이 6 번
2. 이재영 3 번
3. 송정환,이성연,최승혁,박민호,박영서,김재성,전경헌,권종표,이유덕,강상희,김지완,이재영
4. 강상희,권종표,김재성,김지완,박민호,박영서,송정환,이성연,이유덕,이재영,전경헌,최승혁
'''
Ruby
str = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연," +
"박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌"
names = str.split(/,/)
# 순서대로 1,2,3,4번 각각의 출력.
puts names.select {|n| n[0]=~/[김|이]/ }.group_by {|c|c[0]}.map {|f,v| "#{f}: #{v.size}" }
puts names.count {|n| n=="이재영" }
puts names.uniq.join
puts names.uniq.sort
data="이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌".split(",")
kim=0
lee=0
jae=0
sum=set(data)
adder=0
for i in data:
if i[0]=="김":
kim+=1
if i[0]=="이":
lee+=1
if i=="이재영":
jae+=1
print(kim)
print(lee)
print(jae)
for i in data:
for j in data:
if i == j:
adder += 1
if adder >= 2:
data.remove(i)
adder = 0
adder = 0
print(data)
print(sorted(data))
Python
data = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌"
data_list = data.split(",")
kim = 0
lee = 0
for name in data_list:
if name[0] == '이':
lee += 1
elif name[0] == '김':
kim += 1
print("1. Kim is ", kim, "Lee is ", lee)
print("2. Lee Jaeyoung is ", data_list.count("이재영"))
filted_list = list(set(data_list))
print("3. ", filted_list)
filted_list.sort()
print("4. ", filted_list)
name=["유덕","이재영","권종표","이재영","박민호","강상희","이재영","김지완","최승혁","이성연","박영서","박민호","전경헌","송정환","김재성","이유덕","전경헌"]
# 1. 김씨와 이씨는 각각 몇 명 인가요?
kim = 0
lee = 0
for a in range(len(name)):
if(name[a][0] == '김'):
kim +=1
if(name[a][0] == '이'):
lee +=1
print("성이 김씨는 ", kim, "명")
print("성이 김씨는 ", lee, "명")
# 2. "이재영"이란 이름이 몇 번 반복되나요?
count_lee=0
for a in range(len(name)):
if(name[a]=='이재영'):
count_lee+=1
print("이재영은 ",count_lee,"번 반복")
# 3. 중복을 제거한 이름을 출력하세요.
name=["유덕","이재영","권종표","이재영","박민호","강상희","이재영","김지완","최승혁","이성연","박영서","박민호","전경헌","송정환","김재성","이유덕","전경헌"]
b = len(name)
for a in range(b):
for b in range(1,b-1):
if(name[a]==name[b]):
del name[b]
b-=1
print(name)
# 4. 중복을 제거한 이름을 오름차순으로 정렬하여 출력하세요.
print(sorted(name))
>>> s = '이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌'
>>> s = ',' + s
>>> s.count(",이") + s.count(",김")
8
>>> s.count("이재영")
3
>>> print(",".join(set(s.split(','))))
이유덕,최승혁,김지완,전경헌,이재영,박민호,이성연,강상희,김재성,송정환,권종표,박영서
>>> print(",".join(sorted(list(set(s.split(','))))))
강상희,권종표,김재성,김지완,박민호,박영서,송정환,이성연,이유덕,이재영,전경헌,최승혁
파이썬 3
names = '이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌'
#1.김씨와 이씨는 각각 몇 명 인가요?
#2."이재영"이란 이름이 몇 번 반복되나요?
#3.중복을 제거한 이름을 출력하세여.
#4.중복을 제거한 이름을 오름차순으로 정렬하여 출력하세요.
def string(x):
a = ''
for i in x:
a = a+i
return a
def ans1(x):
kim = 0
lee = 0
for i in x:
lst = list(i)
if lst[0] == '김':
kim += 1
elif lst[0] == '이':
lee += 1
return kim, lee
def ans2(x):
ans=0
for i in x:
if i == '이재영':
ans += 1
return ans
def ans3(x):
return set(x)
def ans4(x):
return list(set(x)).sort()
repeat = 0
lst_names = list(names)
for i in lst_names:
if i == ',':
lst_names[repeat] = ' '
repeat += 1
names_2 = string(lst_names)
lst_names2 = list(names_2.split())
print(ans1(lst_names2))
print(ans2(lst_names2))
print(ans3(lst_names2))
print(ans4(lst_names2))
Python
#-*- coding: utf-8 -*-
import re
inp = '이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌'
name_list = inp.split(',')
target_name = '이재영'
def find_last_name(last_name, name_list):
find_cnt = 0
for name in name_list:
find_list = re.findall(last_name, name)
find_cnt += len(find_list)
return find_cnt
def print_list(name_list):
str = ''
cnt = 1
for name in name_list:
if cnt < len(name_list):
str += name + ', '
cnt += 1
else:
str += name
cnt += 1
print '\t' + str
num_kim = find_last_name('김', name_list)
num_lee = find_last_name('이', name_list)
new_name_list = list(set(name_list))
print ("1. 김씨는 {0}명, 이씨는 {1}명입니다.".format(num_kim, num_lee))
print ("2. 이재영이란 이름은 {0}번 반복됩니다.".format(name_list.count(target_name)))
print ("3. 중복을 제거한 리스트는 다음과 같습니다.")
print_list(new_name_list)
print ("4. 중복을 제거하고 오름차순으로 정리한 리스트는 다음과 같습니다.")
new_name_list.sort()
print_list(new_name_list)
파이썬 3.5로 작성되었습니다.
string = ['이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌']
name = string[0].split(',')
new = []
kim, lee, ljy = 0, 0, 0
for i in range(len(name)):
if name[i][0] == "김": kim += 1
if name[i][0] == "이": lee += 1
if name[i] == "이재영": ljy += 1
if name[i] in new: continue
new.append(name[i])
print("1. 김씨 =", kim, "이씨 =", lee)
print("2. 이재영 =", ljy)
print("3.", new)
new.sort()
print("4.", new)
다른 분들의 답을 참고한 결과 리스트 count하는 것과 중복검사를 위해 set을 사용한 것이 더 간편하겠더군요.
부족한 점이 많습니다. 감사합니다.
python 3.5.1로 풀었습니다.
names = '''이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌'''
name_list = names.split(',')
#1
print('김 : {}'.format(len([name for name in name_list if name[0] == '김'])))
print('이 : {}'.format(len([name for name in name_list if name[0] == '이'])))
#2
print(name_list.count('이재영'))
#3
print(list(set(name_list)))
#4
print(sorted(list(set(name_list))))
package main
import (
"fmt"
"strings"
"sort"
)
func main() {
names := strings.Split("이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌", ",")
// count of 김 || 이
count := 0
for _, name := range names {
if strings.HasPrefix(name, "김") || strings.HasPrefix(name, "이") {
count++
}
}
fmt.Println("김 & 이: ", count)
// count of 이재영
count = 0
for _, name := range names {
if name == "이재영" {
count++
}
}
fmt.Println("이재영: ", count)
// remove dup
maps := map[string]bool{}
for _, name := range names {
maps[name] = true
}
sep := ""
for k, _ := range maps {
fmt.Print(sep, k)
sep = ","
}
fmt.Println()
// sort
keys := []string{}
for k, _ := range maps {
keys = append(keys, k)
}
sort_keys := sort.StringSlice(keys)
sort_keys.Sort()
sep = ""
for _, v := range sort_keys {
fmt.Print(sep, v)
sep = ","
}
fmt.Println()
}
기본 문법 공부중입니다^^ 값이 제대로 나오는것도 감지덕지네요 ㅎ
python3.5
names = ["이유덕","이재영","권종표","이재영","박민호","강상희","이재영","김지완","최승혁","이성연","박영서","박민호","전경헌","송정환","김재성","이유덕","전경헌"]
kim_cnt = 0
lee_cnt = 0
leejy_cnt =0
distNames = []
for name in names:
if not distNames or name not in distNames:
distNames.append(name)
if name[0:1] =="김":
kim_cnt += 1
elif name[0:1] =="이":
lee_cnt += 1
leejy_cnt = names.count("이재영")
print("# 김씨와 이씨는 각각 몇 명 인가요?\n"+ str(kim_cnt)+"\n"+str(lee_cnt))
print("\"이재영\"이란 이름이 몇 번 반복되나요?\n"+str(leejy_cnt))
print("중복을 제거한 이름을 출력하세요.\n"+str(distNames))
distNames.sort()
print("중복을 제거한 이름을 오름차순으로 정렬하여 출력하세요.\n"+str(distNames))
김씨와 이씨는 각각 몇 명 인가요? 2 6
"이재영"이란 이름이 몇 번 반복되나요? 3
중복을 제거한 이름을 출력하세요. ['이유덕', '이재영', '권종표', '박민호', '강상희', '김지완', '최승혁', '이성연', '박영서', '전경헌', '송정환', '김재성']
중복을 제거한 이름을 오름차순으로 정렬하여 출력하세요. ['강상희', '권종표', '김재성', '김지완', '박민호', '박영서', '송정환', '이성연', '이유덕', '이재영', '전경헌', '최승혁']
Process finished with exit code 0
자바입니다. 남들보다 제소스가 많이 긴거같은 느낌이 ㅠㅠㅠ
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.Set;
public class 사이냅소프트면접문제 {
// 김씨와 이씨는 각각 몇 명 인가요?
// "이재영"이란 이름이 몇 번 반복되나요?
// 중복을 제거한 이름을 출력하세요.
// 중복을 제거한 이름을 오름차순으로 정렬하여 출력하세요.
public static void main(String[] args) {
String names = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌";
String splitNames[] = names.split(",");
getCountOfKimAndLee(splitNames);
getCountOfName(splitNames);
removeDuplicatedName(splitNames);
sortedRemoveDuplicatedName(splitNames);
}
public static void getCountOfKimAndLee(String[] splitNames){
int kim = 0;
int lee = 0;
for(String name : splitNames) {
if(name.charAt(0) == '김') kim++;
if(name.charAt(0) == '이') lee++;
}
System.out.println("김씨는 "+kim+"명이고, 이씨는 "+lee+"명입니다.");
}
public static void getCountOfName(String[] splitNames) {
int ljy = 0;
for(String name : splitNames) {
if("이재영".equals(name)) {
ljy++;
}
}
System.out.println("이재영이란 이름은 "+ljy+"번 반복됩니다.");
}
public static void removeDuplicatedName(String[] splitNames){
Set<String> set = new LinkedHashSet<>();
for(String name : splitNames) {
set.add(name);
}
System.out.println(set);
}
public static void sortedRemoveDuplicatedName(String[] splitNames){
Set<String> set = new LinkedHashSet<>();
for(String name : splitNames) {
set.add(name);
}
Iterator<String> it = set.stream().sorted().iterator();
while(it.hasNext()){
System.out.print(it.next()+" ");
}
}
}
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
public class test {
public static void main(String[] argv) {
String str = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌";
String[] listStr = str.split(",");
int countLee = 0;
int countKim = 0;
int countSameName = 0;
Set<String> setStr = new HashSet<String>();
for(int i =0 ; i<listStr.length; i++){
String tempStr = listStr[i];
if(tempStr.substring(0,1).equals("이")){
countLee++;
}
if(tempStr.substring(0,1).equals("김")){
countKim++;
}
if(tempStr.equals("이재영")){
countSameName++;
}
setStr.add(tempStr);
}
System.out.println("이씨는 " + countLee + "명 입니다.");
System.out.println("김씨는 "+ countKim+ "명 입니다.");
System.out.println("이재영이란 이름은 "+countSameName +"명 있습니다.");
ArrayList<String> nameList = new ArrayList<String>(setStr);
Collections.sort(nameList);
System.out.println(nameList);
}
}
package 코딩도장; //중복된 이름 제거, 정렬 import java.util.ArrayList; import java.util.Collections;
public class Q9 {
public static void main(String[] args) {
String insert = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌";
String gg[] = insert.split(",");
String zz[]= insert.split("");
int jyCount=0;
int kimCount=0;
int leeCount=0;
int k=0; int j=0;
ArrayList<String> list1 = new ArrayList<String>();
for(int i=0;i<zz.length;i++)
{
if(zz[i].equals("김"))
{
kimCount++;
}
else if(zz[i].equals("이"))
{
leeCount++;
}
}
for(int i=0;i<gg.length;i++)
{
if(gg[i].equals("이재영"))
{
jyCount++;
}
}
for(int i=0;i<gg.length;i++)
{
//배열에 없다면 저장
if(!list1.contains(gg[i]))
{
list1.add(gg[i]);
}
}
System.out.println("김씨 : " + kimCount);
System.out.println("이씨 : " + leeCount);
System.out.println("이재영 : "+jyCount);
System.out.println("중복을 제거한 이름 : ");
System.out.println(list1);
System.out.println("중복을 제거한 이름 정렬 : ");
Collections.sort(list1);
System.out.println(list1);
}
}
자바로 코딩
출력
이씨 카운트 :: ==> 6
김씨 카운트 :: ==> 2
이재영 반복횟수 :: ==> 3
[김재성, 김지완, 권종표, 박민호, 박영서, 송정환, 이유덕, 이재영, 이성연, 전경헌, 강상희, 최승혁]
public static void main(String[] args){
try{
String[] nameArray = new String[]{ "이유덕" ,"이재영" ,"권종표" , "이재영" ,
"박민호" ,"강상희" ,"이재영" , "김지완" ,
"최승혁" ,"이성연" ,"박영서" , "박민호" ,
"전경헌" ,"송정환" ,"김재성" , "이유덕" ,
"전경헌" };
ArrayList<String> array = new ArrayList<>(Arrays.asList(nameArray));
Iterator<String> nameIter = array.iterator();
HashSet<String> sortArray = new HashSet<String>(array);
int nameChk = 0;
int leeCnt = 0; // 이씨 카운트
int kimCnt = 0; // 김씨 카운트
while( nameIter.hasNext()){
// 1. 김,이 씨 만 출력
String name = nameIter.next();
int ch = (int)name.charAt(0);
if ( ch == 51060 ){
leeCnt++;
}
if( ch == 44608 ){
kimCnt++;
}
// 2. 이재영 반복 횟수
if( "이재영".equals(name)){
nameChk++;
}
} // while
System.out.println("이씨 카운트 :: ==> " + leeCnt);
System.out.println("김씨 카운트 :: ==> " + kimCnt);
System.out.println("이재영 반복횟수 :: ==> " + nameChk);
// 3. 중복제거 오름차순
array.clear();
array.addAll(sortArray);
System.out.println(sortArray);
}catch(Exception e){
e.printStackTrace();
}
}
names='이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌'
namelist=names.split(',')
이=0
김=0
이재영_=0
for i in namelist :
if i[0] == '이':
이+=1
elif i[0] == '김':
김+=1
print("이 %d , 김 %d "%(이,김))
for i in namelist :
if i == "이재영":
이재영_+=1
print("이재영 반복 횟수 : %d"%이재영_)
for i in list(set(namelist)):
print(i,end=" ")
print("")
for i in sorted(list(set(namelist))):
print(i,end=" ")
Python 3.5.2
public static void main(String[] args) {
String[] arr = {"이유덕","이재영","이유덕","이재영","권종표","이재영","박민호","강상희","이재영","김지완","최승혁","이성연","박영서","박민호","전경헌","송정환","김재성","이유덕","전경헌"};
int lee=0,kim=0,leeJae=0;
ArrayList<String> list = new ArrayList<String>();
for(int i=0; i<arr.length-i; i++){
list.add(arr[i]);
if((list.get(i).substring(0,1)).equals("이")){lee++;}
if((list.get(i).substring(0,1)).equals("김")){kim++;}
if(list.get(i).equals("이재영"))leeJae++;
}
System.out.println("이씨성의 수 : "+lee+", "+"김씨성의 수 : "+kim+", "+"이재영씨 이름수 : "+leeJae);
for(int i=0; i<list.size(); i++){
for(int j=0; j<i; j++){
if(list.get(i) == list.get(j))
list.remove(i);//중복제거
}
}
Collections.sort(list);//오름차순
System.out.println(list);
}
public class Test1 {
public static void main(String[] args) {
// 김씨와 이씨는 각각 몇명인가요 ?
// "이재영"이란 이름이 몇번 반복되나요 ?
// 중복을 제거한 이름을 출력하세요
// 중복을 제거한 이름을 오름차순으로 청렬하여 출력하세요 .
// "이유덕", "이재영", "권종표", "이재영", "박민호", "강상희", "이재영",
// "김지완", "최승혁", "이성연", "박영서", "박민호", "전경헌", "송정환", "김재성", "이유덕",
// "전경헌"
int kimcnt = 0;
int leecnt = 0;
int ljy = 0;
ArrayList<String> list = new ArrayList<String>();
list.add("이유덕");
list.add("이재영");
list.add("권종표");
list.add("이재영");
list.add("박민호");
list.add("강상희");
list.add("이재영");
list.add("김지완");
list.add("최승혁");
list.add("이성연");
list.add("박영서");
list.add("박민호");
list.add("전경헌");
list.add("송정환");
list.add("김재성");
list.add("이유덕");
list.add("전경헌");
for (int i = 0; i < list.size(); i++) {
if (list.get(i).substring(0, 1).equals("김")) {
kimcnt++; // 김씨 카운트
}
if (list.get(i).substring(0, 1).equals("이")) {
leecnt++; // 이씨 카운트
}
if (list.get(i).equals("이재영")) {
ljy++; // 이재영 카운트
}
}
System.out.println("김씨:" + kimcnt + "이씨:" + leecnt + "이재영:" + ljy);
for(int i = 0 ; i < list.size() ; i++){
for(int j = 0 ; j < list.size() ; j++){
if(list.get(i) == list.get(j)){
list.remove(i); // 중복 제거
}
}
}
for(int i = 0 ; i < list.size() ; i++){
System.out.println(list.get(i)); // 중복제거 이름 나열
}
Collections.sort(list);
System.out.println(list);
Linq 입니다. 알고리즘을 못해서ㅠㅠ Linq로..ㅎㅎ
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication18
{
class Program
{
//김씨와 이씨는 각각 몇 명 인가요?
//"이재영"이란 이름이 몇 번 반복되나요?
//중복을 제거한 이름을 출력하세요.
//중복을 제거한 이름을 오름차순으로 정렬하여 출력하세요.
static void Main(string[] args)
{
string names = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌";
string[] namesSplit = names.Split(',');
var lastNameKim = from lastNameKimItem in namesSplit where
lastNameKimItem.StartsWith("이") select lastNameKimItem;
var lastNameLee = from lastNameLeeItem in namesSplit where
lastNameLeeItem.StartsWith("김") select lastNameLeeItem;
var NameJaeYoung = from NameJaeYoungItem in namesSplit where
NameJaeYoungItem.Equals("이재영") select NameJaeYoungItem;
var nameSplitDistinct = (from nameSplitDistinctItem in namesSplit
select nameSplitDistinctItem).Distinct().ToList();
var nameSplitDistinctAsc = (from nameSplitDistinctItem in namesSplit
orderby nameSplitDistinctItem select nameSplitDistinctItem).Distinct().ToList();
Console.WriteLine("김:" + lastNameKim.Count());
Console.WriteLine("이:" + lastNameLee.Count());
Console.WriteLine("이재영:" + NameJaeYoung.Count());
Console.WriteLine("중복제거이름");
for (int i = 0; i < nameSplitDistinct.Count; i++ )
Console.WriteLine(nameSplitDistinct[i]);
Console.WriteLine("중복제거 오름차순");
for (int i = 0; i < nameSplitDistinctAsc.Count; i++ )
Console.WriteLine(nameSplitDistinctAsc[i]);
}
}
}
names = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌"
nameList = names.split(",")
nameList.sort()
name = [nameList[0]]
kim = 0
lee = 0
ljy = 0
for i in nameList:
if i[0] == "이":
lee += 1
if i == "이재영":
ljy += 1
elif i[0] == "김":
kim += 1
if name[-1] != i:
name.append(i)
print ("김씨 : " + str(kim) + "명\n이씨 : " + str(lee) + "명\n이재영 : " + str(ljy) + "명")
for i in name:
print (i)
Python 3
target = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌".split(",")
kim = 0
lee = 0
for x in target:
if x[0] == "김":
kim = kim + 1
elif x[0] == "이":
lee = lee + 1
targs = set(target)
print("김씨 : {0}명, 이씨 : {1}명".format(kim, lee))
print("중복 횟수 : {0}".format(len(target) - len(targs) + 1))
print("중복 제거 : ", end="")
print(targs)
print("중복 제거 정렬 : ", end="")
targs = list(targs)
targs.sort()
print(targs)
L = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경현"
f_list=L.split(',')
Lee_count=0
Kim_count=0
jy_count=0
for i in f_list:
if i[0]=='이':
Lee_count+=1
if i[0]=='김':
Kim_count+=1
if i=="이재영":
jy_count+=1
print "이씨:"+str(Lee_count)+"명 김씨:"+str(Kim_count)+"명 이재영:"+str(jy_count)+"명"
n_list = set(f_list)
print n_list
n_list = sorted(n_list)
print n_list
names = ['이유덕','이재영','권종표','이재영','박민호','강상희','이재영','김지완','최승혁','이성연','박영서','박민호','전경헌','송정환','김재성','이유덕','전경헌']
q1 = [name[0] for name in names]
print( 'count 김 : ' + str(q1.count('김')) )
print( 'count 이 : ' + str(q1.count('이')) )
print()
print( 'count 이재영 : ' + str(names.count('이재영')) )
print()
print( set(names) )
print()
names.sort()
names.reverse()
print( set(names) )
count 함수를 사용하면 간단하게 풀리네요
lists="이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌".split(",")
#1
a=[i[0] for i in lists]
print("김씨 %d명 이씨 %d명"%(a.count("김"),a.count("이")))
#2
print(lists.count("이재영"))
#3
print(list(set(lists)))
names=list(set(lists))
#4
names.sort()
print(names)
def countName(input):
splitList = input.split(',')
#count kim and lee
countK = 0
countL = 0
for name in splitList:
if name[0] == "김":
countK += 1
elif name[0] == "이":
countL += 1
dict = {}
countLJY=0
for name in splitList:
if name in dict:
dict[name] += 1
else:
dict[name] = 1
#이재영이 이름 나온 숫자
countLJY = dict["이재영"]
#중복을 제거한 이름 list
nameSet = set(dict.keys())
namelist = list(nameSet)
namelist.sort()
return countK, countL, countLJY, nameSet, namelist
a = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌"
print(countName(a))
#define _CRT_SECURE_NO_WARNINGS
#include <windows.h>
#include <stdio.h>
#define totalname 17
#define namesize 7
char str[] = { "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌" };
int main(void) {
int k = 0, l = 0, LJY = 0;
int total = sizeof(str);
char temp[namesize] = { 0, }; //change buff
char* rst = NULL;
rst = new char[sizeof(str) / sizeof(char)];
strcpy(rst, str);
for (int i = 0; i < sizeof(str); i += namesize) {
if (!strncmp(str + i, "김", 2)) {
k++;
}
if (!strncmp(str + i, "이", 2)) {
l++;
}
if (!strncmp(str + i, "이재영", 6)) {
LJY++;
}
}
printf("김씨 = %d명\n이씨 = %d명\n이재영 = %d명\n", k, l, LJY);
for (int i = 0; i < total; i += namesize) {
for (int j = i + namesize; j < total; j += namesize) {
if (!strncmp(rst + i, rst + j, 6)) {
memmove(rst + j, rst + j + namesize, total - (j + namesize));
//중복되는 문자열을 뒤에 문자열들로 덮는다
j -= namesize;
//namesize만큼 j를 감소시켜야 다시 중복되는 문자열을 제거할수있다 ex) 1 1 1 2 3에서 중복되는 숫자를 제거한다 가정
total -= namesize;
//namesize 만큼 떙기기 때문에 기존의 total만큼 탐색하면 안됨
}
}
}
printf("중복제거 : %s\n", rst);
for (int i = 0; i < total; i += namesize) {
for (int j = i + namesize; j < total; j += namesize) {
if (strncmp(rst + i, rst + j, 6) > 0) {
strncpy(temp, rst + i, 6);
strncpy(rst + i, rst + j, 6);
strncpy(rst + j, temp, 6);
}
}
}
printf("오름차순 정렬 : %s\n", rst);
delete[]rst;
system("pause");
return 0;
}
파이썬
nameStr= "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌"
nameList = nameStr.split(",")
# 김씨이씨 인원수
kimNum = 0
leeNum = 0
for i in nameList:
if i[0] == "김":
kimNum += 1
elif i[0] == "이":
leeNum += 1
print("1. 김씨 인원수 : %d , 이씨 인원수 : %d " % (kimNum, leeNum))
# 이재영 반복
num = 0
for i in nameList:
if str(i) == "이재영":
num += 1
print("2. 이재명 반복 횟수 : %d " % num)
# 중복 제거 이름 출력
setNamesList = list(set(nameList))
print("3. 중복 제거 이름 출력 : ", setNamesList)
# 중복 제거 이름 정렬
setNamesList.sort()
print("4. 중복 제거 이름 정렬 출력 : " , setNamesList)
파이썬 코드입니다.
first = '이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌'
a,b,c=(' ',' ',first)
second = []
while (b!=''):
a,b,c = c.partition(',')
second.append(a)
ans_k = 0
ans_l = 0
for i in second:
if i[0] == '김': ans_k += 1
elif i[0] == '이': ans_l += 1
ans_ljy = 0
for i in second:
if i == '이재영': ans_ljy += 1
ans_remove = []
for i in second:
if i not in ans_remove: ans_remove.append(i)
ans_sort = ans_remove.copy()
ans_sort.sort()
print("1. 김씨는 {}명이고, 이씨는 {}명입니다.".format(ans_k,ans_l))
print("2. '이재영'이라는 이름은 총 {}번 반복됩니다.".format(ans_ljy))
print("3. ",end='')
for i in ans_remove[:-1]:
print(i,end=',')
print(ans_remove[-1])
print("4. ",end='')
for i in ans_sort[:-1]:
print(i,end=',')
print(ans_sort[-1])
partition함수를 이용하여 문자열에서 이름하나씩을 리스트로 받아내고 문제를 해결하였습니다. 3번과 4번답은 주어진 문자열처럼 출력하기 위해서 여러줄에 걸쳐 출력했습니다.
파이썬초보입니다. 많은 피드백 부탁드립니다!
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
public static void main(String[] args) {
String s="이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌";
String[] str=s.split(",");
int kim=0;
int lee=0;
int samename=0;
ArrayList<String> remove = new ArrayList<String>();
for(int i=0;i<str.length;i++) {
if(str[i].startsWith("김")) kim++;
if(str[i].startsWith("이")) lee++;
if(str[i].equals("이재영")) samename++;
if(!remove.contains(str[i])) {
remove.add(str[i]);
}
}
System.out.println("김씨는 "+kim+"명 입니다.");
System.out.println("이씨는 "+lee+"명 입니다.");
System.out.println("이재영은 "+samename+"번 반복됩니다.");
System.out.println("중복을 제거한 이름 : "+remove);
Collections.sort(remove);
System.out.println("오름차순으로 정렬 : "+remove);
}
책에서 배운대로....지적 환영합니다.
Java
import java.util.Arrays;
import java.util.function.Function;
import java.util.stream.Collectors;
public class NamesTester {
public static void main(String[] args) {
String names = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌";
String[] nameList = names.split(",");
Arrays.stream(nameList).map(x->x.substring(0, 1))
.filter(y->y.equals("김")||y.equals("이"))
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()))
.forEach((k,v)->System.out.println(k+":"+v));
System.out.println(Arrays.stream(nameList).filter(x->x.equals("이재영")).count());
System.out.println(Arrays.stream(nameList).distinct().collect(Collectors.joining(",")));
System.out.println(Arrays.stream(nameList).distinct().sorted().collect(Collectors.joining(",")));
}
}
#include <iostream>
#include <stdlib.h>
#include <string.h>
using namespace std;
void sort(char *str[], int size);
int replace(char str[17][7]);
int comparisonFunctionString(const void *a, const void *b);
int main() {
char input[]="이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌";
char s[]=",";
char* token =NULL;
char name[17][7];
token = strtok(input, s);
strcpy(name[0], token);
for(int i = 1;i<17;i++) {
token = strtok(NULL, s);
strcpy(name[i], token);
}
char* kim = "김";
char* lee = "이";
char* LJY= "이재영";
int countK = 0;
int countL = 0;
int countLJY = 0;
for(int i = 0;i<16;i++) {
if(!strncmp(name[i], kim, 2)) {
countK++;
}
if(!strncmp(name[i], lee, 2)) {
countL++;
}
if(!strncmp(name[i], LJY, 6)) {
countLJY++;
}
}
int size = replace(name);
cout<<"1. 김씨"<<countK<<" 이씨"<<countL<<"\n";
cout<<"2. 이재영"<<countLJY<<"\n";
cout<<"3. ";
for(int i = 0;i<=size;i++) {
cout<<name[i]<<",";
}
qsort((void*)name, size+1, sizeof(name[0]), comparisonFunctionString);
cout<<"\n4. ";
for(int i = 0;i<=size;i++) {
cout<<name[i]<<",";
}
cout<<"\n\n";
return 0;
}
int comparisonFunctionString(const void *a, const void *b) {
return( strcmp( (char *)a, (char *)b) );
}
int replace(char str[17][7]) {
int count = 0;
for(int i = 0;i<17;i++) {
for(int j = i+1 ; j <17; j++) {
if(!strncmp(str[i],str[j],7)) {
strcpy(str[j], "\0");
count++;
}
}
}
int return_value = count;
while(count>=0) {
for(int i = 0;i<17;i++) {
if(i+1< 17 && !strcmp(str[i],"\0")) {
strcpy(str[i], str[i+1]);
strcpy(str[i+1], "\0");
}
}
count--;
}
return return_value;
}
C 연결리스트 연습하려면..
find_middleappendmerge, sort, unique ...
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
typedef struct name_list name_list;
struct name_list {
const char *name;
name_list* next;
};
name_list* new_name_list(const char* name) {
name_list* n = (name_list*)malloc(sizeof(name_list));
n->name = name;
n->next = NULL;
return n;
}
void append(name_list* head_tail[2], const char* name) {
name_list* n = new_name_list(name);
if (head_tail[1]) {
head_tail[1]->next = n;
}
head_tail[1] = n;
if (!head_tail[0]) {
head_tail[0] = n;
}
}
void free_names(name_list* names) {
while (names) {
name_list* n = names;
names = names->next;
free((void*)n->name);
free(n);
}
}
void print_names(name_list* names) {
if (names) {
printf("%s", names->name);
names = names->next;
}
while (names) {
printf(",");
printf("%s", names->name);
names = names->next;
}
printf("\n");
}
name_list* split_names(const char* names) {
name_list* head_tail[2] = {NULL, NULL};
const char* p = names;
const char* q = names;
while (*q) {
if (*q == ',') {
append(head_tail, strndup(p, q-p));
p = q+1;
}
++q;
}
return head_tail[0];
}
int count_last_name(name_list* names, const char* last_name) {
int c = 0;
while (names) {
if (strstr(names->name, last_name) == names->name) {
c++;
}
names = names->next;
}
return c;
}
int count_name(name_list* names, const char* name) {
int c = 0;
while (names) {
if (strcmp(names->name, name) == 0) {
c++;
}
names = names->next;
}
return c;
}
int contains(name_list* names, const char* name) {
while (names) {
if (strcmp(names->name, name) == 0) {
return 1;
}
names = names->next;
}
return 0;
}
name_list* unique(name_list* names) {
name_list* head_tail[2] = {NULL, NULL};
while (names) {
if (!contains(head_tail[0], names->name)) {
append(head_tail, strdup(names->name));
}
names = names->next;
}
return head_tail[0];
}
name_list* merge(name_list* sorted1, name_list* sorted2) {
name_list* head_tail[2] = {NULL, NULL};
while (sorted1 || sorted2) {
if ((sorted1 && sorted2 && strcmp(sorted1->name, sorted2->name) < 0) || !sorted2) {
append(head_tail, strdup(sorted1->name));
sorted1 = sorted1->next;
} else {
append(head_tail, strdup(sorted2->name));
sorted2 = sorted2->next;
}
}
return head_tail[0];
}
name_list* find_middle(name_list* names) {
name_list* half = names;
while (names && names->next) {
half = half->next;
names = names->next->next;
}
return half;
}
name_list* copy_names(name_list* names, name_list* end) {
name_list* head_tail[2] = {NULL, NULL};
while (names && names != end) {
append(head_tail, strdup(names->name));
names = names->next;
}
return head_tail[0];
}
name_list* sort(name_list* names) {
if (names == NULL) return NULL;
if (names->next == NULL) return copy_names(names, NULL);
// split half and half
name_list* second_half = find_middle(names);
name_list* first_half = copy_names(names, second_half);
// sort each
name_list* sorted1 = sort(first_half);
name_list* sorted2 = sort(second_half);
free_names(first_half);
// merge
name_list* merged = merge(sorted1, sorted2);
free_names(sorted1);
free_names(sorted2);
return merged;
}
int main(int argc, const char * argv[]) {
name_list* names = split_names("이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌");
printf("%d\n", count_last_name(names, "김"));
printf("%d\n", count_last_name(names, "이"));
printf("%d\n", count_name(names, "이재영"));
name_list* uniq_names = unique(names);
print_names(uniq_names);
name_list* sorted = sort(uniq_names);
print_names(sorted);
free_names(sorted);
free_names(uniq_names);
free_names(names);
return 0;
}
C로..
#define len(arr) (sizeof(arr)/sizeof(arr[0]))
void print(char** names, size_t n) {
for (size_t i = 0; i < n; ++i) {
if (i > 0) printf(",");
printf("%s", names[i]);
}
printf("\n");
}
int cmp(const void* a, const void* b) {
return strcmp(*(const char**)a, *(const char**)b);
}
int main(int argc, const char * argv[]) {
char* names[] = {"이유덕", "이재영", "권종표", "이재영", "박민호", "강상희", "이재영", "김지완", "최승혁", "이성연", "박영서", "박민호", "전경헌", "송정환", "김재성", "이유덕", "전경헌"};
size_t count1 = 0, count2 = 0, count3 = 0;
for (size_t i = 0; i < len(names); ++i) {
count1 += strstr(names[i], "김") == names[i];
count2 += strstr(names[i], "이") == names[i];
count3 += strcmp(names[i], "이재영") == 0;
}
printf("%zu\n", count1);
printf("%zu\n", count2);
printf("%zu\n", count3);
char* uniq[len(names)];
size_t n = 0;
for (size_t i = 0; i < len(names); ++i) {
size_t j = 0;
while (j < n && names[i] != uniq[j]) j++;
if (j == n) uniq[n++] = names[i];
}
print(uniq, n);
qsort(uniq, n, sizeof(char*), cmp);
print(uniq, n);
return 0;
}
str_lst='이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌'.split(',')
# q1
k, e = 0, 0
for name in str_lst:
k = k + name.count("김")
e = e + name.count("이")
print('김 : ',k,'이 : ', e)
# q2
n_c = str_lst.count('이재영')
print('이재영 : ',n_c)
# q3
str_lst = list(set(str_lst))
print(str_lst)
# q4
print(sorted(str_lst))
nl = '이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌'
print('1. 김씨 %d명, 이씨 %d명' % ((',' + nl).count(',김'), (',' + nl).count(',이')))
print('2. "이재영" %d번 반복' % nl.count('이재영'))
uq = list(set(nl.split(',')))
print('3. 중복제거 : \n\t%s' % ','.join(uq))
uq.sort()
print('3. 중복제거 오름차순 : \n\t%s' % ','.join(uq))
Python 3.5.2에서 작성하였습니다.
자바로 작성했습니다.
public void empListCheck(String empListString){
ArrayList<String> empList = new ArrayList<String>();
String[] tmpEmpList = empListString.split(",");
int countKim = empListString.split(",김").length + ((empListString.startsWith("김"))?0:-1);
int countLee = empListString.split(",이").length + ((empListString.startsWith("이"))?0:-1);
int countJYLee = empListString.split(",이재영").length + ((empListString.startsWith("이재영"))?0:-1);
for(String empName:tmpEmpList){
if(!empList.contains(empName))
empList.add(empName);
}
//1.김씨와 이씨는 각각 몇 명 인가요?
System.out.println("김씨는 " + countKim + "명, 이씨는 " + countLee + "명");
//2."이재영"이란 이름이 몇 번 반복되나요?
System.out.println("이재영이란 이름은 " + countJYLee + " 번 반복");
//3.중복을 제거한 이름을 출력하세요.
System.out.println("중복을 제거한 이름을 출력");
StringBuilder sb = new StringBuilder();
String spr = "";
for(String empName:empList){
sb.append(spr);
sb.append(empName);
spr = ",";
}
System.out.println(sb.toString());
Collections.sort(empList);
//4.중복을 제거한 이름을 오름차순으로 정렬하여 출력하세요.
System.out.println("중복을 제거한 이름을 오름차순으로 정렬하여 출력");
sb.setLength(0);
spr = "";
for(String empName:empList){
sb.append(spr);
sb.append(empName);
spr = ",";
}
System.out.println(sb.toString());
}
names = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌"
space_names = names.replace(","," ")
import re
list_names = re.findall("\w+", space_names)
print("문제 1번 : 김씨와 이씨는 각각 몇명인가요?")
num_kim = re.findall("[김]..", names)
print(len(num_kim))
num_lee = re.findall("[이]..", names)
print(len(num_lee))
print("\n문제 2번 : 이재영 이란 이름이 몇번 반복되냐?")
print(list_names.count('이재영'))
print("\n문제 3번 : 중복을 제거한 이름을 출력하세요")
set_list_names = set(list_names)
print(set_list_names)
print("\n문제 4번 : 중복을 제거한 이름을 오름차순으로 출력하세요")
del_names = list(set_list_names)
del_names.sort()
print(del_names)
int main() { char *names = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌"; char table[17][10]; char tmp_name[10] = ""; int i, j, index = 0;
for (i = 0; i <= strlen(names); i++) {
if ((names[i] == ',') || (names[i] == '\0')) {
strcpy(table[index], tmp_name);
strcpy(tmp_name, "");
index++;
continue;
}
int len = strlen(tmp_name);
tmp_name[len] = names[i];
tmp_name[len + 1] = '\0';
}
int kim = 0, lee = 0, LJY = 0;
char new_table[12][10];
int new_n = 1;
strcpy(new_table[0], table[0]);
for (i = 0; i < 17; i++) {
strncpy(tmp_name, table[i], 3);
tmp_name[3] = '\0';
int find = 0;
for (j = 0; j < new_n; j++) {
if (strcmp(new_table[j], table[i]) == 0) {
find = 1;
break;
}
}
if (find == 0) strcpy(new_table[new_n++], table[i]);
if (strcmp(table[i], "이재영") == 0) LJY++;
if (strcmp(tmp_name, "김") == 0) kim++;
else if (strcmp(tmp_name, "이") == 0) lee++;
else continue;
}
printf("김씨 : %d명\n", kim);
printf("이씨 : %d명\n", lee);
printf("이재영 : %d명\n", LJY);
for (i = 0; i < new_n; i++) { printf("%s\n", new_table[i]); }
for (i = 0; i < new_n; i++) {
for (j = i+1; j < new_n; j++) {
if (strcmp(new_table[i], new_table[j]) > 0) {
strcpy(tmp_name, new_table[i]);
strcpy(new_table[i], new_table[j]);
strcpy(new_table[j], tmp_name);
}
}
}
for (i = 0; i < new_n; i++) { printf("%s\n", new_table[i]); }
return 0;
}
string = '이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,\
최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌'.split(',')
list_ = [x[0] for x in string if x[0] == '김' or x[0] == '이']
print('김씨 수 : ',list_.count('김'),' 이씨의 수 : ',list_.count('이'))
print('"이재영"이란 이름 반복수 : ', string.count('이재영'))
print('이름의 중복제거 : ',set(string))
print('중복제거 이름 오름차순 : ', sorted(set(string)))
#### 2016.12.10 D-439 ####
package com.kjh.study.test.code;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
public class NameDetector {
private String[] nameArray;
public NameDetector(String[] nameArray) {
this.nameArray = nameArray;
}
public int getCountForLastName(String lastName) {
int count = 0;
for (String name : nameArray) {
String memberLastName = name.substring(0, 1);
if (lastName.equals(memberLastName)) {
System.out.println("같은 녀석 : " + name);
count++;
}
}
return count;
}
public int getCountForFullName(String fullName) {
int count = 0;
for (String name : nameArray) {
if (name.equals(fullName)) {
count ++;
}
}
return count;
}
public String[] getDeduplicatedNameArray() {
List<String> deduplicatedList = new ArrayList<String>();
for (String name : nameArray) {
if (!deduplicatedList.contains(name)) {
deduplicatedList.add(name);
}
}
return deduplicatedList.toArray(new String[deduplicatedList.size()]);
}
public String[] getAscendingNameArray(String[] deduplicatedArray) {
List<String> ascendingList = new ArrayList<String>();
/* Algorith 활용 */
//Selection Sort
// String[] sortedArray = selectionSort(deduplicatedArray);
// return sortedArray;
/* List API 활용 */
ascendingList = Arrays.asList(deduplicatedArray);
getAscendingNameArrayUsingListAPI(ascendingList);
return ascendingList.toArray(new String[ascendingList.size()]);
}
private String[] selectionSort(final String[] array) {
String[] sortedArray = new String[array.length];
System.arraycopy(array, 0, sortedArray, 0, array.length);
for (int i = 0 ; i < sortedArray.length -1 ; i++) {
String minName = sortedArray[i];
for (int j = i + 1 ; j < sortedArray.length ; j++) {
if (sortedArray[j].compareTo(minName) < 0) {
minName = sortedArray[j];
String temp = sortedArray[i];
sortedArray[i] = sortedArray[j];
sortedArray[j] = temp;
}
}
}
return sortedArray;
}
private String[] getAscendingNameArrayUsingListAPI(List<String> ascendingList) {
ascendingList.sort(new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
return o1.compareTo(o2);
}
});
return ascendingList.toArray(new String[ascendingList.size()]);
}
}
package com.kjh.study.test.junit;
import static org.junit.Assert.*;
import org.junit.Before;
import org.junit.Test;
import com.kjh.study.test.code.NameDetector;
public class NameDetectorTest {
private String[] nameArray;
private NameDetector nameDetector;
@Before
public void setup() {
nameArray = new String[] {
"이유덕", "이재영", "권종표", "이재영", "박민호", "강상희",
"이재영", "김지완", "최승혁", "이성연", "박영서", "박민호",
"전경헌", "송정환", "김재성", "이유덕", "전경헌"
};
nameDetector = new NameDetector(nameArray);
}
@Test
public void getLastNameCount() {
int kimLastNameCount = nameDetector.getCountForLastName("김");
int leeLastNameCount = nameDetector.getCountForLastName("이");
assertEquals(2, kimLastNameCount);
assertEquals(6, leeLastNameCount);
}
@Test
public void getFullNameCount() {
int ljyFullNameCount = nameDetector.getCountForFullName("이재영");
assertEquals(2, ljyFullNameCount);
}
@Test
public void getDeduplicatedNameArray() {
String[] dedupArray = nameDetector.getDeduplicatedNameArray();
for (String name : dedupArray) {
System.out.print(name + " ");
}
}
@Test
public void getAscendingNameArray() {
String[] ascArray = nameDetector.getAscendingNameArray(nameDetector.getDeduplicatedNameArray());
for (String name : ascArray) {
System.out.print(name + " ");
}
}
}
import java.util.Arrays;
import java.util.List;
public class Names {
public static void main(String[] args) {
String names = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌";
List<String> namesList = Arrays.asList(names.split(","));
// 1. 김씨와 이씨는 각각 몇 명 인가요?
System.out.print("1. 김씨는 " +
namesList.stream().distinct()
.filter(name -> String.valueOf(name.toCharArray()[0]).equals("김"))
.count() + "명, ");
System.out.println("이씨는 " +
namesList.stream().distinct()
.filter(name -> String.valueOf(name.toCharArray()[0]).equals("이"))
.count() + "명");
//2. "이재영" 이란 이름이 몇 번 반복되나요?
System.out.println("2. " +
namesList.stream().filter(name -> name.equals("이재영")).count() + " 번");
//3. 중복을 제거한 이름을 출력하세요.
System.out.println("4. ");
namesList.stream().distinct().forEach(System.out::println);
//4. 중복을 제거한 이름을 오름차순으로 정렬하여 출력하세요.
System.out.println("5. ");
namesList.stream().distinct().sorted().forEach(System.out::println);
}
}
자바입니다.
결과 //
import java.awt.List;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
public class sainapsoft {
public static String[] str = {
"이유덕","이재영","권종표",
"이재영","박민호","강상희",
"이재영","김지완","최승혁",
"이성연","박영서","박민호",
"전경헌","송정환","김재성",
"이유덕","전경헌"
};
public static String[] str2;
public static void main(String[] args) {
System.out.print("1. 김씨와 이씨는 각각 몇 명 인가요? ");
int cnt = firstNameCnt("이");
System.out.print("이씨는 " + cnt + "명, " );
cnt = firstNameCnt("김");
System.out.println("김씨는 " + cnt + "명" );
System.out.print("2. '이재영'이란 이름이 몇번 반복되나요? ");
cnt = repeatNameCnt("이재영");
System.out.println("이재영은 " + cnt + "번 반복됩니다. " );
System.out.print("3. 중복을 제거한 이름을 출력하세요. ");
str = new HashSet<String>(Arrays.asList(str)).toArray(new String[0]);
ArrayList<String> list = new ArrayList<String>();
for(String s:str){
System.out.print(s);
list.add(s);
if(!s.equals("최승혁")){
System.out.print(", ");
}
}
System.out.println("");
System.out.print("4. 중복을 제거한 이름을 오름차순으로 정렬하여 출력하세요. ");
Collections.sort(list);
System.out.println(list);
}
private static int repeatNameCnt(String strName) {
int cnt = 0;
for(int i=0; i<str.length; i++){
if(strName.equals(str[i])){
cnt++;
}
}
return cnt;
}
public static int firstNameCnt(String strName){
int cnt = 0;
for(int i=0; i<str.length; i++){
if(strName.equals(str[i].substring(0, 1))){
cnt++;
}
}
return cnt;
}
}
import java.awt.List;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.StringTokenizer;
import java.util.regex.*;
public class nameSerch {
public static void main(String[] args) {
String name = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁"
+ ",이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌";
ArrayList list = new ArrayList();
StringTokenizer st = new StringTokenizer(name, ",");
for(int i=1; st.hasMoreTokens(); i++){
list.add(st.nextToken());
}
int jaeyungCnt=0;
int kimCnt=0;
int leeCnt=0;
for(int i=0; i < list.size();i++){
if( ((list.get(i).toString()).substring(0, 1)).equals("김") ){
kimCnt++;
}
if( ((list.get(i).toString()).substring(0, 1)).equals("이") ){
leeCnt++;
}
if( (list.get(i).toString()).matches("이재영") ){
jaeyungCnt++;
}
}
System.out.println("김 씨 "+kimCnt+" 명");
System.out.println("이 씨 "+leeCnt+" 명");
System.out.println("이재영 씨 "+jaeyungCnt +" 명");
list.sort(String.CASE_INSENSITIVE_ORDER);
ArrayList setList = new ArrayList(new HashSet<>(list));
System.out.println(setList);
}
}
package KYU;
import java.util.*;
public class ex1 {
public static void main(String args[]) {
int i, count_kim, count_lee, count_leejae;
count_kim = 0;
count_lee = 0;
count_leejae = 0;
String names = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌";
String[] arr = names.split(",");
Set<String> set = new HashSet<String>(); //중복 제거를 위한 HashSet//
List sortedList;
for (i = 0; i < arr.length; i++) {
if (arr[i].charAt(0) == '이')
count_lee++;
else if (arr[i].charAt(0) == '김')
count_kim++;
else
continue;
}
System.out.println("김씨: " + count_kim + "명, 이씨: " + count_lee + "명");
for (i = 0; i < arr.length; i++) {
if (arr[i].equals("이재영"))
count_leejae++;
}
System.out.println("이재영: " + count_leejae + "명");
for (i = 0; i < arr.length; i++) {
set.add(arr[i]);
}
System.out.println("중복 제거: " + set);
sortedList = new ArrayList(set);
Collections.sort(sortedList); //오름차순 정렬//
System.out.println("오름차순 정렬: " + sortedList);
}
}
import java.util.*;
import java.util.stream.Collectors;
public class Synapsoft {
private static final String input = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌";
public static void main(String[] args) {
String[] names = input.split(",");
System.out.println("김씨 = " + Arrays.asList(names).stream().filter(i -> i.startsWith("김")).count());
System.out.println("이씨 = " + Arrays.asList(names).stream().filter(i -> i.startsWith("이")).count());
System.out.println(Arrays.asList(names).stream().collect(Collectors.groupingBy(p -> p.charAt(0), Collectors.counting())).entrySet().stream().filter(k->k.getKey().equals('김') || k.getKey().equals('이')).collect(toSet()));
System.out.println(new LinkedHashSet(new ArrayList(Arrays.asList(names))));
System.out.println(new LinkedHashSet<String>(new ArrayList<String>(Arrays.asList(names)).stream().sorted().collect(Collectors.toList())));
}
}
def main(data):
data=data.split(",")
dic={}
n1kim=sum(1 for i in data if i[0]=="김")
n1lee=sum(1 for i in data if i[0]=="이")
n2=sum(1 for i in data if i=="이재영")
for i in data:
dic[i]=1
n4=list(dic.keys())
print("김씨는 %d명, 이씨는 %d명 있습니다" %(n1kim, n1lee))
print("'이재영'이란 이름은 %d번 반복됩니다." %(n2))
print(dic.keys())
print(n4)
main("이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌")
import java.util.ArrayList;
import java.util.Collections;
public class Test6 {
public static void main(String[] args) {
String names = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌";
question1(names);
question2(names);
question3(names);
question4(names);
}
public static void question1(String names) {
String[] nameArr = names.split(",");
int cntKim = 0;
int cntLee = 0;
for (int i = 0; i < nameArr.length; i++) {
String FamilyName = (nameArr[i].substring(0, 1));
if ("김".equals(FamilyName)) {
cntKim++;
} else if ("이".equals(FamilyName)) {
cntLee++;
}
}
System.out.println("1.김씨와 이씨는 각각 몇 명 인가요? " + "김씨=" + cntKim + ", " + "이씨=" + cntLee);
}
public static void question2(String names) {
String[] nameArr = names.split(",");
int cnt = 0;
for (int i = 0; i < nameArr.length; i++) {
if ("이재영".equals(nameArr[i])) {
cnt++;
}
}
System.out.println("2.\"이재영\"이란 이름이 몇 번 반복되나요? " + cnt);
}
public static void question3(String names) {
String[] nameArr = names.split(",");
ArrayList<String> resultArr = new ArrayList<String>();
int flag = 0;
for (int i = 0; i < nameArr.length; i++) {
for (int j = 0; j < nameArr.length; j++) {
flag = 0;
if (i != j && nameArr[i].equals(nameArr[j])) {
flag = 1;
break;
}
}
if (!resultArr.contains(nameArr[i])) {
resultArr.add(nameArr[i]);
} else if (flag == 0) {
resultArr.add(nameArr[i]);
}
}
System.out.println("3.중복을 제거한 이름을 출력하세요. ");
System.out.println(resultArr);
}
public static void question4(String names) {
String[] nameArr = names.split(",");
ArrayList<String> resultArr = new ArrayList<String>();
int flag = 0;
for (int i = 0; i < nameArr.length; i++) {
for (int j = 0; j < nameArr.length; j++) {
flag = 0;
if (i != j && nameArr[i].equals(nameArr[j])) {
flag = 1;
break;
}
}
if (!resultArr.contains(nameArr[i])) {
resultArr.add(nameArr[i]);
} else if (flag == 0) {
resultArr.add(nameArr[i]);
}
}
System.out.println("4.중복을 제거한 이름을 오름차순으로 정렬하여 출력하세요. ");
Collections.sort(resultArr);
System.out.println(resultArr);
}
}
파이썬 3.5.3 연습용 코드입니다.
a ="이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌"
a = a.split(',')
kim = 0
lee = 0
ljy = 0
for x in a:
if x[0] == '김':
kim += 1
if x[0] == '이':
lee += 1
if x == '이재영':
ljy += 1
b = set(a)
c = list(b)
c.sort()
print(kim)
print(lee)
print(ljy)
print(b)
print(c)
파이썬입니다
a = '이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌'
a = a.split(',')
leecount = 0
kimcount = 0
leecount1 = 0
for i , name in enumerate(a):
if name[0] == '이':
leecount += 1
if name == '이재영':
leecount1 += 1
if name[0] == '김':
kimcount += 1
print("김씨는 %s명 / 이씨는 %s명 / 이재영은 %s번 반복 \n" % (kimcount,leecount,leecount1))
a = set(a)
print("중복 제거 : %s \n" % a)
a = sorted(a)
print("오름차순 정렬 : %s" % a)
names = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌"
n = names.split(',')
# 1. 김씨와 이씨 성을 가진 이름
def k_l(n):
surname = [ x[0] for x in n]
print("김씨는 %d명이고,"%(surname.count("김")),"이씨는 %d명입니다"%(surname.count("이")))
# 2. 이재영은 몇 명
def jy(n):
return n.count("이재영")
# 3. 중복 이름 제거한 목록
def no_re(n):
return set(n)
# 4. 중복 없고 오름차순
def asc(n):
return sorted(no_re(n))
public void go() {
String setname = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌";
String [] name = setname.split(",");
int count=0;
for(int i=0 ; i<name.length ;i++ ){
char a = name[i].charAt(0);
if(a=='이'||a=='김') {
count++;
}
}
System.out.println("1번: "+count);
//2번문제
count=0;
for(int i=0 ; i<name.length ; i++) {
if(name[i].equals("이재영")) {
count++;
}
}
System.out.println("2번: "+count);
//3번문제
HashSet<String> rename = new HashSet<String>();
for(int i=0 ; i<name.length ; i++) {
rename.add(name[i]);
}
System.out.println("3번: "+rename);
//4번문제
ArrayList<String> a = new ArrayList<String>();
a.addAll(rename);
Collections.sort(a);
System.out.print("4번: "+a);
}
package training;
import java.util.ArrayList;
public class CynapSoftTest {
public static void main(String[] args) {
String strSample = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌";
String[] strArr = strSample.split(",");
ArrayList<String> arr = new ArrayList();
int iArrCnt = strArr.length;
int iAnswer1 = 0;
int iAnswer2 = 0;
int iAnswer3 = 0;
int iAnswer4 = 0;
for(int i=0;i<iArrCnt;i++){
if(strArr[i].substring(0, 1).equals("김") || strArr[i].substring(0, 1).equals("이")){
iAnswer1++;
}
if(strArr[i].equals("이재영")){
iAnswer2++;
}
for(int j=0;j<arr.size();j++){
if(arr.get(j).equals(strArr[i])){
iAnswer3++;
}
}
if(iAnswer3 == 0){
arr.add(strArr[i]);
iAnswer3 = 0;
} else {
iAnswer3 = 0;
}
}
// 김씨와 이씨는 각각 몇 명 인가요?
System.out.println("iAnswer1 : "+iAnswer1);
// "이재영"이란 이름이 몇 번 반복되나요?
System.out.println("iAnswer2 : "+iAnswer2);
// 중복을 제거한 이름을 출력하세요.
System.out.println(arr);
// 중복을 제거한 이름을 오름차순으로 정렬하여 출력하세요.
// sorting
arr.sort(null);
System.out.println(arr);
}
}
#include <iostream>
#include <vector>
#include <set>
using namespace std;
int Func( vector< string >& rVec , string& rStr )
{
size_t rFound;
rFound = rStr.find( "," );
if( rFound != string::npos )
{
rVec.push_back( rStr.substr( 0 , rFound ) );
rStr = rStr.substr( rFound + 1 );
return 0;
}
else if( rStr.size() > 0 )
{
rVec.push_back( rStr );
rStr = "";
return 0;
}
return -1;
}
int main( int argc , char** argv )
{
string rStr = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌";
vector< string > rVec;
int ret=0;
while( ( ret = Func( rVec , rStr ) ) >= 0 )
{
}
int kim = 0;
int lee = 0;
int leejaeyoung = 0;
set< string > rSet;
for( size_t i = 0 ; i < rVec.size() ; ++i )
{
if( rVec[ i ].compare( 0 , strlen( "김" ) , "김" ) == 0 )
{
kim++;
}
else if( rVec[ i ].compare( 0 , strlen( "이" ) , "이" ) == 0 )
{
lee++;
}
if( rVec[ i ].compare( "이재영" ) == 0 )
{
leejaeyoung++;
}
rSet.insert( rVec[ i ] );
}
printf( "김씨:%d 이씨:%d 이재영:%d\n" , kim , lee , leejaeyoung );
for( set< string >::iterator rIter = rSet.begin() ; rIter != rSet.end() ; ++rIter )
{
cout << *rIter << endl;
}
}
list1="이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌"
result=list1.split(",")
def first(a,b):
k=0
for i in list1:
if i[0]==a:
k=k+1
if i[0]==b:
k=k+1
return k
print(first('김','이'))
def second(a):
k=0
for i in result:
if i == a:
k=k+1
return k
print(second("이재영"))
#print(result.count("이재영"))
name=[]
ol=set(result)
for i in ol:
name.append(i)
print(name)
name.sort()
name.reverse()
print(name)
/* Micrisift Windows 10.0.14393 (32-bits)
* Java 1.8.0_131 (32-bits)
* Eclipse Neon.3 Release (4.6.3)
*/
import java.util.ArrayList;
import java.util.Collections;
public class CD_Solutiion {
public static void main(String[] args) {
// TODO Auto-generated method stub
String[] data = {"이유덕", "이재영", "권종표", "이재영", "박민호", "강상희", "이재영", "김지완", "최승혁", "이성연", "박영서", "박민호", "전경헌", "송정환", "김재성", "이유덕", "전경헌"};
// 문제 1. 김씨와 이씨는 각각 몇 명 인가요?
int kim = 0; // "김"씨 성을 갖는 사람들의 숫자를 세기 위한 변수
int lee = 0; // "이"씨 성을 갖는 사람들의 숫자를 세기 위한 변수
for (String d : data) {
if (d.charAt(0) == '김') kim++;
if (d.charAt(0) == '이') lee++;
}
System.out.println("[Q1]");
System.out.println("kim : " + kim + "\tlee: " + lee);
// 문제 2. "이재영"이란 이름이 몇 번 반복되나요?
int ljy = 0;
for (String d : data) {
if (d.equals("이재영")) ljy++;
}
System.out.println("[Q2]");
System.out.println("이재영 : " + ljy);
// 문제 3. 중복을 제거한 이름을 출력하세요.
ArrayList<String> al_d = new ArrayList<String>();
for (String d : data) {
if (!al_d.contains(d)) al_d.add(d);
}
System.out.println("[Q3]");
for (int i = 0; i < al_d.size(); i++) System.out.println(al_d.get(i));
// 문제 4. 중복을 제거한 이름을 오름차순으로 정렬하여 출력하세요.
Collections.sort(al_d);
System.out.println("[Q4]");
for (int i = 0; i < al_d.size(); i++) System.out.println(al_d.get(i));
}
}
Python 3.4.2
name = '이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌'
print("김씨와 이씨는 각각 {}, {} 명이 있습니다.".format(name.count("김"), name.count("이")))
print("'이재영'이라는 동명이인이 {}명 있습니다.".format(name.count("이재영")))
unsorted_name_set = set(name.split(',')) # 집합으로 '이재영'이라는 이름 중복제거
sorted_name_list = sorted(unsorted_name_set) # 비정열된 집합을 정렬된 리스트로 전환
print(",".join(unsorted_name_set))
print(",".join(sorted_name_list))
name = ["이유덕", "이재영", "권종표", "이재영", "박민호", "강상희", "이재영", "김지완", "최승혁", "이성연", "박영서", "박민호", "전경헌", "송정환", "김재성", "이유덕", "전경헌"]
a = [i[0] for i in name]
print("김씨 : %d\n이씨 : %d\n" %(a.count("김"), a.count("이")))
print("이재영 이름 반복횟수 : ", name.count("이재영"))
name2 = list(set(name))
print(name2)
name2.sort()
print(name2)
def name(n):
n_lst=[]
for i in lst:
for j in i:
if j[0]==n:
n_lst.append(i)
result=len(n_lst)
return result
a=name("김")
print("김씨는 몇 명인가? %d명이다." %a)
b=name("이")
print("이씨는 몇 명인가? %d명이다." %b)
n=lst.count("이재영")
print("이재영은 몇 번 반복되나? %d번 반복된다." %n)
a=list(set(lst))
a.sort()
print(a)
많이 허접하지만..
a = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌"
b = a.split(",")
c = 0
d = 0
e = []
count = 0
for i in range(0,len(b)):
if b[i][0] == "김":
c += 1
elif b[i][0] == "이":
d += 1
else:
pass
for j in range(0, len(b)):
for k in range((j+1),len(b)):
if b[j] == b[k]:
e.append(b[j])
break
else:
pass
for i in b:
if i == "이재영":
count += 1
else:
pass
for m in e:
for n in b:
if m == n:
b.remove(n)
break
else:
pass
B = sorted(b)
print("1.김씨와 이씨는 각각 %d, %d 명입니다." %(c,d))
print("2. 이재영이란 이름 반복 : %d회" %count)
print("3.중복을 제거한 이름 : %s" %b)
print("4.중복을 제거한 이름을 오름차순으로 정렬 : %s" %B)
names = '이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌'
list1 = names.split(",")
listkim = []
listlee = []
c = 0 # count
# a = [i[0] for i in names]\n a.count("김")
for S in list1:
if '김' in S:
listkim.append(S)
elif '이' in S:
listlee.append(S)
N1 = len(listkim)
N2 = len(listlee)
print("1의 답: %d, %d " %(N1, N2))
c = listlee.count("이재영")
print("2의 답 : %f" %c)
s1 = set(list1)
print("3의 답: %s" %s1)
sortlist = sorted(s1)
print("4의 답 : %s " %sortlist)
참, 컬렉션을 안 쓰려고 해도 계속 써지네요...
// 이름 체크 - C#
using System;
using System.Collections.Generic;
namespace names
{
class Program
{
static void Main(string[] args)
{
string names = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌";
// 1. 김씨와 이씨는 각각 몇 명인가요?
Console.WriteLine("{0}, {1}", names.Length - names.Replace("이", "").Length, names.Length - names.Replace("박", "").Length);
// 2. "이재영"이라는 이름이 몇 번 반복되나요?
Console.WriteLine((names.Length - names.Replace("이재영", "").Length) / 3);
// 3. 중복을 제거한 이름을 출력하세요.
string[] list = names.Split(',');
List<string> goal = new List<string>();
for (int i = 0; i < list.Length; i++)
{
if (goal.Contains(list[i]))
continue;
goal.Add(list[i]);
}
foreach (string s in goal)
Console.Write("{0} ", s);
Console.WriteLine();
// 4. 중복을 제거한 이름을 오름차순으로 출력하세요.
goal.Sort();
foreach (string s in goal)
Console.Write("{0} ", s);
Console.WriteLine();
}
}
}
string="이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌"
def name_problem(string):
list(string)
name=[]
tmp=""
kim=0
lee=0
for i in range(len(string)):
if string[i]==",":
name.append(tmp)
tmp=""
else:
if tmp=="":
if string[i]=="김":
kim+=1
elif string[i]=="이":
lee +=1
tmp+=string[i]
else:
tmp+=string[i]
print("김씨 수 : ",kim,"이씨 수 : ",lee)
print("사람수 : ",len(name)+1)
cnt=0
for i in range(len(name)):
if name[i]=="이재영":
cnt+=1
print("이재영이란 이름의 반복 횟수 : ",cnt)
name=list(set(name))
print("중복된 이름 제거후 남은 배열: ",name)
name.sort()
print(name)
name_problem(string)
public static void main(String[] args) {
String num="이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌";
String[] num1=num.split(",");
int cnt1=0;
int cnt2=0;
for(int i=0;i<num1.length;i++){
if(num1[i].charAt(0)=='이' || num1[i].charAt(0)=='김')
cnt1++;
}//이씨나 김씨를 검출
for(int i=0;i<num1.length;i++){
if(num1[i].equals("이재영"))
cnt2++;
}//이재영이 몇명인지 검출
System.out.println(cnt1+"명");//1번출력
System.out.println(cnt2+"번");//2번출력
ArrayList<String> list1 = new ArrayList<>();//중복을 제거하고 담을 어레이리스트 컬렉션 선언
for(int i=0;i<num1.length;i++){
if(!list1.contains(num1[i]))
list1.add(num1[i]);
}//중복 제거하고 넣음
for(int i=0;i<list1.size();i++){
System.out.print(list1.get(i) +" ");
}//3번 출력
System.out.println();
HashSet<String> hs = new HashSet<>();//해쉬셋 컬렉션 선언
for(int i=0;i<num1.length;i++){
hs.add(num1[i]);
}//넣어지면서 자동으로 정렬됨
System.out.println(hs);//4번출력
}
나름 객체지향적으로 하려고 했는데 잘 짜고 있는건지 모르겠네요.
javascript(ES6)
var Names = function(str) {
this.array = str.split(",");
};
Names.prototype.countByLastname = function(str) {
return this.array.map(v => v.startsWith(str) ? 1 : 0).reduce((a, b) => a + b, 0);
};
Names.prototype.countByName = function(str) {
return this.array.map(v => v === str ? 1 : 0).reduce((a, b) => a + b, 0);
};
Names.prototype.getNames = function(opt) {
var array = Array.from(new Set(this.array));
return opt && opt.sort ? array.sort().join(",") : array.join(",");
};
var input = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌";
var names = new Names(input);
console.log(names.countByLastname("김"));
console.log(names.countByLastname("이"));
console.log(names.countByName("이재영"));
console.log(names.getNames());
console.log(names.getNames({sort : true}));
countByLastname 과 countByName 을 합쳐봤습니다.
var Names = function(str) {
this.array = str.split(",");
};
Names.prototype.compare = {
"lastname" : (v, str) => v.startsWith(str),
"name" : (v, str) => v === str
};
Names.prototype.countBy = function(opt, str) {
return this.array.map(v => this.compare[opt](v, str) ? 1 : 0).reduce((a, b) => a + b, 0);
};
var input = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌";
var names = new Names(input);
console.log(names.countBy("lastname", "김"));
console.log(names.countBy("lastname", "이"));
console.log(names.countBy("name", "이재영"));
name = '이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌'
nameList = name.split(',')
lastName = [x[0] for x in nameList]
print("김씨 %d 명, 이씨 %d 명" % (lastName.count('김'),lastName.count('이')))
print("이재영 %d회 반복" % nameList.count('이재영'))
nameListNew = []
for x in nameList:
if x not in nameListNew:
nameListNew.append(x)
print("중복 제거된 이름: ", nameListNew)
nameListNew.sort()
print("오름차순 정렬: ",nameListNew)
c로 풀이
#include <stdio.h>
#include <string.h>
typedef struct namee{
char last[3];
char first[5];
int num;
}name;
void input_name(name*a,char*b,int*c);
void prev_name(name*a,int*b);
int compare_last(name*a,char*b);
void rearrange_name(name*a,int*b);
int main(void)
{
char a[]="이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌";
name list[20];
int i,j,num=0;
list[0].num=1;
for(i=0;i<20;i++) input_name(list,a,&i);
i-=20;
for(j=0;j<i;j++) num+=compare_last(&list[j],"김");
printf("1. 김씨 : %d",num);
num=0;
for(j=0;j<i;j++) num+=compare_last(&list[j],"이");
printf(" 이씨 : %d\n",num);
printf("2. 이름 : ");
for(j=0;j<i;j++) printf("%s%s ",list[j].last,list[j].first);
for(j=0;j<i;j++) if(!(strcmp(list[j].first,"재영")||strcmp(list[j].last,"이"))) printf("\n3. 이재영 숫자 : %d",list[j].num);
rearrange_name(list,&i);
printf("\n4. 이름 : ");
for(j=0;j<i;j++) printf("%s%s ",list[j].last,list[j].first);
return 0;
}
void input_name(name*a,char*b,int*c)
{
int i;
static int j;
for(i=0;i<2;i++) a[*c].last[i]=b[j++];
a[*c].last[2]='\0';
for(i=0;i<4;i++) a[*c].first[i]=b[j++];
a[*c].first[4]='\0';
prev_name(a,c);
if(b[j]=='\0') *c+=20;
j++;
}
void prev_name(name*a,int*b)
{
int i;
for(i=0;i<*b;i++)
{
if(!(strcmp(a[*b].first,a[i].first)||strcmp(a[*b].last,a[i].last)))
{
a[i].num++;
(*b)--;
}
else a[*b].num=1;
}
}
int compare_last(name*a,char*b)
{
if(strcmp(a->last,b))return 0;
else return a->num;
}
void rearrange_name(name*a,int*b)
{
int i,j;
name temp;
for(i=0;i<*b;i++) for(j=i+1;j<*b;j++)
{
if(strcmp(a[i].last,a[j].last)==1)
{
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
else if(strcmp(a[i].last,a[j].last)==0) if(strcmp(a[i].first,a[j].first)==1)
{
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
}
C++로 풀이
#include <iostream>
#include <string>
#include <vector>
using namespace std;
const string names[] = {"이유덕", "이재영", "권종표", "이재영", "박민호",
"강상희", "이재영", "김지완", "최승혁", "이성연",
"박영서", "박민호", "전경헌", "송정환", "김재상",
"이유덕", "전경헌"};
// problem 1.
int cntKimAndLee(const vector<string>& strs_name)
{
string f_name = "";
int cnt = 0;
for (auto s : strs_name ) {
f_name = s.substr(0,3);
if(f_name == "김" || f_name == "이") {
++cnt;
}
}
return cnt;
}
// problem 2.
int findName(const vector<string>& strs_name, const string& nameTofind)
{
int cnt = 0;
for (auto s : strs_name) {
if ( s == nameTofind)
++cnt;
}
return cnt;
}
// problem 3. and problem 4.
void printRMoverlapName(const vector<string>& strs_name)
{
bool bOverlaped = false;
vector<string> rmOverlapName;
for (auto s1 : strs_name) {
for (auto s2 : rmOverlapName) {
if ( s1 == s2 )
bOverlaped = true;
}
if(!bOverlaped)
rmOverlapName.push_back(s1);
bOverlaped = false;
}
std::cout << "non-overlapping name : " ;
for (auto s : rmOverlapName)
std::cout << s << " ";
std::cout << std::endl;
// problem 4.
sort(rmOverlapName.begin(), rmOverlapName.end());
std::cout << "sorted non-overlaping name : " ;
for (auto s : rmOverlapName)
std::cout << s << " ";
std::cout << std::endl;
}
int main()
{
vector<string> name_vec;
for (int i=0; i < 17; i++ ) {
name_vec.push_back(names[i]);
}
std::cout << "num of 김 or 이 : " << cntKimAndLee(name_vec) << std::endl;
std::cout << "num of 이재영 : " << findName(name_vec, "이재영") << std::endl;
printRMoverlapName(name_vec);
return 0;
}
파이썬 코드입니다.
names = '이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌'
lst = names.split(',')
print("김 씨:", sum([1 for n in lst if n[0] == '김']), "명")
print("이 씨:", sum([1 for n in lst if n[0] == '김']), "명")
print("이재영:", lst.count('이재영'), "회 반복")
print("중복제거:", set(lst))
print("중복제거-오름차순:", sorted(set(lst)))
C/C++로 풀라고 만든 문제 같아서 C로 작성해봤습니다. 작업 하나하나는 어려운 게 아닌데 역시 시간이 훨씬 더 걸리네요.
#include <stdio.h>
#include <string.h>
// 세 글자가 아닌 이름은 없다고 가정함
// 보기 쉬우라고 그냥 전역 변수로 선언
char input[] = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌";
char *names[20], *unames[20], *token, *context = NULL;
int ncnt, uncnt;
// 잘라서 포인터만 저장
void split()
{
char *token, *context = NULL;
ncnt = 0;
token = strtok_s(input, ",", &context);
while (token) {
names[ncnt++] = token;
token = strtok_s(NULL, ",", &context);
}
}
// names[i]에 str이 처음부터 "들어가" 있는지 검사하고 매치되면 카운트
int instr_cnt(char *str)
{
int len, cnt, i, j;
len = strlen(str);
cnt = 0;
for (i = 0; i < ncnt; i++) {
for (j = 0; j < len; j++) {
if (names[i][j] != str[j])
break;
}
if (j >= len) cnt++;
}
return cnt;
}
// 중복 이름 제거. *names[] --> *unames[]
// compaction 귀찮아서 그냥 다른 배열에 저장.
void make_unique()
{
int i, j;
uncnt = 0; // unique_name count
for (i = 0; i < ncnt-1; i++) {
for (j = i + 1; j < ncnt; j++) {
if (strncmp(names[i], names[j], strlen(names[i])) == 0)
break;
}
if (j >= ncnt)
unames[uncnt++] = names[i];
}
}
// 여기서 정렬이 중요하진 않으니 그냥 버블ㅋㅋ
void sort()
{
int last, j;
char *tmp;
for (last = 0; last < uncnt; last++) {
for (j = 0; j < last; j++) {
if (strncmp(unames[j], unames[j + 1], strlen(unames[j])) > 0) {
tmp = unames[j];
unames[j] = unames[j + 1];
unames[j + 1] = tmp;
}
}
}
}
int main()
{
int i;
split();
for (i = 0; i < ncnt; i++)
printf("%s ", names[i]);
printf("\n\n");
printf("김씨 %d명\n", instr_cnt("김"));
printf("이씨 %d명\n", instr_cnt("이"));
printf("이재영 %d회 반복\n", instr_cnt("이재영"));
make_unique();
printf("\n중복제거: \n");
for (i = 0; i < uncnt; i++)
printf("%s ", unames[i]);
printf("\n\n");
sort();
printf("중복제거 오름차순: \n");
for (i = 0; i < uncnt; i++)
printf("%s ", unames[i]);
printf("\n\n");
}
def count_by_last_name(items, last_name):
return len([x for x in items if x.startswith(last_name)])
items = '이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌'\
.split(',')
print('1. 김씨와 이씨는 각각 몇 명 인가요?\n %d명, %d명'
% (count_by_last_name(items, '이'), count_by_last_name(items, '김')))
print('2. "이재영"이란 이름이 몇 번 반복되나요?\n %d번'
% len([x for x in items if x == '이재영']))
print('3. 중복을 제거한 이름을 출력하세요.\n', set(items))
print('4. 중복을 제거한 이름을 오름차순으로 정렬하여 출력하세요.\n',
sorted(set(items)))
a_list = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌".split(',')
count_k = 0
count_l = 0
count_j = 0
for x in a_list:
if x[0] == '김':
count_k += 1
elif x == '이재영':
count_j += 1
elif x[0] == '이':
count_l += 1
print('김씨:',count_k,'명' ' 이씨:',count_l,'명') #1번
print('이재영:',count_j,'번 반복') #2번
print(set(a_list)) #3번
print(sorted(set(a_list))) #4번
부족한 부분이 있으면 지적 부탁드립니다.
``````{.java} package java_tutorial;
import java.util.Arrays;
public class NameList {
public static void main(String[] args) {
String name = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌";
String []name_List = new String[100];
int list_Num = 0;
int kimCount = 0;
int leeCount = 0;
int ljyCount = 0;
Arrays.fill(name_List, "");
for(int i = 0; i < name.length(); i++)
{
if(name.charAt(i)==',')
{
list_Num++;
continue;
}
name_List[list_Num] += name.charAt(i);
}
for(int i = 0; i < list_Num; i++)
{
if(name_List[i].charAt(0)=='김')
{
kimCount++;
}
if(name_List[i].charAt(0)=='이')
{
leeCount++;
}
if(name_List[i]=="이재영")
{
ljyCount++;
}
}
System.out.println("김씨는 "+ kimCount + "명이고, 이씨는 " + leeCount + "명 입니다.");
int while_Count = list_Num;
while(while_Count > 0)
{
for(int i = 0; i < list_Num; i++)
{
for(int j = i+1; j < list_Num; j++)
{
if(name_List[i].equals(name_List[j]))
{
name_List[j] = "";
}
}
}
int count = 0;
for(int i = 0; i < list_Num; i++)
{
if(name_List[i]=="")
{
count = i;
while(name_List[count]=="")
{
count++;
}
name_List[i] = name_List[count];
list_Num--;
}
}
while_Count--;
}
for(int i = 0; i < list_Num; i++)
{
System.out.println(name_List[i]);
}
Arrays.sort(name_List, 0, list_Num);
for(int i = 0; i < list_Num; i++)
{
System.out.println(name_List[i]);
}
}
}
```
from collections import defaultdict as dd
a = '이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌'.split(',')
#1-1
s = [x[0] for x in a]
s_dict = dd(int)
for n in s:
s_dict[n] += 1
print(s_dict['김'], s_dict['이'])
#2
print(a.count('이재영'))
#3
print(set(a))
#4
print(sorted(list(set(a))))
names = '이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌'
name_list = names.split(',')
# 1번 문제
lee = 0
kim = 0
for i in range(len(name_list)) :
if name_list[i][0] == '이' :
lee += 1
elif name_list[i][0] == '김' :
kim += 1
print(lee, kim)
# 2번 문제
print(name_list.count('이재영'))
# 3번 문제
newlist = []
for i in range(len(name_list)) :
if name_list[i] in newlist :
pass
else :
newlist.append(name_list[i])
print(','.join(newlist))
# 4번 문제
print(','.join(sorted(newlist)))
public class SynapInterview {
public static void main(String[] args) {
String input = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌";
String[] names = input.split(",");
ArrayList<String> output = new ArrayList<String>();
int i, cntKim=0, cntLee=0, cntLJY=0;
for(i=0;i<names.length;i++) {
if(names[i].startsWith("김")) cntKim++;
if(names[i].startsWith("이")) cntLee++;
if(names[i].equals("이재영")) cntLJY++;
if(!output.contains(names[i])) output.add(names[i]);
}
System.out.println(cntKim);
System.out.println(cntLee);
System.out.println(cntLJY);
System.out.println(output);
Collections.sort(output);
System.out.println(output);
}
}
public static void name(){
/*
* 김씨와 이씨는 각각 몇 명 인가요?
*"이재영"이란 이름이 몇 번 반복되나요?
*중복을 제거한 이름을 출력하세요.
*중복을 제거한 이름을 오름차순으로 정렬하여 출력하세요.
*/
/*String name[] = new String[] {"이유덕","이재영","권종표","이재영",
"박민호","강상희","이재영","김지완","최승혁",
"이성연","박영서","박민호","전경헌","송정환","김재성","이유덕","전경헌"};
*/
String names;
names = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌";
String name[];
name = names.split(",");
String firstName[];
firstName = new String[17];
int KIM=0 ;
int LEE=0 ;
int JaeyounLee = 0;
HashSet<String> hSet = new HashSet<String>();
TreeSet<String> tSet = new TreeSet<String>();
for (int i = 0; i < name.length; i ++)
{
firstName[i] = name[i].substring(0, 1);
if(firstName[i].equals("김"))
{
KIM = KIM + 1;
}
if(firstName[i] .equals("이"))
{
LEE = LEE + 1;
}
if(name[i].equals("이재영"))
{
JaeyounLee = JaeyounLee +1;
}
hSet.add(name[i]);
tSet.add(name[i]);
hSet.size();
}
System.out.println("김 : "+KIM);
System.out.println("이 : "+LEE);
System.out.println("JaeyounLee : " +JaeyounLee);
System.out.println("이름리스트:"+Arrays.toString(name));
System.out.println("중복제거:"+hSet);
System.out.println("제거후 정렬:"+tSet);
HashSet<String> hSet1 = new HashSet<String>();
for(int i = 0; i < 9; i++){
hSet1.add(name[i]);
}
}
R로 작성했습니다.
Q <- '이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌'
StringProblem <- function(Q){
Q <- strsplit(Q, ',')
Q <- do.call('c', Q)
Q.split <- strsplit(Q, split = '')
Q.split <- lapply(Q.split, '[', 1)
firstName <- do.call('c', Q.split)
ans1 <- c(sum(firstName == '김'), sum(firstName == '이'))
print(paste('1. 김씨와 이씨는 각각 몇 명 인가요?'))
print(paste0('답: 김씨는 ', ans1[1], '명 / ', '이씨는 ', ans1[2], '명'))
ans1 <- sum(Q == '이재영')
print(paste('2. 이재영이란 이름이 몇 번 반복되나요?'))
print(paste0('답: ', ans1, '번'))
ans3 <- paste(unique(Q), collapse = ', ')
print('3. 중복을 제거한 이름을 출력하세요.')
print(paste0('답: ', ans3))
ans4 <- paste(unique(Q)[order(unique(Q))], collapse = ', ')
print('4. 중복을 제거한 이름을 오름차순으로 정렬하여 출력하세요.')
print(paste0('답: ', ans4))
}
StringProblem(Q)
Python으로 작성했습니다.```{.python} Q = '이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌'
def StringProblem(Q): Q = Q.split(',') ans = {'김': 0, '이': 0, '이재영': 0}
# Answer1 & Answer2
for word in Q:
if word[0] == '김':
ans['김']+=1
if word[0] == '이':
ans['이']+=1
if word == '이재영':
ans['이재영']+=1
# Answer3 & Answer4
ans3 = sorted(set(Q), key=Q.index)
ans4 = sorted(set(Q))
print('1. 김씨와 이씨는 각각 몇 명 인가요?')
print('답: 김씨는 ' + str(ans['김']) + '명 / ' + '이씨는 ' + str(ans['이']) + '명')
print('2. "이재영"이란 이름이 몇 번 반복되나요?')
print('답: ' + str(ans['이재영']) + '번 반복')
print('3. 중복을 제거한 이름을 출력하세요.')
print('답: ' + ', '.join(ans3))
print('4. 중복을 제거한 이름을 오름차순으로 정렬하여 출력하세요.')
print('답: ' + ', '.join(ans4))
StringProblem(Q) ```
[Python 3.6]
def findLastNameCount(inputStr, lastName):
return len([name for name in inputStr.split(",") if name[0] == lastName])
def findNameCount(inputStr, inputName):
return len([name for name in inputStr.split(",") if name == inputName])
def elimDupName(inputStr):
return ",".join(set(inputStr.split(",")))
def elimDupNameSort(inputStr):
return ",".join(sorted(elimDupName(inputStr).split(",")))
inputStr = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌"
print(findLastNameCount(inputStr, "김"))
print(findLastNameCount(inputStr, "이"))
print(findNameCount(inputStr, "이재영"))
print(elimDupName(inputStr))
print(elimDupNameSort(inputStr))
import java.util.ArrayList;
import java.util.Collections;
public class Main {
public static void main(String[] args) {
String str = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌";
String [] nameArr = str.split(","); // 콤마를 기준으로 잘라서 String 배열에 저장
System.out.println("1. 김씨와 이씨는 각각 몇 명인가요?");
int numOfKim = 0, numOfLee = 0, numOfLeejaeyoung = 0;
for (int i=0; i<nameArr.length; i++) {
if (nameArr[i].startsWith("김")) {
numOfKim++;
}
if (nameArr[i].startsWith("이")) {
numOfLee++;
}
if (nameArr[i].equals("이재영")) {
numOfLeejaeyoung++;
}
}
System.out.println(" >> 김씨 : " + numOfKim + "명, 이씨 : " + numOfLee + "명");
System.out.println("2. \"이재영\"이란 이름이 몇 번 반복되나요?");
System.out.println(" >> " + numOfLeejaeyoung + "번");
System.out.println("3. 중복을 제거한 이름을 출력하세요.");
ArrayList<String> list = new ArrayList<String>();
for (int i=0; i<nameArr.length; i++) {
if (list.contains(nameArr[i])) {
continue;
} else {
list.add(nameArr[i]);
}
}
System.out.print(" >> ");
for (int i=0; i<list.size(); i++) {
System.out.print(list.get(i) + " ");
}
System.out.println();
System.out.println("4. 중복을 제거한 이름을 오름차순으로 정렬하여 출력하세요.");
System.out.print(" >> ");
Collections.sort(list);
for (int i=0; i<list.size(); i++) {
System.out.print(list.get(i) + " ");
}
}
}
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashSet;
import java.util.Set;
import java.util.stream.Collectors;
public class Example24 {
public static void main(String[] args) {
Example24 ex = new Example24();
String names = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌";
String[] stringArray = names.split(",");
// 1. 김씨와 이씨는 각각 몇 명인가요?
// 일반
int kimsCount = ex.getfirstNameCount(stringArray, "김");
System.out.println("김씨 : " + kimsCount);
// 람다로
int kimsCount2 = (int) Arrays.stream(stringArray).filter(x -> x.startsWith("김")).count();
System.out.println("김씨 : " + kimsCount2);
// 2. 이재영은 몇번 반복되나요?
int repeatCount = (int) Arrays.stream(stringArray).filter(x -> x.equals("이재영")).count();
System.out.println("이재영 : " + repeatCount);
// 3. 중복을 제거한 이름을 출력하세요.
Set<String> set = new HashSet<>();
for (String str : stringArray) {
set.add(str);
}
for (String str : set) {
System.out.println(str);
}
// 4. 중복을 제거한 이름을 오름차순으로 정렬하여 출력하세요.
System.out.println("=======오름차순=======");
for (String str : set.stream().sorted(Comparator.naturalOrder()).collect(Collectors.toList())) {
System.out.println(str);
}
}
private int getfirstNameCount(String[] s, String firstName) {
int increseCount = 0;
for (String str : s) {
if (str.startsWith(firstName)) {
increseCount++;
}
}
return increseCount;
}
}
Java1.8 람다로 작성되어 있습니다.
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.StringTokenizer;
/**
* @author : 염현우
* @date :2017. 9. 8.
* @description : 주어진 문자열(공백 없이 쉼표로 구분되어 있음)을 가지고 아래 문제에 대한 프로그램을 작성하세요.
* 이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌
*
* 1.김씨와 이씨는 각각 몇 명 인가요?
* 2."이재영"이란 이름이 몇 번 반복되나요?
* 3.중복을 제거한 이름을 출력하세요.
* 4.중복을 제거한 이름을 오름차순으로 정렬하여 출력하세요.
*
*/
public class Ex7 {
public static void main(String[] args) {
String str = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌";
System.out.println("김씨:" + output1(str,'김') + "명");
System.out.println("이씨:" + output1(str,'이') + "명");
output2(str,"이재영");
output3(str);
output4(str);
}
public static int output1(String str, char ch) {
StringTokenizer st = new StringTokenizer(str,",");
int count = 0;
while(st.hasMoreTokens()) {
String name = st.nextToken();
if(name.charAt(0) == ch)
++count;
}
return count;
}
public static int output2(String str, String name) {
StringTokenizer st = new StringTokenizer(str,",");
int count = 0;
while(st.hasMoreTokens()) {
String data = st.nextToken();
if(data.equals(name))
++count;
}
return count;
}
public static void output3(String str) {
StringTokenizer st = new StringTokenizer(str,",");
HashSet<String> set = new HashSet<String>();
while(st.hasMoreTokens()) {
set.add(st.nextToken());
}
Iterator<String> iter = set.iterator();
while(iter.hasNext()) {
System.out.print(iter.next()+",");
}
System.out.println();
}
public static void output4(String str) {
String[] data = str.split(",");
ArrayList<String> array = new ArrayList<String>();
for (int i = 0; i < data.length; i++) {
array.add(data[i]);
}
Collections.sort(array);
System.out.println(array.toString());
System.out.println();
}
}
풀이 방법은 거의 유사한 것 같아서, 자바8 Collection api 를 주로 활용했습니다.
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.StringTokenizer;
import static java.util.stream.Collectors.*;
public class Exams1 {
public static void main(String[] args) {
String input = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌";
StringTokenizer tokenizer = new StringTokenizer(input, ",");
List<String> names = new ArrayList<>(tokenizer.countTokens());
while (tokenizer.hasMoreTokens()) {
names.add(tokenizer.nextToken());
}
System.out.print("김씨와 이씨는 각각 몇 명 인가요? ");
names.stream()
.filter(name -> name.startsWith("김") || name.startsWith("이"))
.map(name -> name.substring(0, 1))
.collect(groupingBy(String::toString, counting()))
.forEach((name, count) ->
System.out.print("성: " + name + " / 명수: " + count + " "));
System.out.println();
System.out.println("\"이재영\"이란 이름이 몇 번 반복되나요? " + names.stream().filter("이재영"::equals).count());
List<String> distinctNames = names.stream().distinct().collect(toList());
System.out.println("중복을 제거한 이름을 출력하세요. " + distinctNames);
distinctNames.sort(Comparator.reverseOrder());
System.out.println("중복을 제거한 이름을 오름차순으로 정렬하여 출력하세요. " + distinctNames);
}
}
# -*- coding: utf-8 -*-
# python 3.6
inp = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌"
inp = inp.split(",")
print("이씨 수: ", len([chk for chk in inp if chk[0] == "이"]))
print("김씨 수: ", len([chk for chk in inp if chk[0] == "김"]))
print("이재영 수: ", inp.count("이재영"))
new_set = set(inp)
print(", ".join(new_set))
print(", ".join(sorted(new_set)))
파이썬입니다.
str_name = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌"
name = str_name.split(',')
print("1. 김씨는 %d명이고 이씨는 %d명이다." % (len([n for n in name if n[0] == '김']), len([n for n in name if n[0] == '이'])))
print("2. 이재영은 %d 반복된다." % name.count("이재영"))
print("3. 중복된 이름을 제거하면 %s 이다." % list(set(name)))
name2 = list(set(name))
name2.sort()
print("4. 이름을 제거후 정렬하면 %s 이다." % name2)
a='이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌'
b=a.split(',')
# 김씨와 이씨는 각각 몇 명 인가요?
kim=int()
lee=int()
for i in range(len(b)):
if b[i][0]=='김':
kim+=b[i].count('김')
for i in range(len(b)):
if b[i][0]=='이':
lee+=b[i].count('이')
print(kim)
print(lee)
# "이재영"이란 이름이 몇 번 반복되나요?
print(b.count('이재영'))
# 중복을 제거한 이름을 출력하세요.
print(set(b))
# 중복을 제거한 이름을 오름차순으로 정렬하여 출력하세요.
print(sorted(list(set(b))))
public static void main(String[] args) {
String str ="이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌";
int cnt1=0;
int cnt2=0;
int cnt3=0;
String tmpstr="";
String[] list = str.split(",");
List<String> arr = new ArrayList<String>();
//1.김씨와 이씨는 각각 몇 명 인가여?
for(String tmp: list){
if(tmp.substring(0,1).equals("김")){
cnt1++;
}
if(tmp.subSequence(0, 1).equals("이")){
cnt2++;
}
if(tmp.substring(0,3).equals("이재영")){
cnt3++;
}
}
System.out.println("김씨는 "+cnt1+"명 입니다.");
System.out.println("이씨는 "+cnt2+"명 입니다.");
//2."이재영"이란 이름이 몇번 반복되나여?
System.out.println("이재영이란 이름은"+cnt3+"번 반복됐습니다");
//3.중복을 제거한 이름을 출력하세요.
for(int i=0;i<list.length;i++){
for(int j=i+1;j<list.length;j++){
if(list[i].equals(list[j])){
list[j]="";
}
}
}
for(String tmp: list){
if(tmp!="") arr.add(tmp);
}
System.out.println("ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ중복을 제거한 후 이름 출력ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ");
System.out.println(arr);
Collections.sort(arr);
System.out.println("ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ정렬후 이름 출력ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ");
System.out.println(arr.toString());
}```{.java}
public static void main(String[] args) {
String str ="이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌";
int cnt1=0;
int cnt2=0;
int cnt3=0;
String tmpstr="";
String[] list = str.split(",");
List<String> arr = new ArrayList<String>();
//1.김씨와 이씨는 각각 몇 명 인가여?
for(String tmp: list){
if(tmp.substring(0,1).equals("김")){
cnt1++;
}
if(tmp.subSequence(0, 1).equals("이")){
cnt2++;
}
if(tmp.substring(0,3).equals("이재영")){
cnt3++;
}
}
System.out.println("김씨는 "+cnt1+"명 입니다.");
System.out.println("이씨는 "+cnt2+"명 입니다.");
//2."이재영"이란 이름이 몇번 반복되나여?
System.out.println("이재영이란 이름은"+cnt3+"번 반복됐습니다");
//3.중복을 제거한 이름을 출력하세요.
for(int i=0;i<list.length;i++){
for(int j=i+1;j<list.length;j++){
if(list[i].equals(list[j])){
list[j]="";
}
}
}
for(String tmp: list){
if(tmp!="") arr.add(tmp);
}
System.out.println("ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ중복을 제거한 후 이름 출력ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ");
System.out.println(arr);
Collections.sort(arr);
System.out.println("ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ정렬후 이름 출력ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ");
System.out.println(arr.toString());
}
```
package codingdojang;
import java.util.ArrayList; import java.util.Collections;
public class ex24 {
public static void main(String[] args) {
// TODO Auto-generated method stub
String s = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌";
ArrayList<String> par = new ArrayList<String>();
String[] parse = s.split(",");
for(int i=0; i<parse.length; i++) {
par.add(parse[i]);
}
int k = 0;
int l = 0;
int count = 0;
boolean kill = false;
for(int i=0; i<parse.length; i++) {
if(parse[i].charAt(0) == '김') {
k++;
}
if(parse[i].charAt(0) == '이') {
l++;
}
if(parse[i].equals("이재영")) {
count++;
}
}
for(int i=0; i<par.size(); i++) {
if(kill == true && par.get(i).equals("이재영")) {
par.remove(i);
}
if(par.get(i).equals("이재영")) {
kill = true;
}
}
System.out.println("1번 = "+k+" and "+l);
System.out.println("2번 = "+ count);
System.out.print("3번 = ");
for(int i=0; i<par.size(); i++) {
System.out.print(par.get(i)+ " ");
}
System.out.println();
System.out.print("4번 = ");
Collections.sort(par);
//Collections.reverse(par);
for(int i=0; i<par.size(); i++) {
System.out.print(par.get(i)+ " ");
}
}
}
names = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌"
name_list = names.split(',')
#1
a = list(i[0] for i in name_list)
print("이씨는 %s명, 김씨는 %s명입니다." % (a.count("이"),a.count("김")))
#2
x = 0
for i in name_list:
if i == "이재영":
x += 1
print("이재영은 %d번 반복됩니다." %x)
# answer 3
sorted_name = list(set(name_list))
print(sorted_name)
#answer 4
print(sorted(sorted_name))
제가 봐도 더럽네요
public class test_sort {
public static void main(String[] args) {
String str = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌";
String[] strs = str.split(",");
int e = 0;
int kim = 0;
int ejy = 0;
ArrayList<String> arr = new ArrayList<>();
// 1. 성, 이름 count
for (int i = 0; i < strs.length; i++) {
if (strs[i].substring(0, 1).equals("이")) {
e++;
} else if (strs[i].substring(0, 1).equals("김")) {
kim++;
}
if (strs[i].equals("이재영")) {
ejy++;
}
arr.add(strs[i]);
}
// 2.중복 제거
for (int i = 0; i < arr.size(); i++) {
for (int j = 0; j < arr.size(); j++) {
if (arr.get(i).equals(arr.get(j)) && i != j) {
arr.remove(j);
}
}
}
// 3.정렬
Collections.sort(arr);
System.out.print("정렬 : ");
for (int i = 0; i < arr.size(); i++) {
System.out.print(arr.get(i) + " ");
}
System.out.println();
System.out.println("김씨 : " + kim);
System.out.println("이씨 : " + e);
System.out.println("이재영 : " + ejy);
}
}
function cynap1() {
var kim = 0;
var lee = 0;
for (var i=0; i<s.length; i++){
if(s[i][0] === '이') lee++;
if(s[i][0] === '김') kim++;
}
return "kim:"+ kim + " lee:" +lee;
}
function cynap2() {
var name = '이재영';
var count = 0;
for (var i=0; i<s.length; i++){
if(s[i] === name){
count++;
}
}
return '이재영:'+ count;
}
function cynap3() {
var uniq =[];
for (var i=0; i<s.length; i++) {
var uni_count=0;
for (var j = 0; j < s.length; j++) {
if(s[i] === s[j]) uni_count++;
}
if(uni_count<2) uniq.push(s[i]);
}
return uniq;
}
function cynap4() {
return cynap3().sort();
}
var s = ['이유덕', '이재영', '권종표', '이재영', '박민호', '강상희',
'이재영', '김지완', '최승혁', '이성연', '박영서',
'박민호', '전경헌', '송정환', '김재성', '이유덕', '전경헌'];
console.log(cynap1(s));
console.log(cynap2(s));
console.log(cynap3(s));
console.log(cynap4(s));
package test;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedHashSet;
public class test01 {
public static void main(String[] args)
{
String str = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌";
String[] name = str.split(",");
int kim = 0;
int lee = 0;
int ljy = 0;
//1번 문제
for(int i = 0; i < name.length; i++)
{
if(name[i].substring(0, 1).equals("김"))
{
kim++;
}
if(name[i].substring(0, 1).equals("이"))
{
lee++;
}
}
System.out.println("1. 김씨와 이씨는 각각 몇 명 인가요?" +" "+ kim +", " + lee);
//2번 문제
for(int i = 0; i < name.length; i++)
{
if(name[i].substring(0,3).equals("이재영"))
{
ljy++;
}
}
System.out.println("2. \"이재영\"이란 이름이 몇 번 반복되나요?"+ " " + ljy);
//3번 문제
ArrayList<String> arraylist = new ArrayList<String>();
for(int i=0; i<name.length; i++)
{
if( !arraylist.contains(name[i]) )
arraylist.add(name[i]);
}
String newarray[] = arraylist.toArray(new String[arraylist.size()]);
System.out.print("3. 중복을 제거한 이름 : ");
for(int i=0; i<newarray.length; i++)
System.out.print(newarray[i] + ((newarray.length == i + 1)?"\n":", "));
//4번 문제
Arrays.sort(newarray);
System.out.print("4. 중복을 제거한 이름을 오름차순으로 : ");
for(int i=0; i<newarray.length; i++)
System.out.print(newarray[i] + ((newarray.length == i + 1)?"\n":", "));
}
}
namelist = ['이유덕','이재영','권종표','이재영','박민호','강상희','이재영','김지완','최승혁','이성연','박영서','박민호','전경헌','송정환','김재성','이유덕','전경헌']
#1 중복 제외하고, 이씨, 김씨 세기
count_lee = 0
count_kim = 0
for i in set(namelist):
if i[0] == '이':
count_lee += 1
elif i[0] == '김':
count_kim += 1
print(count_lee)
print(count_kim)
#2 이재영 이름 세기
count_이재영 = 0
for i in namelist:
if i == '이재영':
count_이재영 += 1
else:
continue
print(count_이재영)
#3 중복을 제거한 이름
print(set(namelist))
#4 오름차순으로 정렬하여 출력
print(sorted(set(namelist)))
# 한글 처리 in Atom 1.21.1 + Anaconda(Python 3.6.3)
import sys
import io
sys.stdout = io.TextIOWrapper(sys.stdout.detach(), encoding='utf-8')
sys.stderr = io.TextIOWrapper(sys.stderr.detach(), encoding='utf-8')
name_string = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌"
names = name_string.split(',')
# 김씨와 이씨는 각각 몇 명 인가요?
count = 0
for name in names:
if name[0]=="김" or name[0]=="이" :
count += 1
print("김씨, 이씨는 총",count,"명입니다")
# "이재영"이란 이름이 몇 번 반복되나요?
count = 0
for name in names:
if name=="이재영" :
count += 1
print("이재영",count,"명입니다")
# 중복을 제거한 이름을 출력하세요.
names = set(names)
print(','.join(names))
# 중복을 제거한 이름을 오름차순으로 정렬하여 출력하세요.
names = list(names)
names.sort()
print(','.join(names))
python
names = '이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,\
이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌'
namelist = names.split(',')
print(namelist)
#1
many = 0
for i in namelist:
if list(i)[0] == '이':
many += 1
if list(i)[0] == '김':
many += 1
print("김씨와 이씨는 각각 %d 명 입니다." % many)
#2
people = 0
for i in namelist:
if i == '이재영':
people += 1
print('이재영 이라는 이름은 %d번 반복됩니다.' % people)
#3
for i in namelist:
while namelist.count(i) > 1:
print(i)
namelist.remove(i)
print(namelist)
#4
print(sorted(namelist))
name = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌"
class cynap: #사이냅을 이렇게 쓰는것일까요...
def __init__(self, name):
self.name = name.split(",") # 문자열을 리스트로 분리
self.shurui = set(self.name) # 집합화하여 중복되는 이름 제거
def Lee_and_Kim(self):
for i in self.name:
if i[0] == "이": # 이씨일 경우
print(i) # 출력
elif i[0] == "김": # 김씨일 경우
print(i) # 출력
def LEEJAI(self): # 이재영 세기
self.cnt = 0
for i in self.name:
if i == "이재영":
self.cnt += 1
print(self.cnt)
def SHURUI(self): # 이름 종류
print (self.shurui)
def SORTED(self): # 이름 종류의 정렬
print (sorted(list(self.shurui)))
cy = cynap(name)
cy.Lee_and_Kim()
cy.LEEJAI()
cy.SHURUI()
cy.SORTED()
PYTHON
names = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌"
lst = names.split(",")
# print(lst.count("이유덕"))
# 1)김씨와 이씨는 각각 몇 명 인가요?
find_family_name = lambda x : x[0]
dic = {"김":[find_family_name(n) for n in lst ].count("김") , "이":[find_family_name(n) for n in lst ].count("이")}
print(dic)
# 2)"이재영"이란 이름이 몇 번 반복되나요?
name_count = names.count("이재영")
print(name_count)
# 3)중복을 제거한 이름을 출력하세요.
set_a = set(lst)
print(set_a)
# 4)중복을 제거한 이름을 오름차순으로 정렬하여 출력하세요.
lst01 = list(set_a)
lst01.sort()
print(lst01)
import java.util.*;
import java.util.ArrayList;
import java.util.Arrays;
public class CodingAttack {
static int first;
static int same;
public static void main(String[] args) {
String List ="이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌";
int k = Search(List,"김");
int l = Search(List,"이");
System.out.println("김씨의 인원수는?"+k);
System.out.println("이씨의 인원수는?"+l);
int over_lap = overlap(List,"이재영");
System.out.println("이재영의 이름을 가진 사람수는?"+over_lap);
Same_Del(List);
} // Main
public static int Search(String List,String f) {
String Name[] =List.split(",");
for(int i=0 ; i<Name.length ; i++ ) {
//System.out.println("Name["+i+"] : "+Name[i]);
//System.out.println("i 크기 "+ i);
if(Name[i].startsWith(f)) {
first++;
}
}
return first;
} //Search Out
public static int overlap(String List,String full_name) {
String Name[] = List.split(",");
ArrayList<String> name_Arraylist = new ArrayList<String>();
for(int i=0; i<Name.length;i++) {
if(Name[i].equals(full_name))
{
name_Arraylist.add(Name[i]);
}
same = name_Arraylist.size();
}
return same;
} //overlap Out
public static void Same_Del(String List) {
String Name[] = List.split(",");
boolean check=false;
ArrayList<String> name_ArrayList = new ArrayList<String>();
for(int i=0 ; i<Name.length; i++) {
String temp = Name[i];
//System.out.println("임시저장값 "+temp);
for(int j=0 ; j<name_ArrayList.size();j++) {
if(name_ArrayList.get(j).equals(temp)) {
check=true;
}
}
if(check) {
check = false;
} else {
name_ArrayList.add(Name[i]);
}
}
System.out.println("중복된 이름을 뺀 이름은?"+name_ArrayList.toString());
Collections.sort(name_ArrayList);
System.out.println("중복된 이름을 빼고 순차적으로 나열한것은?"+name_ArrayList.toString());
}//Same_Del Out
}
name = '이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌'
full_name = name.split(',')
last_name = []
for i in full_name:
last_name = last_name + [i[0]]
print('김씨: {}명, 이씨: {}명'.format(last_name.count('김'),last_name.count('이')))
print('"이재영"이름은 {}번 반복'.format(full_name.count('이재영')))
set_name=list(set(full_name))
print('중복 제거 이름: ',set_name)
set_name.sort()
print('오름 차순 이름: ',set_name)
class Program
{
static void Main(string[] args)
{
string[] names = { "이유덕", "이재영", "권종표", "이재영", "박민호", "강상희", "이재영", "김지완", "최승혁", "이성연", "박영서", "박민호", "전경헌", "송정환", "김재성", "이유덕", "전경헌"};
string[] nameResult;
List<string> namelist = new List<string>();
int kimCount = 0;
int leeCount = 0;
int ljyCount = 0;
foreach (string name in names)
{
if(name[0] == '김')
{
kimCount += 1;
}
else if(name[0] == '이')
{
leeCount += 0;
}
else if(name == "이재영")
{
ljyCount += 0;
}
int containcount = 0;
for(int i = 0; i < names.Count(); i++)
{
if(name == names[i])
{
containcount++;
}
}
if (containcount < 2)
{
namelist.Add(name);
}
}
string result = string.Format("김씨: {0}, 이씨: {1}, 이재영:{2}", kimCount, leeCount, ljyCount);
Console.WriteLine(result);
namelist.Sort();
foreach (string n in namelist)
{
Console.WriteLine(n);
}
}
# coding: utf8
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
names=u"이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌"
a=u"이재영"
kim=u"김"
lee=u"이"
i=0; k=0; l=0
flag=0
namelst=names.split(',')
for one in namelst:
if one[0] == kim:
k=k+1
if one[0] == lee:
l=l+1
if one == a:
i=i+1
print k,u"김씨"
print l,u"이씨"
print i,u"이재영"
print u"중복제거 이름:"
once=list(set(namelst))
for j in range(0,len(once)):
print once[j]
print u"중복제거 이름 오름차순 정렬:"
once=list(set(namelst))
once.sort()
for j in range(0,len(once)):
print once[j]
names = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호, 전경헌,송정환,김재성,이유덕,전경헌".split(",")
a=[ i[0] for i in names ] print("김씨 : %d\n이씨 : %d\n"%(a.count("김"), a.count("이")))
print(names.count("이재영"))
uniq_names = list(set(names)) print(uniq_names)
uniq_names.sort() print(uniq_names)
public static void main(String[] args) { String name = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌"; String []name_List = new String[100]; int list_Num = 0; int kimCount = 0; int leeCount = 0; int ljyCount = 0;
Arrays.fill(name_List, "");
for(int i = 0; i < name.length(); i++)
{
if(name.charAt(i)==',')
{
list_Num++;
continue;
}
name_List[list_Num] += name.charAt(i);
}
for(int i = 0; i < list_Num; i++)
{
if(name_List[i].charAt(0)=='김')
{
kimCount++;
}
if(name_List[i].charAt(0)=='이')
{
leeCount++;
}
if(name_List[i]=="이재영")
{
ljyCount++;
}
}
System.out.println("김씨는 "+ kimCount + "명이고, 이씨는 " + leeCount + "명 입니다.");
int while_Count = list_Num;
while(while_Count > 0)
{
for(int i = 0; i < list_Num; i++)
{
for(int j = i+1; j < list_Num; j++)
{
if(name_List[i].equals(name_List[j]))
{
name_List[j] = "";
}
}
}
int count = 0;
for(int i = 0; i < list_Num; i++)
{
if(name_List[i]=="")
{
count = i;
while(name_List[count]=="")
{
count++;
}
name_List[i] = name_List[count];
list_Num--;
}
}
while_Count--;
}
for(int i = 0; i < list_Num; i++)
{
System.out.println(name_List[i]);
}
Arrays.sort(name_List, 0, list_Num);
for(int i = 0; i < list_Num; i++)
{
System.out.println(name_List[i]);
}
}
a='이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌'
an=len(a)
x=0
y=2
b=[]
while y<an:
b.append(a[x:y+1])
x=x+4
y=y+4
c=[]
for x in b:
c.append(x[0])
y=0
for x in c:
if(x=='김' or x=='이'):
y=y+1
print(y)
d=[]
for x in b:
if not(d.count(x)):
d.append(x)
d.sort()
print(d)
names='이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌'
names=names.split(',')
k_count=0
l_count=0
for i in names:
if i[0]=='김':
k_count+=1
elif i[0]=='이':
l_count+=1
print('김씨와 이씨는 각각 {}명, {}명'.format(k_count, l_count))
print('이재영은 총 {}명'.format(names.count('이재영')))
re_names=list(set(names))
print('중복제거: '+', '.join(re_names))
re_names.sort()
re_names.reverse()
print('중복제거 + 오름차순: '+', '.join(re_names))
data="이유덕,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌"
def listfilter(data):
# 문자열 자료를 이름 리스트형 자료로 변환
datalist =[]
m = 0
n = 3
a = data[m:n]
datalist.append(a)
datalen = len(data)
while m < datalen:
n += 4
m += 4
a = data[m:n]
datalist.append(a)
datalist.pop()
# 자료 처리를 위한 객체 정의
kim = 0
lee = 0
leejy = 0
filterlist = []
result = []
# '김'씨 성을 가진 인원 , '이'씨성을 가진 인원, '이재명'이란 이름이 반복된 횟수 계산
for i in datalist:
if i[0] == '김':
kim += 1
if i[0] == '이':
lee += 1
if i =='이재영':
leejy += 1
print(" 1) '김'씨 성을 가진 사람들 인원: %d 명" % kim, "\n")
print(" 2) '이'씨 성을 가진 사람들 인원: %d 명" % lee, "\n")
print(" 3) '이재영'이라는 이름이 반복된 횟수: %d 회" % leejy, "\n")
# 리스트에서 이름이 중복된 경우 한개만 남기고 지우기
filterlist = list(set(datalist))
print(" 4) 중복이름 제거 리스트: ","\n\n", filterlist,"\n")
# 중복이름 제거된 리스트의 오름차순 정렬
result = sorted(filterlist)
print(" 5) 중복이름 제거 리스트 오름차순 정렬: ","\n\n", result)
listfilter(data)
1) '김'씨 성을 가진 사람들 인원: 2 명
2) '이'씨 성을 가진 사람들 인원: 5 명
3) '이재영'이라는 이름이 반복된 횟수: 2 회
4) 중복이름 제거 리스트:
['이성연', '이재영', '강상희', '김지완', '박영서', '김재성', '박민호', '권종표', '최승혁', '전경헌', '송정환', '이유덕']
5) 중복이름 제거 리스트 오름차순 정렬:
['강상희', '권종표', '김재성', '김지완', '박민호', '박영서', '송정환', '이성연', '이유덕', '이재영', '전경헌', '최승혁']
name ="이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌"
# 문제 1번
pr1 = [name for name in name.split(',') if name.find("김")>=0 ]
pr11 = [name for name in name.split(',') if name.find("이")>=0 ]
print("문제 1번 : 김씨 {0}명, 이씨 {1}명".format(len(pr1),len(pr11)))
# 문제 2
pr2 = sum([1 for name in name.split(',') if name=='이재영' ])
print("문제 2번 : {0} 번 ".format(pr2))
# 문제 3
pr3 = set(name.split(','))
print("문제 3번 : ",end ="")
for x in pr3 : print(x,'',end="")
print()
# 문제 4
pr4 = list(pr3)
pr4.sort()
print("문제 4번 : ",end ="")
for x in pr4 : print(x,'',end="")
JAVA
import java.util.*;
public class Synapsoft { //JAVA
private static Synapsoft synap;
private static String[] names = null;
private static int num_Kim, num_Lee;
private static int num_Repeat;
private static Vector<String> remove_Overlap = new Vector<String>();
private static Vector<String> ascending_Sort = new Vector<String>();
public static void main(String[] args) {
synap = new Synapsoft();
names = new String[] {"이유덕","이재영","권종표","이재영",
"박민호","강상희","이재영","김지완",
"최승혁","이성연","박영서","박민호",
"전경헌","송정환","김재성","이유덕","전경헌"};
num_Kim = synap.findFamilyName(names).get(0);
num_Lee = synap.findFamilyName(names).get(1);
num_Repeat = synap.findRepeat(names);
remove_Overlap = synap.removeOverlap(names);
ascending_Sort = synap.ascendingSort(remove_Overlap);
System.out.print("1.김씨와 이씨는 각각 몇 명 인가요?: ");
System.out.println("김씨는 " + num_Kim + " 명 , 이씨는 " + num_Lee + " 명 입니다.");
System.out.print("2.이재영 이란 이름이 몇 번 반복되나요?: ");
System.out.println( num_Repeat + " 번 반복됩니다.");
System.out.println("3.중복을 제거한 이름을 출력하세요.");
System.out.println( remove_Overlap );
System.out.println("4.중복을 제거한 이름을 오름차순으로 정렬하여 출력하세요.");
System.out.println( ascending_Sort );
}
// 1. charAt 사용, 추출
public ArrayList<Integer> findFamilyName(String[] names) {
int nKim=0, nLee=0;
ArrayList<Integer> getArray = new ArrayList<Integer>(2);
for(String name : names ) {
if(name.charAt(0) == '김') nKim++;
if(name.charAt(0) == '이') nLee++;
}
getArray.add(nKim);
getArray.add(nLee);
return getArray;
}
// 2. equals 사용, 반복
public int findRepeat(String[] names) {
int numRepeat=0;
for(String name : names) {
if(name.equals("이재영")) numRepeat++;
}
return numRepeat;
}
// 3. 중복 제거
public Vector<String> removeOverlap(String[] names) {
Vector<String> vectors = new Vector<String>();
for (String name : names) {
int a = 0;
for (String vector : vectors)
{
if (name.equals(vector)) {
a = 1;
break;
}
}
if (a==0) vectors.add(name);
}
return vectors;
}
// 4. 오름차순 정렬
public Vector<String> ascendingSort(Vector<String> vectors) {
vectors.sort(null);
return vectors;
}
}
Console
1.김씨와 이씨는 각각 몇 명 인가요?: 김씨는 2 명 , 이씨는 6 명 입니다.
2.이재영 이란 이름이 몇 번 반복되나요?: 3 번 반복됩니다.
3.중복을 제거한 이름을 출력하세요.
[이유덕, 이재영, 권종표, 박민호, 강상희, 김지완, 최승혁, 이성연, 박영서, 전경헌, 송정환, 김재성]
4.중복을 제거한 이름을 오름차순으로 정렬하여 출력하세요.
[강상희, 권종표, 김재성, 김지완, 박민호, 박영서, 송정환, 이성연, 이유덕, 이재영, 전경헌, 최승혁]
import re
s = '이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌'
arr = s.replace(' ' , '').split(',')
r1 = 0
r2 = 0
for w in arr :
w = w.replace(' ' , '')
# 김시와 이씨 찾기
if re.compile('^(김|이)').match(w) :
r1 += 1
# 이재영 찾기
if re.compile('(이재영)').match(w) :
r2 += 1
# 중복 제거
print(r1)
print(r2)
print(list(set(arr)))
print(sorted(list(set(arr))))
import java.util.Arrays;
import java.util.TreeSet;
public class Main {
public static void main(String[] args) {
// 이름들이 담긴 문자열
String name = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌";
// TreeSet에 특징을 이용하여 중복을 제거할 TreeSet
TreeSet<String> ts = new TreeSet<String>();
// String에 Split메소드를 이용해서 ','를 기준으로 문자열을 배열로 분리
String[] sp = name.split(",");
// 중복제거가 된 값을 담을 배열
String[] sr;
// 이씨로 시작 하는 사람들의 갯수를 담을 변수
int count1 = 0;
// 이재영의 반복횟수를 담을 변수
int count2 = 0;
for (int i = 0; i < sp.length; i++) {
// TreeSet에 담아서 중복을 제거
ts.add(sp[i]);
// String에 startsWith메소드를 이용해서 '이','김'씨로 시작 하는 사람의 갯수 셈
if (sp[i].startsWith("이") || sp[i].startsWith("김"))
count1++;
// String에 contains메소드를 이용하여 "이재영"이 몇번 반복 되는지 갯수를 셈
if (sp[i].contains("이재영"))
count2++;
}
System.out.println("이씨로 시작하는 사람 : " + count1);
System.out.println("이재영 반복 횟수 : " + count2);
// TreeSet에 toArray 메소드를 이용해서 TreeSet을 String 배열로 변환
sr = ts.toArray(new String[ts.size()]);
// 자바에서 제공하는 Arrays.sort를 이용하여 정렬
Arrays.sort(sr);
for (int i = 0; i < sr.length; i++) {
System.out.print(sr[i] + " ");
}
}
}
String checkVal = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌";
int kimNum = 0;
int leeNum = 0;
int ljyNum = 0;
String checkValarr[] = checkVal.split(",");
ArrayList checkedName = new ArrayList();
for(int i=0; i<checkValarr.length; i++)
{
String val = checkValarr[i];
if(val.startsWith("김"))
{
kimNum++;
}
if(val.startsWith("이"))
{
leeNum++;
if("이재영".equals(val))
{
ljyNum++;
}
}
if(checkedName.size()!=0 && !( checkedName.contains(val)))
{
checkedName.add(val);
}else if(checkedName.size()==0)
{
checkedName.add(val);
}
}
System.out.println("김씨 : "+kimNum);
System.out.println("이씨 : "+leeNum);
System.out.println("이재영씨 : "+ljyNum);
System.out.println("미중복 개수 : "+checkedName.size());
Collections.sort(checkedName);
Collections.reverse(checkedName);
System.out.println("정렬 후 출력 : "+checkedName.size());
for(int q=0; q<checkedName.size()-1; q++)
{
System.out.println(checkedName.get(q));
}
kimList = []
leeList = []
def practice1():
for temp in nameList:
if "김" in temp:
kimList.append(temp)
elif "이" in temp:
leeList.append(temp)
print("1. 김씨와 이씨는 각각 몇 명인가요?" + " 김씨 : " + str(len(kimList)) + ", 이씨 : " + str(len(leeList)))
def pracitce2():
count = 0
for temp in nameList:
if "이재영" in temp:
count += 1
return count
def practice3():
no_repeat_list = list(set(nameList))
return no_repeat_list
def practice4():
no_repeat_list = practice3()
no_repeat_list.sort()
return no_repeat_list
#-*- coding: utf-8 -*-
# initdb -E UTF-8 --lc-collate=C -W -D <위치>
list_of_name = ['이유덕','이재영','권종표','이재영','박민호','강상희','이재영','김지완','최승혁','이성연','박영서','박민호','전경헌','송정환','김재성','이유덕','전경헌']
def find_name(user_input_name):
user_name=[ i[0] for i in list_of_name ]
count_name = user_name.count(user_input_name)
print("이름은", count_name,"나왔습니다.")
def count_name_of_list(user_input_name):
count = 0
x = 0
for _ in list_of_name:
if list_of_name[x] == user_input_name:
count = count + 1
x = x + 1
return (count)
print("찿고 싶은이름이 있으면 1번")
print("몇번 반복되는지 확일할려면 2번")
print("중복한 이름을 제거하고 싶으면 3번")
print("중복을 제거한 이름을 오름차순으로 정렬할려면 4번")
print("리스트를 확인하려면 5번")
print("0번을 입력하면 끝납니다.")
a = 10000
while a != 0:
user_input = input("숫자를 입력하세요: ")
if user_input == '1':
user_input_name = input("이름을 입력하세요: ")
find_name(user_input_name)
elif user_input == '2':
user_input_name = input("이름을 입력하세요: ")
count1 = count_name_of_list(user_input_name)
print(user_input_name, ' ', count1, "번 반복되었습니다.")
elif user_input == '3':
re_name_is = set(list_of_name)
print("중복을 제거한 이름은 ", re_name_is,"입니다")
elif user_input == '4':
re_name_is = set(list_of_name)
re_name_is = list(re_name_is)
re_name_is.sort()
print("중복을 제거하고 정렬한 이름은", re_name_is, "입니다.")
elif user_input == '5':
print(list_of_name)
elif user_input == '0':
break
else:
print("잘못입력하셨습니다.")
continue
print("즐거운 하루되세요")
name = '이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌'
# 김씨와 이씨는 각각 몇 명 인가요?
KL = [i[0] for i in name.split(',')]
print(KL.count('김'), KL.count('이'))
# "이재영"이란 이름이 몇 번 반복되나요?
print(name.count('이재영'))
# 중복을 제거한 이름을 출력하세요.
print(set(name.split(",")))
# 중복을 제거한 이름을 오름차순으로 정렬하여 출력하세요.
print(sorted(set(name.split(","))))
python 3.6
names = '이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌'
names_list = names.split(',')
# 1
family_names = [name[0] for name in names_list]
print(family_names.count('김'), family_names.count('이'))
# 2
print(names_list.count('이재영'))
# 3
for name in names_list:
if names_list.count(name) > 1:
for i in range(names_list.count(name)-1):
names_list.remove(name)
print(','.join(names_list))
# 4
a = 1
while a < len(names_list)-1:
for b in range(a+1):
if names_list[b][0] > names_list[b+1][0]:
names_list[b], names_list[b+1] = names_list[b+1], names_list[b]
a += 1
print(','.join(names_list))
파이썬 입니다.
data='이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌'
kcnt=0
lcnt=0
ljy=0
S=list()
for name in data.split(','):
S.append(name)
if name[0]=='이':
lcnt=lcnt+1
if name=='이재영':
ljy=ljy+1
if name[0]=='김':
kcnt=kcnt+1
print('1. 김씨는 %d명, 이씨는 %d명'%(kcnt,lcnt))
print('2. 이재영은 %d번 반복된다.'%ljy)
print('3. '+",".join(set(S)))
print('4. '+",".join(sorted(list(set(S))))) ##.sort()를 써서 할 수도 있다. 이 때는 먼저 정렬한 리스트를 저장하고 출력해줘야한다.
파이썬 입니다.
#데이터
data = ['이유덕','이재영','권종표','이재영','박민호','강상희','이재영','김지완','최승혁','이성연','박영서','박민호','전경헌','송정환','김재성','이유덕','전경헌']
#no1
kims = len(list(filter(lambda name: name.startswith('김'), data)))
lees = len(list(filter(lambda name: name.startswith('이'), data)))
print('김씨 : ', kims, '명')
print('이씨 : ', lees, '명')
#no2
lee_jae_youngs = len(list(filter(lambda name: name == '이재영', data)))
print('이재영 등장회수:', lee_jae_youngs, '회')
#no3
pure_names = set(list(data))
print('중복 제거한 이름:', pure_names)
#no4
sorted_names = sorted(pure_names)
print('오름차순 이름:', sorted_names)
data = '이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌'
//1번
sdata = data.split(',')
kim = 0
lee = 0
for x in range(len(sdata)):
if sdata[x][0] == '김':
kim += 1
elif sdata[x][0] == '이':
lee += 1
print(kim)
print(lee)
//2번
print(sdata.count('이재영'))
//3번
print(list(set(sdata)))
//4번
print(sorted(list(set(sdata))))
name_list = ['이유덕','이재영','권종표','이재영','박민호','강상희', \
'이재영','김지완','최승혁','이성연','박영서','박민호', \
'전경헌','송정환','김재성','이유덕','전경헌']
if __name__ == '__main__':
# 김씨와 이씨는 각각 몇 명 인가요?
kim_count = 0
lee_count = 0
for name in name_list:
if name.startswith('김'):
kim_count += 1
elif name.startswith('이'):
lee_count += 1
else:
continue
print('Kim\'s Count:', kim_count)
print('Lee\'s Count:', lee_count)
# "이재영"이란 이름이 몇 번 반복되나요?
print(name_list.count('이재영'))
# 중복을 제거한 이름을 출력하세요.
print(set(name_list))
# 중복을 제거한 이름을 오름차순으로 정렬하여 출력하세요.
print(sorted(set(name_list)))
자바에요...허허
private String[] arr = new String[]{"이유덕","이재영","권종표","이재영","박민호","강상희","이재영","김지완","최승혁","이성연","박영서","박민호","전경헌","송정환","김재성","이유덕","전경헌"};
public static void main(String[] args)
{
main m = new main();
HashMap<String, Integer> map = m.FirstNameCnt();
System.out.println("김씨 사람: "+map.get("김"));
System.out.println("이씨 사람: "+map.get("이"));
System.out.println("-----------------------------------------");
System.out.println("이재영 갯수: "+m.findName("이재영"));
System.out.println("-----------------------------------------");
String[] overlapArr = m.overlapDel();
for(String str : overlapArr)
{
System.out.println(str);
}
System.out.println("-----------------------------------------");
//오름차순
Arrays.sort(overlapArr);
for(String str : overlapArr)
{
System.out.println(str);
}
}
//1번
public HashMap<String, Integer> FirstNameCnt()
{
Integer cnt = 0;
String tmp;
HashMap<String, Integer> map = new HashMap<>();
for(String str : arr)
{
tmp = str.substring(0,1);
if(map.containsKey(tmp))
{
cnt = (Integer)map.get(tmp);
map.put(tmp, cnt+1);
}
else
{
cnt = 1;
map.put(tmp, cnt);
}
}
return map;
}
//2번
public int findName(String name)
{
int cnt = 0;
for(String str : arr)
{
if(name.equals(str))
cnt++;
}
return cnt;
}
//중복제거
public String[] overlapDel()
{
ArrayList<String> tmpList = new ArrayList<>();
String[] res;
String tmp = "";
for(String str : arr)
{
if(tmp.isEmpty())
{
tmpList.add(str);
tmp = str;
}
else
{
if(!tmpList.contains(str))
{
tmpList.add(str);
tmp = str;
}
}
}
res = new String[tmpList.size()];
tmpList.toArray(res);
return res;
}
s = "이유덕, 이재영, 권종표, 이재영, 박민호, 강상희, 이재영, 김지완, 최승혁, 이성연, 박영서, 박민호, 전경헌, 송정환, 김재성, 이유덕, 전경헌"
S = s.replace(" ", "")
names = S.split(',')
#1. 중복을 제거하세요
print(set(names))
#2. #1을 오름차순으로 정렬하세요
print(sorted(list(set(names))))
#3. 김씨와 이씨는 몇명일까요
g1 = sorted(list(set(names)))
kim = 0
lee = 0
for name in g1:
if name[0] == '김':
kim += 1
elif name[0] == '이':
lee += 1
else:
pass
print(kim)
print(lee)
#4. 이재영이란 이름은 몇 번 반복 되나요
findljy = list(filter(lambda x: x == '이재영', names))
print(len(findljy))
import java.util.*;
public class synapSoft {
public static void main(String[] args) {
String s = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌";
int i;
int kim=0,lee=0;
int k=0;
// 1번
for(i=0;i<s.length();i+=4){
if(s.charAt(i)=='이')
lee++;
else if(s.charAt(i) =='김')
kim++;
}
System.out.printf("김씨:%d명,이씨:%d명\n",kim,lee);
// 2번
for(i=0;i<s.length();i+=4){
String tmp = s.substring(i, i+3);
if(tmp.matches("이재영"))
k++;
}
System.out.println("이재영은 " + k + "번 있습니다.");
// 3번
Set set = new HashSet();
for(i=0; i<s.length(); i+=4){
String tmp = s.substring(i, i+3);
set.add(tmp);
}
System.out.println(set);
// 4번
List list = new LinkedList(set);
Collections.sort(list);
System.out.println(list);
}
}
import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set;
public class level_1_synapsoft_interview {
public static void main(String[] args) {
String names = "이유덕,이재영,권종표,이재영,박민호,강상회,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌";
String[] splitnames = names.split(","); // ","을 기준으로 이름들을 배열에 쪼개넣음.
int Lee = 0; // 이씨성 count.
int Kim = 0; // 김씨성 count.
int namecount = 0; // 이재영 count.
for(int i = 0; i < splitnames.length; i++) // 김씨와 이씨가 각각 몇명인지.
{
char firstname = 0;
firstname = splitnames[i].charAt(0);
if(firstname == '이')
{
Lee++;
}
else if(firstname == '김')
{
Kim++;
}
}
System.out.print("김씨성 인원 : " + Kim + " ");
System.out.println("이씨성 인원 : " + Lee);
for(int i = 0; i < splitnames.length; i++) // 이재영이 몇번 나오는지 찾기.
{
if(splitnames[i].contains("이재영"))
{
namecount++;
}
}
System.out.println("이재영이 나온 횟수 : " + namecount);
Set<String> removeoverlap = new HashSet<String>(); // 중복되는 이름 제거.
for(int i = 0; i < splitnames.length; i++)
{
removeoverlap.add(splitnames[i]);
}
for(String str: splitnames)
{
removeoverlap.add(str);
}
System.out.println(removeoverlap); // 결과 : [김재성, 김지완, 권종표, 이성연, 전경헌, 박민호, 박영서, 송정환, 이유덕, 이재영, 강상회, 최승혁]
List<String> sortname = new ArrayList<String>(removeoverlap); // 중복 제거된 이름들을 오름차순으로 재정렬.
Collections.sort(sortname);
System.out.println(sortname);
}
}
names = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌".split(",")
Lee = 0
Kim = 0
for i in names:
if i[0] == '이':
Lee+=1
elif i[0] == '김':
Kim+=1
print(Lee); print(Kim);
print(names.count("이재영"))
no_repeat_names = list(set(names))
print(no_repeat_names)
no_repeat_names.sort()
print(no_repeat_names)
k_pattern = r"김."
l_pattern = r"이."
ljy_pattern = r"이재영"
k_num = 0; l_num = 0; ljy_num = 0;
for i in name_list
ismatch(k_pattern, i) ? k_num +=1 : k_num
ismatch(l_pattern, i) ? l_num += 1 : l_num
ismatch(ljy_pattern, i) ? ljy_num += 1 : ljy_num
end
new_name_list = unique(name_list)
sort(new_name_list)
Julia
x <- c("이유덕","이재영","권종표","이재영","박민호","강상희","이재영","김지완","최승혁","이성연","박영서","박민호","전경헌","송정환","김재성","이유덕","전경헌")
# 1번 문제
name1<- table(substr(x,1,1))
kim <- name1["김"]; kim
lee <- name1["이"]; lee
# 2번 문제
name2 <- table(x)
leejaeyoung <- name2["이재영"]; leejaeyoung
# 3번 문제
unique(x)
# 4번 문제
sort(unique(x))
a="이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌"
print("김씨 수:",a.count("김"))
print("이씨 수:",a.count("이"))
print("이재영 이름 반복수:",a.count("이재영"))
b=a.split(",")
set_b=set(b)
print("중복이 제거된 이름:",set_b)
c=sorted(set_b)
print("중복제거 이름 오름차순 정렬:",c)
r로 풀었습니다.
```{r}
s<-c('이유덕','이재영','권종표','이재영','박민호','강상희','이재영','김지완','최승혁','이성연','박영서','박민호','전경헌','송정환','김재성','이유덕','전경헌')
s1<-unique(s)
n<-0
m<-0
s2<-NULL
for(i in s1){
s2<-paste(s2,i)
if(substr(i, 1, 1)=='김'){
n<-n+1
}else{
if(substr(i, 1, 1)=='이'){
m<-m+1
}
}
}
s3<-sort(s1)
s4<-NULL
for(i in s3){
s4<-paste(s4,i)
}
paste0('김씨는 ',n,'명이고, ', '이씨는 ', m,'명임.', ' 이재영은 ',length(s[s=='이재영']),'번 반복되고, ', '중복 제거한 이름 출력하면 (',trimws(s2),'), ','오름차순 정렬하면 (',trimws(s4), ')')
```
Python 3.6
#arr = list(map(str, input().strip().split(" ")))
arr = ["이유덕","이재영","권종표","이재영","박민호","강상희","이재영","김지완","최승혁","이성연","박영서","박민호","전경헌","송정환","김재성","이유덕","전경헌"]
#P1
print("김씨: {}, 이씨 {}".format(len([1 for i in arr if i[0]=="김"]), len([1 for i in arr if i[0]=="이"])))
#P2
print("이재영: {}".format(arr.count("이재영")))
#P3
arr_set = set(arr)
print(arr_set)
#P4
list_arr_set = list(arr_set)
list_arr_set.sort()
print(list_arr_set)
x<-c("이유덕",'이재영','권종표','이재영','박민호','강상희','이재영','김지완','최승혁','이성연','박영서','박민호','전경헌','송정환','김재성','이유덕','전경헌')
1번 length(grep("^(이|김)+",x)) 2번 length(grep("이재영",x)) 3번 unique(x) 4번 sort(unique(x))
names= "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌".split(",")
1.
def countn(a,b):
c=0
for x in a:
if b==x[0]:
c+=1
print('%s씨는 %d명입니다'%(b,c))
countn(names,'김')
countn(names,'이')
2.
print(names.count('이재영'))
var text = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌", explode = text.split(','), names = [], leeJaeYung = 0, overlap = 0, lee = 0;
for(var i = 0; i < explode.length-1; i++) { var name = explode[i]; if(name[0] == "이") lee++; if(name == "이재영") leeJaeYung++; if(names.indexOf(name) != -1) overlap++; else names.push(name); }
names.sort();
console.log(names);
Name="이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌"
Name_List=list(Name.split(","))
InPut=input("1.김씨와 이씨는 각각 몇명?/ 2.'이재영'이라는 이름이 몇번 반복?/3.중복을 제거한 이름을 출력./4.중복을 제거한 이름을 오름차순으로 정렬하여 출력(원하는 숫자 입력): ")
if InPut == "1":
kim_count=0
e_count=0
for i in Name_List:
if i[0]=="김":
kim_count+=1
elif i[0]=="이":
e_count+=1
print("김씨는 ",kim_count," 명, ","이씨는 ", e_count," 명입니다.")
if InPut=="2":
ejy_c=0
for i in Name_List:
if i =="이재영":
ejy_c+=1
print("이재영은 ",ejy_c," 번 반복됩니다.")
if InPut=="3":
for i in Name_List:
Count=Name_List.count(i)
if Count>1:
Name_List.remove(str(i))
print(Name_List)
if InPut=="4":
Name_List.sort()
for i in Name_List:
Count=Name_List.count(i)
if Count>1:
Name_List.remove(str(i))
print(Name_List)
f = open("name.txt", 'r')
line = f.readline()
line = line.split(',')
print(line, end = '\n\n')
#1
kim = 0
lee = 0
for i in range(len(line)-1):
if line[i][0] == '김':
kim = kim +1
if line[i][0] == '이':
lee = lee +1
print("1. 김씨는 %d명, 이씨는 %d명입니다."%(kim,lee))
#2
count = 0
for i in range(len(line)-1):
if line[i] == '이재영':
count = count +1
print("2. '이재영'이란 이름은 %d번 반복됩니다."%count)
#3
list = []
for i in range(len(line)-1):
if line[i] not in list:
list.append(line[i])
print('3.', end = " ")
print(list)
#4
list.sort()
print("4.", end = " ")
print(list)
arrs=["이유덕","이재영","권종표","이재영","박민호","강상희","이재영","김지완","최승혁","이성연","박영서","박민호","전경헌","송정환","김재성","이유덕","전경헌","김재성"]
dic ={}
def test():
for str in arrs:
if str not in dic:
dic[str]=1
else:
num=dic.get(str)
dic[str]=num+1
print(dic)
test()
결과
{'이유덕': 2, '이재영': 3, '권종표': 1, '박민호': 2, '강상희': 1, '김지완': 1, '최승혁': 1, '이성연': 1, '박영서': 1, '전경헌': 2, '송정환': 1, '김재성': 2}
package synapProgram;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.stream.Collectors;
//김씨와 이씨는 각각 몇 명 인가요?
//"이재영"이란 이름이 몇 번 반복되나요?
//중복을 제거한 이름을 출력하세요.
//중복을 제거한 이름을 오름차순으로 정렬하여 출력하세요.
public class SynapProgram {
public int getPeopleByLastName(String[] strArray, String n) {
int result = 0;
for (String ele : strArray)
if (ele.startsWith(n))
result++;
return result;
}
public int getPeopleByLastName2(String[] strArray, String n) {
return (int) Arrays.asList(strArray).stream().filter(m -> m.contains(n)).count();
}
public int getPeopleByFullName(String[] strArray, String n) {
int result = 0;
for (String ele : strArray)
if (ele.contains(n))
result++;
return result;
}
public int getPeopleByFullName2(String[] strArray, String n) {
return (int) Arrays.asList(strArray).stream().filter(m -> m.equals(n)).count();
}
public String[] getNameWithoutDuplicated(String[] strArray) {
HashSet<String> set = new HashSet<String>(Arrays.asList(strArray));
return set.toArray(new String[set.size()]);
}
public String[] getNameWithoutDuplicated2(String[] strArray) {
List<String> list = Arrays.asList(strArray).stream().distinct().collect(Collectors.toList());
return list.toArray(new String[list.size()]);
}
public String[] sortedNameArrayOfWithoutDuplicated(String[] strArray) {
String[] str = getNameWithoutDuplicated(strArray);
Arrays.sort(str);
return str;
}
public String[] sortedNameArrayOfWithoutDuplicated2(String[] strArray) {
List<String> list = Arrays.asList(getNameWithoutDuplicated2(strArray)).stream().sorted()
.collect(Collectors.toList());
return list.toArray(new String[list.size()]);
}
public static void main(String[] args) {
// TODO Auto-generated method stub
String[] strArray = { "이유덕", "이재영", "권종표", "이재영", "박민호", "강상희", "이재영", "김지완", "최승혁", "이성연", "박영서", "박민호", "전경헌",
"송정환", "김재성", "이유덕", "전경헌" };
SynapProgram sp = new SynapProgram();
System.out.println("김씨와 이씨는 각각 몇 명 인가요? 김: " + sp.getPeopleByLastName(strArray, "김") + ", 이: "
+ sp.getPeopleByLastName(strArray, "이"));
System.out.println("김씨와 이씨는 각각 몇 명 인가요? 김: " + sp.getPeopleByLastName2(strArray, "김") + ", 이: "
+ sp.getPeopleByLastName2(strArray, "이"));
System.out.println();
System.out.println("'이재영'이란 이름이 몇 번 반복되나요? " + sp.getPeopleByFullName(strArray, "이재영"));
System.out.println("'이재영'이란 이름이 몇 번 반복되나요? " + sp.getPeopleByFullName2(strArray, "이재영"));
System.out.println();
System.out.println("중복을 제거한 이름을 출력하세요. " + Arrays.toString(sp.getNameWithoutDuplicated(strArray)));
System.out.println("중복을 제거한 이름을 출력하세요. " + Arrays.toString(sp.getNameWithoutDuplicated2(strArray)));
System.out.println();
System.out.println(
"중복을 제거한 이름을 오름차순으로 정렬하여 출력하세요. " + Arrays.toString(sp.sortedNameArrayOfWithoutDuplicated(strArray)));
System.out.println(
"중복을 제거한 이름을 오름차순으로 정렬하여 출력하세요. " + Arrays.toString(sp.sortedNameArrayOfWithoutDuplicated2(strArray)));
}
}
names = '이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌'
names_list = names.split(',')
names_list.sort()
# 1
number_kims = 0
number_lees = 0
for name in names_list:
if name[0] == '김':
number_kims += 1
for name in names_list:
if name[0] == '이':
number_lees += 1
print(number_kims, number_lees)
# 2
number_이재영 = 0
for name in names_list:
if name == '이재영':
number_이재영 += 1
print(number_이재영)
# 3
names_set = set(names_list)
nameset = list(names_set)
print(nameset)
# 4
nameset.sort()
print(nameset)
# 파이썬
sample = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌"
name_list = sample.split(",")
kim = 0
lee = 0
for m in name_list:
if m[0] == "김": kim += 1
elif m[0] == "이": lee += 1
print("김: ", kim)
print("이: ", lee)
name_set = set(name_list)
print("중복 제거: ", name_set)
name_list_ascend = list(name_set)
name_list_ascend.sort()
print("오름차순: ", name_list_ascend)
var _list = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌";
var _array = new Array;
_array = _list.split(",");
function _count_1 (n) {
var _c = 0;
for (var i = 0; i < _array.length; i++) {
if (_array[i][0] == n) {
_c = _c + 1;
};
};
return _c;
;}
function _count_2 (n) {
var _c = 0;
for (var i = 0; i < _array.length; i++) {
if (_array[i] == n) {
_c = _c + 1;
};
};
return _c;
;}
var _set = new Set;
for (var i = 0; i < _array.length; i++) {
_set.add(_array[i]);
};
var _array_2 = Array.from(_set);
console.log(_count_1("김"), _count_1("이"));
console.log(_count_2("이재영"));
console.log(_array_2.sort());
자바스크립트입니다!!
var input = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌";
var processedNames = new Set();
var sortedNames = new Array();
var ljy = 0;
var kim = 0;
var lee = 0;
var names = input.split(',');
for(var i = 0; i < names.length; i++) {
var words = names[i].split('');
if(words[0] === "김") {
kim++;
}
if(words[0] === "이") {
lee++;
}
if(names[i] === "이재영") {
ljy++;
}
processedNames.add(names[i]);
}
//김씨와 이씨는 각각 몇 명 인가요?
console.log(kim, lee);
//"이재영"이란 이름이 몇 번 반복되나요?
console.log(ljy);
//중복을 제거한 이름을 출력하세요.
for(values of processedNames) {
console.log(values);
}
//중복을 제거한 이름을 오름차순으로 정렬하여 출력하세요.
for(values of processedNames) {
sortedNames.push(values);
}
sortedNames.sort();
for(keys in sortedNames) {
console.log(sortedNames[keys]);
}
global question_string_list
question_string="이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌"
question_string_list=question_string.split(',')
def problem1():
kim_counter=0
lee_counter=0
for k in question_string_list:
if k[0]=='김':
kim_counter+=1
if k[0]=='이':
lee_counter+=1
return kim_counter,lee_counter
def problem2():
leejaeyoung_counter=0
for k in question_string_list:
if k=='이재영':
leejaeyoung_counter+=1
return leejaeyoung_counter
def problem3():
new_question_string_list = []
for k in question_string_list:
if k in new_question_string_list:
continue
new_question_string_list.append(k)
return new_question_string_list
def problem4():
new_question_string_list = []
for k in question_string_list:
if k in new_question_string_list:
continue
new_question_string_list.append(k)
new_question_string_list.sort()
return new_question_string_list
print(problem1())
print(problem2())
print(problem3())
print(problem4())
`` import java.util.ArrayList; import java.util.Collections;
public class Soft {
public static void main(String[] args) {
int name_kim = 0;
int name_lee = 0;
int name_ljy = 0;
String name ="이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌";
String[] name_arr = name.split(",");
for(int i=0;i<name_arr.length;i++)
{
if(name_arr[i].startsWith("김")) name_kim++;
if(name_arr[i].startsWith("이")) name_lee++;
if(name_arr[i].equals("이재영")) name_ljy++;
}
System.out.println("김씨:"+name_kim+"명");
System.out.println("이씨:"+name_lee+"명");
System.out.println("이재영:"+name_ljy+"명");
ArrayList<String> name_list = new ArrayList<String>();
for(int i=0;i<name_arr.length;i++)
{
if(name_list.contains(name_arr[i])) continue;
name_list.add(name_arr[i]);
}
for(int i=0;i<name_list.size();i++)
{
System.out.print(name_list.get(i)+" ");
}
System.out.println();
//
Collections.sort(name_list);
for(int i=0;i<name_list.size();i++)
{
System.out.print(name_list.get(i)+" ");
}
}
}
public int countFirstName() {
for(int i = 0; i < stringarray.length; i++) {
String tempString = stringarray[i].substring(0,1);
if(tempString.equals("이") || tempString.equals("김")) {
count++;
}
}
return count;
}
public int dupNameCount(String[] stringarray, String str) {
this.stringarray = stringarray;
String compareString = str;
for(int i = 0; i < stringarray.length; i++) {
String tempString = stringarray[i];
if(tempString.equals(compareString)) {
nameCount++;
}
}
return nameCount;
}
public void convertFromArrayToMap(String[] stringarray) {
this.stringarray = stringarray;
Set set;
for(int i = 0; i < stringarray.length; i++) {
hashmap.put(stringarray[i], stringarray[i]);
}
set = hashmap.keySet();
Iterator iterator = set.iterator();
ArrayList<String> array = new ArrayList<String>();
while(iterator.hasNext()) {
array.add(hashmap.get(iterator.next()));
}
System.out.println("--중복제거한 명단--");
for(int i = 0; i < array.size(); i++) {
System.out.println(array.get(i));
}
System.out.println("--정렬한 명단--");
Collections.sort(array);
for(int i = 0; i < array.size(); i++) {
System.out.println(array.get(i));
}
}
package com.codingdojang.level1;
import java.awt.List;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
public class SynapSoft {
/*주어진 문자열(공백 없이 쉼표로 구분되어 있음)을 가지고 아래 문제에 대한 프로그램을 작성하세요.
김씨와 이씨는 각각 몇 명 인가요?
"이재영" 이라는 이름이 몇 번 반복되나요?
중복을 제거한 이름을 출력하세요.
중복을 제거한 이름을 오름차순으로 정렬하여 출력하세요.
*/
public static void main(String[] args) {
String nameText = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌";
String name[] = nameText.split(",");
int kim = 0;
int lee = 0;
for (int i = 0; i < name.length; i++) {
if (name[i].startsWith("김")) {
kim++;
} else if (name[i].startsWith("이")) {
lee++;
}
}
System.out.println("1. 김씨 : " + kim + "명, 이씨 : " + lee + "명");
lee = 0;
for (int i = 0; i < name.length; i++) {
if (name[i].equals("이재영")) {
lee++;
}
}
System.out.println("2. " + lee + "번");
HashSet<String> set = new HashSet<String>();
for (int i = 0; i < name.length; i++) {
set.add(name[i]);
}
System.out.println("3. " + set);
ArrayList setList = new ArrayList(set);
Collections.sort(setList);
System.out.println("4. " + setList);
}
}
func countCheckFn(_ nameList: Array<Substring>) -> (Int, Int, Int){
var leeCount = 0, kimCount = 0, leeJYCount = 0
for name in nameList {
if name.hasPrefix("김") {
leeCount += 1
} else if name.hasPrefix("이") {
kimCount += 1
}
if name == "이재영" {
leeJYCount += 1
}
}
return (kimCount, leeCount, leeJYCount)
}
let rawList = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌"
let nameList = rawList.split(separator: ",")
print("이름 배열 생성 : \(nameList)")
var result: (Int, Int, Int) = (0, 0, 0)
result = countCheckFn(nameList)
print("김씨 : \(result.0), 이씨 : \(result.1), 이재영 갯수 : \(result.2)")
let setName = Set(nameList)
print("중복제거된 이름 : \(setName)")
let sortedName = setName.sorted { $0 < $1 }
print("정렬된 이름 : \(sortedName)")
스위프트 입니다.
name_string = '이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌'
name_list = name_string.split(",")
##1##
kim_count = 0; lee_count = 0
for name in name_list:
if name[0] == '김':
kim_count += 1
elif name[0] == '이':
lee_count += 1
print(kim_count, lee_count)
##2##
ljy_count = 0
for name in name_list:
if name == "이재영":
ljy_count += 1
print(ljy_count)
##3##
print(set(name_list))
##4##
print(sorted(list(set(name_list))))
group = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌"
group = group.split(",")
kim = 0
lee = 0
jy = 0
for name in group:
if name == "이재영": jy = jy +1
if name[0] == "김":
kim = kim + 1
elif name[0] == "이":
lee = lee + 1
print("김씨:",str(kim)+"명")
print("이씨:",str(lee)+"명")
print("이재영:", str(jy)+"명")
regroup = list(set(group))
print("중복 제외 리스트")
print(regroup)
regroup.sort()
print("중복 제외, 오름차순 리스트")
print(regroup)
text = '이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌'
list = text.split(",")
name_list = []
kim = 0
lee = 0
for name in list:
if name not in name_list:
name_list.append(name)
if name[0] == "김":
kim += 1
elif name[0] == "이":
lee += 1
print(list.count("이재영"))
print(len(name_list))
print(name_list)
name_list.sort()
print(name_list)
import java.util.Arrays;
public class Names {
public static void main(String[] args) {
String names = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌";
int length = names.length();
String[] nameArr = new String[(length+1)/4];
for (int i = 0; i < nameArr.length; i++) {
nameArr[i] = names.substring(i*4, i*4+3);
}
int numKim = 0, numLee = 0, numLJY=0;
for (int i = 0; i < nameArr.length; i++) {
if(nameArr[i].substring(0, 1).equals("김"))
numKim++;
if(nameArr[i].substring(0, 1).equals("이"))
numLee++;
if(nameArr[i].equals("이재영"))
numLJY++;
}
System.out.println("김씨 " + numKim + "명");
System.out.println("이씨 " + numLee + "명");
System.out.println("이재영 " + numLJY + "명");
for (int i = 0; i < nameArr.length; i++) {
for (int j = i+1; j < nameArr.length; j++) {
if(nameArr[i].equals(nameArr[j]))
nameArr[j] = "";
}
}
for (int i = 0; i < nameArr.length; i++) {
if(nameArr[i].equals("")){}
else{
System.out.print(nameArr[i] + " / ");
}
}
System.out.println();
Arrays.sort(nameArr);
for (int i = 0; i < nameArr.length; i++) {
if(nameArr[i].equals("")){}
else{
System.out.print(nameArr[i] + " / ");
}
}
}
}
def main():
pass
names = []
nString = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌"
names = nString.split(",")
#print(names)
k_num = 0
l_num = 0
my_name = 0
for name in names:
if "김" == name[0]:
k_num += 1
if "이" == name[0]:
l_num += 1
if "이재영" == name:
my_name += 1
# Example 1
print("K : %d\nL : %d\n" % (k_num, l_num), end = "")
# Example 2
print("LJY : %d\n" % (my_name), end = "")
# Example 3
names = list(set(names))
print(names)
# Example 4
names.sort()
print(names)
main()
def sortnames(names):
kim = 0
lee = 0
jaeyeong = 0
nameslist = list(set(names.split(',')))
for args in nameslist:
if args[0] == '김':
kim = kim + 1
if args[0] == '이':
lee = lee + 1
for a in names.split(','):
if a == '이재영':
jaeyeong = jaeyeong + 1
result = '김씨 %d명\n이씨 %d명\n이재영 %d번\n' % (kim, lee, jaeyeong) + str(nameslist) + '\n' + str(sorted(nameslist))
return result
'''
주어진 문자열(공백 없이 쉼표로 구분되어 있음)을 가지고 아래 문제에 대한 프로그램을 작성하세요.
이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌
김씨와 이씨는 각각 몇 명 인가요?
"이재영"이란 이름이 몇 번 반복되나요?
중복을 제거한 이름을 출력하세요.
중복을 제거한 이름을 오름차순으로 정렬하여 출력하세요.
'''
#1번 문제
names ="이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌"
nameList = names.split(',')
count_kim = 0
count_lee = 0
count_j = 0
for i in nameList:
if i[0] == '김':
count_kim += +1
if i[0] == '이':
count_lee += 1
if i == '이재영':
count_j += 1
print("김 씨 :" + str(count_kim), "이 씨 :" + str(count_lee) )
#2번 문제
print("이재영 :", str(count_j))
#3번 문제
a = list(set(nameList))
print(a)
#4번 문제
a.sort()
print(a)
파이썬 도전
namelist = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌"
namel = namelist.split(',')
i, j, k = 0, 0, 0
for name in namel:
if name[0] == '김':
i += 1
if name[0] == '이':
j += 1
if name == "이재영":
k += 1
a= set(namel)
b = sorted(a)
print("""1. 김씨 : %d명
이씨 : %d명
2. 이재영 : %d명""" % (i, j, k))
print('3. ', a)
print('4. ', b)
name = '이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌'
names = name.split(',')
cnt1 = 0
cnt2 = 0
cnt3 = 0
new_name = []
for i in names:
if i[:1] == '김':
cnt1+=1
if i[:1] == '이':
cnt2+=1
if i == '이재영':
cnt3+=1
for i in names:
if names.count(i) != 1:
names.remove(i)
for i in names:
new_name.append(i)
new_name.sort()
print("1. 김씨 %d명, 이씨 %d명" % (cnt1,cnt2))
print("2. %d번 반복" % cnt3)
print("3. 중복을 제거한 이름 출력: %s" % ",".join(names))
print("4. 3번을 오름차순으로 정렬: %s" % ",".join(new_name))
def name(string):
ex = string.split(',')
cnt = 0
for i in ex :
if i.startswith("김") or i.startswith("이") :
cnt += 1
MRlee = ex.count("이재영")
unique = ','.join(set(ex))
unique_sort = ','.join(sorted(list(set(ex))))
print("김씨와 이씨는 각각 몇명인가요? : {}".format(cnt))
print("이재영이란 이름은 몇번 반복되나요? : {}".format(MRlee))
print("중복을 제거한 이름을 출력해주세요 : \n {}".format(unique))
print("중복을 제거한 이름을 오름차순으로 정려하여 출력하세요: \n {}".format(unique_sort))
name("이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌")
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Scanner;
import java.util.Set;
public class NameString {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
String inputLine = sc.nextLine();
sc.close();
String[] names = inputLine.split(",");
int countKim = 0;
int countLee = 0;
int countLeeJaeyoung = 0;
for(String name : names){
if(name.charAt(0) == '김'){
countKim++;
}
if(name.charAt(0) == '이'){
countLee++;
}
}
System.out.println("김씨 : " + countKim);
System.out.println("이씨 : " + countLee);
for(String name : names){
if(name.equals("이재영")){
countLeeJaeyoung++;
}
}
System.out.println("이재영 : "+ countLeeJaeyoung);
Set<String> set = new HashSet<>();
for(String name : names){
set.add(name);
}
System.out.println(set);
List<String> nameList = new ArrayList<>(set);
Collections.sort(nameList);
System.out.println(nameList);
}
}
Swift입니다.
import Foundation
var names = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌".split(separator:",")
// 1. 김씨와 이씨는 각각 몇 명 인가요?
print("#1. 김씨: \(names.filter { $0.starts(with:"김") }.count)")
print("#1. 이씨: \(names.filter { $0.starts(with:"이") }.count)")
// 2. "이재영"이란 이름이 몇 번 반복되나요?
print("#2. 이재영: \(names.filter { $0 == "이재영" }.count)")
// 3. 중복을 제거한 이름을 출력하세요.
var s = Set(names)
print("#3. 중복을 제거한 이름: \(s)")
// 4. 중복을 제거한 이름을 오름차순으로 정렬하여 출력하세요.
var namesNoDup = Array(s)
print("#4. 중복을 제거한 이름의 오름차순 정렬: \(namesNoDup.sorted())")
List,namelist,Firstname,Kim,Lee,same = [],[],[],0,0,0
nameList = ["이유덕","이재영","권종표","이재영","박민호","강상희","이재영","김지완","최승혁","이성연","박영서","박민호","전경헌","송정환","김재성","이유덕","전경헌"]
for x in range(0,len(nameList)):
List = list(nameList[x])
Firstname.append(List[0])
#같은 성이 몇명인가
for x in range(0,len(Firstname)):
if Firstname[x] == "김":
Kim += 1
elif Firstname[x] == "이":
Lee += 1
print(Kim,Lee)
#같은 이름의 반복
same = nameList.count("이재영")
print(same)
#중복된 이름 지우기
while len(nameList) != 0:
name = nameList[0]
namelist.append(name)
x = nameList.count(name)
for x in range(1,x+1):
nameList.remove(name)
continue
print(namelist)
#가나다 순으로 이름 정렬하기
namelist.sort()
print(namelist)
import re
names = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌"
name = names.split(",")
count = 0
arr = []
for i in name:
arr.append(i);
if re.search("김|이.*", i):
count += 1
print(count)
print(arr.count("이재영"))
arr = list(set(arr))
for i in range(len(arr)):
print(arr[i])
print("\n")
arr.sort()
for i in range(len(arr)):
print(arr[i])
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PracticeWW
{
class Program
{
static void Main(string[] args)
{
string names = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌";
string[] name = names.Split(',');
int Kim = 0, Lee = 0, LJY = 0;
foreach(var n in name)
{
if (n.StartsWith("김"))
Kim++;
else if (n.StartsWith("이"))
Lee++;
if (n.Equals("이재영"))
LJY++;
}
Console.WriteLine("김 씨 : {0}, 이 씨 : {1}, 이재영 : {2}", Kim, Lee, LJY);
var q_name = (from n in name
select n).Distinct<string>();
foreach (var n in q_name)
Console.WriteLine(n);
Console.WriteLine();
q_name = from n in q_name
orderby n ascending
select n;
foreach (var n in q_name)
Console.WriteLine(n);
}
}
}
input = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌"
name_list = input.split(",")
#1
kim_count = 0
lee_count = 0
for name in name_list:
if name[0] == "김": kim_count += 1
elif name[0] == "이": lee_count +=1
print("김씨: {0}".format(kim_count))
print("이씨: {0}".format(lee_count))
#2
target_count = 0
for name in name_list:
if name == "이재영": target_count +=1
print("이재영: {0}".format(target_count))
#3
dupli_list = []
for name in name_list:
if name not in dupli_list: dupli_list.append(name)
print(dupli_list)
#4
dupli_list.sort()
print(dupli_list)
str1 = '이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌'
list1 = str1.split(',')
#1 김씨와 이씨는 각각 몇 명 인가요?
print(len(list(x for x in list1 if x.startswith("김"))))
print(len(list(x for x in list1 if x.startswith("이"))))
#2 "이재영"이란 이름이 몇 번 반복되나요?
print(list1.count("이재영"))
#3 중복을 제거한 이름을 출력하세요.
print(set(list1))
#4 중복을 제거한 이름을 오름차순으로 정렬하여 출력하세요.
print(sorted(set(list1)))
/*김씨와 이씨는 각각 몇 명 인가요?*/
public static int kimLeeCnt(String iStr) {
int kimLeeCnt = 0;
String[] nameArr = iStr.split(",");
for(int i = 0; i < nameArr.length; i++) {
if(nameArr[i].charAt(0) == '김' || nameArr[i].charAt(0) == '이') {
kimLeeCnt++;
}
}
return kimLeeCnt;
}
/*"이재영"이란 이름이 몇 번 반복되나요?*/
public static int repeatCnt(String iStr) {
int repeatCnt = 0;
String[] nameArr = iStr.split(",");
for(int i = 0; i < nameArr.length; i++) {
repeatCnt = nameArr[i].equals("이재영") ? repeatCnt + 1 : repeatCnt;
}
return repeatCnt;
}
/*중복을 제거한 이름을 출력하세요.*/
public static String rmDupName(String iStr) {
String oStr = "";
String[] nameArr = iStr.split(",");
for(int i = 0; i < nameArr.length - 1; i++) {
if(i == 0) oStr = nameArr[i];
for(int j = i + 1; j < nameArr.length; j++) {
if(nameArr[i].equals(nameArr[j])) {
nameArr[j] = "";
}
}
if(i != 0 && !nameArr[i].equals("")) {
oStr = oStr + "," + nameArr[i];
}
}
return oStr;
}
/*중복을 제거한 이름을 오름차순으로 정렬하여 출력하세요.*/
public static String sortAscending(String iStr) {
String oStr = "";
String[] nameArr = iStr.split(",");
for(int i = 0; i < nameArr.length - 1; i++) {
if(i == 0) oStr = nameArr[i];
for(int j = i + 1; j < nameArr.length; j++) {
if(nameArr[i].equals(nameArr[j])) {
nameArr[j] = "";
}
}
if(i != 0 && !nameArr[i].equals("")) {
oStr = oStr + "," + nameArr[i];
}
}
String[] tmpArr = oStr.split(",");
Arrays.sort(tmpArr);
String.join(",", tmpArr);
return String.join(",", tmpArr);
}
// 사이냅소프트 면접문제
package main
import (
"fmt"
"sort"
"strings"
)
var input = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌"
func main() {
inpStr := parser(input)
// 김씨, 이씨 찾기
var countKim, countLee int
for _, v := range inpStr {
if matchFamilyName(v, "김") {
countKim++
}
if matchFamilyName(v, "이") {
countLee++
}
}
fmt.Printf("count 김: %d, 이: %d\n", countKim, countLee)
// 이재영 찾기
fmt.Printf("count 이재영: %d\n", countName(inpStr, "이재영"))
// 중복제거
rmd := removeDuplicate(inpStr)
fmt.Println("중복제거: ", rmd)
// 정렬
fmt.Println("정렬: ", sortSlice(rmd))
}
func parser(s string) []string {
return strings.Split(s, ",")
}
func matchFamilyName(s string, match string) bool {
chk := false
if string([]rune(s)[0]) == match {
chk = true
}
return chk
}
func countName(s []string, match string) int {
count := 0
for _, v := range s {
if v == match {
count++
}
}
return count
}
func removeDuplicate(s []string) []string {
rst := []string{}
set := map[string]bool{}
for _, v := range s {
set[v] = true
}
for key := range set {
rst = append(rst, key)
}
return rst
}
func sortSlice(s []string) []string {
sort.Strings(s)
return s
}
names = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌".split(",")
#1
a = []
for i in names:
a.append(i[0])
print("김씨 : %d\n이씨 : %d\n"%(a.count("김"), a.count("이")))
#2
print("이재영 count is : ",names.count("이재영"))
#3
print("\n중복제거 : ",set(names))
#4
print("\n정렬 : ",sorted(set(names)))
a = input().split(',')
count1 = 0
for i in a:
q = str(i)
if ((q[0] == '이') | (q[0] == '김')):
count1 = count1 + 1
count2 = a.count('이재영')
b = list(set(a))
b.sort()
print(count1)
print(count2)
print(b)
print(b)
python3 입니다
people = '이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌'
people_name = people.split(',') #people 리스트화
#문제1: 김씨와 이씨는 각각 몇 명 인가요?
result = []
for person_name in people_name:
if person_name[:1] == '이' or person_name[:1] == '김':
result.append(person_name)
print(len(result))
#문제2: "이재영"이란 이름이 몇 번 반복되나요?
print(people_name.count('이재영'))
#문제3: 중복을 제거한 이름을 출력하세요.
peopleList = []
for person_name in people_name:
if person_name in peopleList:
pass
else:
peopleList.append(person_name)
print(peopleList)
#문제4: 중복을 제거한 이름을 오름차순으로 정렬하여 출력하세요.
print(sorted(peopleList))
import java.util.ArrayList; import java.util.Arrays;
public class main {
public static void main(String[] args) {
String input = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌";
String[] nameArr = input.split(",");
// step 1, 2. count
int cnt_Kim = 0;
int cnt_Lee = 0;
int cnt_LJY = 0;
for(int i=0; i<nameArr.length; i++){
if(nameArr[i].equals("이재영"))
cnt_LJY++;
if(nameArr[i].substring(0,1).equals("김"))
cnt_Kim++;
if(nameArr[i].substring(0,1).equals("이"))
cnt_Lee++;
}
System.out.println(cnt_Kim+","+cnt_Lee+","+cnt_LJY);
// step 3. remove duplicated name
ArrayList notDupList = new ArrayList();
for(int i=0; i<nameArr.length; i++){
if(notDupList.contains(nameArr[i]) == false)
notDupList.add(nameArr[i]);
}
System.out.println("==not Duplication==");
for(int i=0; i<notDupList.size(); i++){
System.out.println(notDupList.get(i));
}
// step 4 . ascending ordered sort
String[] notDupOrderedArr = new String[notDupList.size()];
notDupList.toArray(notDupOrderedArr);
Arrays.sort(notDupOrderedArr);
System.out.println("==not Duplication & Ascending Ordered==");
for (int i=0; i< notDupOrderedArr.length; i++){
System.out.println(notDupOrderedArr[i]);
}
}
}
public void synapSoft()
{
List<string> list = new List<string>{ "이유덕","이재영","권종표","이재영","박민호","강상희","이재영","김지완","최승혁","이성연","박영서","박민호","전경헌","송정환","김재성","이유덕","전경헌"};
int nCnt1 = 0;
int nCnt2 = 0;
foreach (string name in list)
{
if (name.StartsWith("김") || name.StartsWith("이"))
{
nCnt1++;
}
if (name == "이재영") // Will match once.
{
nCnt2++;
}
}
List<string> distinctlist = list.Distinct().ToList();
Console.WriteLine("1.김씨와 이씨는 각각 몇 명 인가요? {0}", nCnt1);
Console.WriteLine("2.이재영이란 이름이 몇 번 반복되나요? {0}", nCnt2);
Console.WriteLine("3.중복을 제거한 이름을 출력하세요 : ");
foreach (string name in distinctlist)
{
Console.Write("{0} \t", name);
}
Console.WriteLine();
distinctlist.Sort();
Console.WriteLine("4.중복을 제거한 이름을 오름차순으로 정렬하여 출력하세요 : ");
foreach (string name in distinctlist)
{
Console.Write("{0} \t", name);
}
Console.WriteLine();
}
package codingDojang;
public class CyberNaps { public String findKim(String str) { String[] strK = str.split(","); int countK = 0; int countL = 0; for(int i = 0; i < strK.length;i++) { String init = strK[i].substring(0, 1); if(init.equals("김")) { countK += 1; } else if(init.equals("이")) { countL += 1; } } String result = "김씨: " + countK + " 이씨: " + countL; return result; } public int findFname(String str, String name) { int result = 0; String[] tStr = str.split(","); for(int i = 0; i < tStr.length; i++) { if(tStr[i].equals(name)) { result += 1; } } return result; } public String delDup(String str) { String[] dup = str.split(","); String result = dup[0]; for(int i = 1; i < dup.length; i++) { boolean flag = true; for(int j = 1; j <= i; j++){ if(dup[i].equals(dup[i-j])) { flag = false; break; } } if(flag == true) { result = result.concat("," + dup[i]); } } return result; } public String sortName(String str) {
String[] sort = str.split(",");
for(int i = 0; i < sort.length - 1; i++) {
for(int j = i + 1; j < sort.length; j++) {
if(sort[i].compareTo(sort[j]) > 0) {
String temp = sort[i];
sort[i] = sort[j];
sort[j] = temp;
}
}
}
String result = sort[0];
for(int i = 1; i < sort.length; i++) {
result = result.concat("," + sort[i]);
}
return result;
}
public static void main(String[] args) {
String str = new String("이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌");
CyberNaps fK = new CyberNaps();
CyberNaps fJY = new CyberNaps();
CyberNaps del = new CyberNaps();
CyberNaps sort = new CyberNaps();
System.out.println(fK.findKim(str));
System.out.println(fJY.findFname(str,"이재영"));
System.out.println(del.delDup(str));
System.out.println(sort.sortName(del.delDup(str)));
}
}
#include<iostream>
#include<string>
#include<vector>
using namespace std;
int main()
{
string name[] = { "이유덕", "이재영", "권종표", "이재영", "박민호", "강상희", "이재영", "김지완"
, "최승혁", "이성연", "박영서", "박민호", "전경헌", "송정환", "김재성", "이유덕", "전경헌" };
int Lee_count = 0, Kim_count = 0;
int Lee_Jae_Yung_Count = 0;
string tmp;
vector<string> v;
for (int i = 0; i < 17; i++)
{
v.push_back(name[i]);
if ("이" == name[i].substr(0, 2)) // 1번 문제
Lee_count++;
else if ("김" == name[i].substr(0, 2))
Kim_count++;
if ("이재영" == name[i]) // 2번 문제
Lee_Jae_Yung_Count++;
}
for (int i = 0; i < v.size(); i++) // 4번 문제
{
for (int j = i + 1; j < v.size(); j++)
{
if (v[i] > v[j])
{
tmp = v[i];
v[i] = v[j];
v[j] = tmp;
}
}
}
for (int i = 0; i < v.size(); i++) // 3번 문제
{ // 중복이름 제거
for (int j = i + 1; j < v.size(); j++)
{
if (v[i] == v[j])
{
v.erase(v.begin() + i);
if (v[i] == v[j++])
v.erase(v.begin() + i);
}
}
}
cout << "1번 문제" << endl;
cout << "이씨 성을 가진 사람 수는>> " << Lee_count << "\t김씨 성을 가진 사람 수는>> " << Kim_count << endl << endl;
cout << "2번 문제" << endl;
cout << "이재영 반복 횟수>> " << Lee_Jae_Yung_Count << endl << endl;
cout << "3-4번 문제" << endl << ">> ";
for (int i = 0; i < v.size(); i++)
{
cout << i + 1 << "." << v[i] << ' ';
}
cout << endl;
}
여러 코드를 보며 공부하는 중입니다.
public static void Test1()
{
string sIputValue = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌";
List<string> lNameList = new List<string>();
string[] sName = sIputValue.Split(',');
int KimCnt = 0, LeeCnt = 0, SameCnt = 0;
for (int i = 0; i < sName.Length; i++)
{
if (sName[i].StartsWith("이")) LeeCnt++;
else if (sName[i].StartsWith("김")) KimCnt++;
if (sName[i] == "이재영") SameCnt++;
lNameList.Add(sName[i]);
}
Console.WriteLine($"Kim : {KimCnt} / Lee : {LeeCnt}");
Console.WriteLine($"Same '이재영' : {SameCnt}");
IEnumerable<string> CompareList = lNameList.Distinct();
lNameList = CompareList.ToList();
Console.WriteLine("Remove same");
foreach (string item in lNameList)
{
Console.WriteLine($"{item}");
}
Console.WriteLine("Sort\n");
lNameList.Sort();
foreach (string item in lNameList)
{
Console.WriteLine($"{item}");
}
}
public class test{
public static void main(String[] args){
String []arr = {"이유덕","이재영","권종표","이재영","박민호","강상희","이재영","김지완","최승혁","이성연","박영서","박민호","전경헌","송정환","김재성","이유덕","전경헌"};
int count1=0, count2=0, count3=0;
//1번
for(int i=0;i<arr.length;i++){
if(arr[i].charAt(0) == '김')
count1++;
else if(arr[i].charAt(0) == '이')
count2++;
//2번
if(arr[i].equals("이재영")){
count3++;
if(count3 >= 2)
arr[i] = "0";
}
}
System.out.println("김씨는 " + count1 + "명, 이씨는 " + count2 + "명입니다.");
System.out.println("이재영은 " + count3 + "번 반복됩니다.");
//3번
for(int i=0;i<arr.length-1;i++){
for(int j=i+1;j<arr.length;j++){
if(arr[i].equals(arr[j]))
arr[j] = "0";
}
}
for(int i=0;i<arr.length;i++){
if(arr[i].equals("0") == false)
System.out.print(arr[i] + " ");
}
System.out.println();
//4번
for(int j=0;j<Math.pow((arr.length-1),2);j++){
for(int i=0;i<arr.length-1;i++){
if(arr[i].compareTo(arr[i+1]) > 0){
String temp = arr[i];
arr[i] = arr[i+1];
arr[i+1] = temp;
}
}
}
for(int i=0;i<arr.length;i++){
if(arr[i].equals("0") == false)
System.out.print(arr[i] + " ");
}
System.out.println();
}
}
// 자바입니다
public static void main(String[] args) throws Exception {
String[] str = {"이유덕","이재영","권종표","이재영","박민호","강상희","이재영","김지완","최승혁","이성연","박영서","박민호","전경헌","송정환","김재성","이유덕","전경헌"};
Set<String> set = new HashSet<>();
int cnt = 0;
int cnt2 = 0;
for (int i=0; i<str.length; i++) {
if (str[i].charAt(0) == '이' || str[i].charAt(0) == '김')
cnt++;
if(str[i].equals("이재영"))
cnt2++;
set.add(str[i]);
}
System.out.println("김씨와 이씨의 수 : " + cnt);
System.out.println("이재영의 수 : " + cnt2);
String[] str2 = set.toArray(new String[0]);
System.out.println(Arrays.toString(str2));
Arrays.sort(str2);
System.out.println(Arrays.toString(str2));
} // set 콜렉션으로 처리했습니다
import java.util.ArrayList;
import java.util.Arrays;
public class Prob410 {
public static void main(String[] args) {
String input = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌";
String[] names = input.split(",");
int count_kim = 0;
int count_lee = 0;
int count_ljy = 0;
ArrayList<String> name_list = new ArrayList<String>();
for(int i = 0; i < names.length; i++) {
if(names[i].startsWith("김"))
count_kim++;
if(names[i].startsWith("이"))
count_lee++;
if(names[i].equals("이재영"))
count_ljy++;
if(!name_list.contains(names[i]))
name_list.add(names[i]);
}
String[] name_arr = name_list.toArray(new String[name_list.size()]);
System.out.println("김 씨: " + count_kim);
System.out.println("이 씨: " + count_lee);
System.out.println("이재영 씨: " + count_ljy);
System.out.println("중복을 제거한 이름: ");
for(int i = 0; i < name_arr.length; i++)
System.out.print(name_arr[i] + ((name_arr.length == i + 1)?"\n":", "));
Arrays.sort(name_arr);
System.out.println("중복을 제거한 이름을 오름차순으로: ");
for(int i = 0; i < name_arr.length; i++)
System.out.print(name_arr[i] + ((name_arr.length == i + 1)?"\n":", "));
}
}
#include<iostream>
#include"stdafx.h"
int main()
{
int num_kim = 0, num_lee = 0;
list<wstring> lt;
lt.push_back(L"이유덕");
lt.push_back(L"이재영");
lt.push_back(L"권종표");
lt.push_back(L"이재영");
lt.push_back(L"박민호");
lt.push_back(L"강상희");
lt.push_back(L"이재영");
lt.push_back(L"김지완");
lt.push_back(L"최승혁");
lt.push_back(L"이성연");
lt.push_back(L"박영서");
lt.push_back(L"박민호");
lt.push_back(L"전경헌");
lt.push_back(L"송정환");
lt.push_back(L"김재성");
lt.push_back(L"이유덕");
lt.push_back(L"전경헌");
lt.sort();
wstring *wstr;
wstr = new wstring[lt.size()];
list<wstring>::iterator iter;
int i = 0;
for (iter = lt.begin(); iter != lt.end(); ++iter)
{
wstr[i++] = *iter;
}
for (auto i = 0; i < lt.size(); i++)
{
if (wstr[i][0] == L'김')
num_kim++;
else if (wstr[i][0] == L'이')
num_lee++;
}
delete[]wstr;
wcout.imbue(locale("kor"));//이거 안하면 한글안나옴.
cout << "num1_answer:" << num_kim << " " << num_lee << endl << endl;
cout << "num2_answer:" << count(lt.begin(), lt.end(), L"이재영") << endl << endl;
lt.unique();
cout << "num3 and num4 answer:";
for (iter = lt.begin(); iter != lt.end(); iter++)
wcout << *iter << ",";
cout << endl;
}
package sysnep;
import java.util.HashSet;
import java.util.TreeSet;
public class practice {
public static void main(String[] args) {
String temp = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌";
String[] name = temp.split(",");
HashSet<String> an = new HashSet<>();
TreeSet<String> an1 = new TreeSet<>();
int count[] = new int[3];
for (int i = 0; i < name.length; i++) {
count[0] = name[i].startsWith("김") ? ++count[0] : count[0];
count[1] = name[i].startsWith("이") ? ++count[1] : count[1];
count[2] = name[i].matches("이재영") ? ++count[2] : count[2];
an.add(name[i]);
an1.add(name[i]);
}
System.out.println(count[0] + "," + count[1] + "\n" + count[2]);
System.out.println(an.toString() + "\n" + an1.toString());
}
}
Python
s = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌"
s = s.split(",")
ans = list()
ans.append((sum([1 for c in s if "김" == c[0]]), sum([1 for c in s if "이" == c[0]])))
ans.append(s.count("이재영"))
ans.append(set(s))
ans.append(sorted(set(s)))
print(*ans, sep="\n")
name= "이유덕,이재영,권종표,이재영,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재영,이유덕,전경헌"
name_list=name.split(',')
def find_kim():
num = 0
for name in name_list:
if name[0] == "김":
num+=1
return print(num)
def find_le():
num = 0
for name in name_list:
if name[0] == "이":
num+=1
return print(num)
def find_lejaeyoung():
num = 0
for name in name_list:
if name == "이재영":
num+=1
return print(num)
def set_name_list():
return print(set(name_list))
def sort_name_list():
result=set(name_list)
return print(sorted(result))
find_kim()
find_le()
find_lejaeyoung()
set_name_list()
sort_name_list()
db= ("이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌").split(",")
name = []
for i in db:
name.append(i[0])
# 1
print("lee는%s, kim은 %s"%(name.count("이"),name.count("김")))
# 2
print("이재영 반복 횟수: %s"%db.count("이재영"))
# 3
list(set(db))
# 4
sorted(list(set(db)))
data= '이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌'.split(',')
#김씨와 이씨는 각각 몇 명 인가요?
print("김씨는 {}명 입니다.".format(len([d for d in data if d[0] == '김'])))
print("이씨는 {}명 입니다.".format(len([d for d in data if d[0] == '이'])))
#"이재영"이란 이름이 몇 번 반복되나요?
print("이재영씨는 이름이 {}번 반복됩니다.".format(data.count('이재영')))
#중복을 제거한 이름을 출력하세요.
#중복을 제거한 이름을 오름차순으로 정렬하여 출력하세요.
print(sorted(list(set(data))))
import java.util.*;
public class Practice100 { public static void main(String[] args) { String example="이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌"; int count_kim_lee=0, count_ljy=0;
String[] names=example.split(",");
List<String>names_list=new ArrayList<String>(Arrays.asList(names));
Set<String>names_set=new HashSet<String>();
names_set.addAll(names_list);
//해당 이름을 가진 사람의 총 수
for(int i=0;i<names.length;i++) {
if(names[i].startsWith("김")||names[i].startsWith("이")) {
count_kim_lee++;
}
if(names[i].equals("이재영")) {
count_ljy++;
}
}
Collections.sort(names_list);
System.out.println(names_list);
}
}
vStr="이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌"
memList = []
count1 = 0 #김씨, 이씨가 몇명
count2 = 0 #이재영 몇명
for word in vStr.split(","):
memList.append(word)
print(memList)
for i in range(len(memList)):
if memList[i].startswith("이") or memList[i].startswith("김") :
count1 += 1
if memList[i] == "이재영":
count2 += 1
print("김씨와 이씨는 각각 몇 명 인가요? %d" % (count1))
print("이재영이란 이름이 몇 번 반복되나요? %d" % (count2))
# newMemList = []
newMemList = list(set(memList))
print(newMemList)
newMemList.sort()
print(newMemList)
ss = '이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌'
org = {}
for i in ss.split(','):
if i in org: org[i] += 1
else: org[i] = 1
print('1. 김씨: {}명, 이씨: {}명'.format(sum(j for i,j in org.items() if i[0] == '김'),sum(j for i,j in org.items() if i[0] == '이')))
print('2. 이재영: {}명'.format(sum(j for i,j in org.items() if i == '이재영')))
print('3. {}'.format(list(org.keys())))
print('4. {}'.format(sorted(org.keys())))
1. 김씨: 2명, 이씨: 6명
2. 이재영: 3명
3. ['이유덕', '이재영', '권종표', '박민호', '강상희', '김지완', '최승혁', '이성연', '박영서', '전경헌', '송정환', '김재성']
4. ['강상희', '권종표', '김재성', '김지완', '박민호', '박영서', '송정환', '이성연', '이유덕', '이재영', '전경헌', '최승혁']
파이썬3
data = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌"
list1 = data.split(",")
print(list1)
kim_list = [i for i in list1 if i.startswith("김")]
print(len(kim_list))
lee_list = [i for i in list1 if i.startswith("이")]
print(len(lee_list))
print(list1.count("이재영"))
print(set(list1))
print(sorted(list(set(list1))))
// 사이냅소프트 면접문제
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);
String st = sc.nextLine();
String[] stArr = st.split(",");
getAns(stArr);
}
public static void getAns(String[] stArr)
{
ArrayList<String> newStr = new ArrayList<>();
int kim = 0, lee = 0;
int ljy = 0;
int count = 0;
for(String st : stArr)
{
if(st.equals("이재영")) // 2번
{
ljy++;
lee++;
}
else if(st.charAt(0) == '김') // 1번
kim++;
else if(st.charAt(0) == '이')
lee++;
}
newStr.add(stArr[0]);
for(int i = 1; i < stArr.length; i++) // 3번
{
for(int j = 0; j < i; j++)
{
if(stArr[i].equals(stArr[j]))
count++;
}
if(count == 0)
newStr.add(stArr[i]);
count = 0;
}
System.out.println("1번: " + "김씨=" + kim + " 이씨=" + lee);
System.out.println("2번: " + ljy);
System.out.println("3번: " + newStr);
Collections.sort(newStr); // 4번
System.out.println("4번: " + newStr);
}
}
#사이냅소프트 면접문제
names='이유덕,이재영,권종표,박민호,강상희,이재영,김지완,최승혁,이성연,박민호,전경헌,송정환,이유덕,전경헌'
#1 김씨와 이씨는 각각 몇 명 인가요?
x=names.split(',')
n=len(x)
count_kim=0
count_lee=0
for i in range(0,n):
if x[i][0] == '김':
count_kim +=1
elif x[i][0] == '이':
count_lee +=1
else :
continue
print('김씨 ;', count_kim,'명 , 이씨 : ' ,count_lee,' 명')
#2 이재영이란 이름이 몇번 반복되나요?
print(names.count('이재영'))
#3 중복을 제거한 이름을 출력하세요
print(set(x))
# 오름차순으로 정렬출력
name_1=list(set(x))
print(name_1.sort())
name=['이유덕','이재영','권종표','이재영','박민호','강상희','이재영','김지완',
'최승혁','이성연','박영서','박민호','전경헌','송정환','김재성','이유덕','전경헌']
#1번문제
kim=[]
lee=[]
def kimLee(namelist):
for i in range(len(namelist)):
if namelist[i][0] == '이':
lee.append(namelist[i])
elif namelist[i][0] == '김':
kim.append(namelist[i])
return len(kim), len(lee)
print(kimLee(name))
#2번
def calCount(namelist):
count = 0
for i in namelist:
if i == '이재영':
count +=1
return count
print(calCount(name))
# 3번
print(set(name))
#4번
noduple=list(set(name))
noduple.sort()
print(noduple)
3.7.0
a = '이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌'
a = list(a.split(','))
fn = [i[0] for i in a]
print('김씨는여 %d명 이구여, 이씨는여, %d명 이어여' %(fn.count('김'), fn.count('이')))
print('이재영은 %d명이어유' %a.count('이재영'))
print(list(set(a)))
print(sorted(list(set(a))))
C#
using System;
using System.Linq;
namespace CD024
{
class Program
{
static void Main(string[] args)
{
string input = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌";
var names = new Names(input);
Console.WriteLine($"김씨 {names.KimCount}명, 이씨 {names.LeeCount}명");
Console.WriteLine($"이재영 {names.LJYCount}명");
Console.Write("중복제외 이름: ");
foreach (var n in names.NameDistinct) { Console.Write($"{n} "); }
Console.WriteLine();
Console.Write("중복제외 이름(오름차순): ");
foreach (var n in names.NameDistinct.OrderBy(i => i)) { Console.Write($"{n} "); }
Console.WriteLine();
}
}
class Names
{
private readonly string[] name;
public Names(string aString)
{
name = aString.Split(',');
}
// 김씨 수 반환
public int KimCount
=> (from n in name where n[0] == '김' select n).Count();
// 이씨 수 반환
public int LeeCount
=> (from n in name where n[0] == '이' select n).Count();
// 이재영 수 반환
public int LJYCount
=> (from n in name where n == "이재영" select n).Count();
// 중복 제외 출력
public string[] NameDistinct => name.Distinct().ToArray();
}
}
_names = '이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌'
_names_list = [_name for _name in _names.split(',')]
_names_set = set(_names_list)
print("김씨 : %d명, 이씨 : %d명"% (_names.count('김'),_names.count('이')))
print('"이재영"이란 이름이 몇 번 반복되나요 : %d'% _names_list.count('이재영'))
print("중복을 제거한 이름을 출력하세요. %s"% _names_set)
print("중복을 제거한 이름을 오름차순으로 정렬하여 출력하세요. %s"% sorted(list(_names_set)))
Python 3.6.4
s = ['이유덕','이재영','권종표','이재영','박민호','강상희','이재영','김지완','최승혁','이성연','박영서','박민호','전경헌','송정환','김재성','이유덕','전경헌']
l = 0
k = 0
for i in s:
if i[0] == '이':
l = l + 1
if i[0] == '김':
k = k + 1
print('Q:김씨와 이씨는 각각 몇 명 인가요?')
print(' A:이씨는 '+str(l)+'명 '+ ' 김씨는 '+str(k)+'명입니다.')
ljy = 0
for j in s:
if j == '이재영':
ljy = ljy + 1
print('Q:"이재영"이란 이름이 몇 번 반복되나요?')
print(' A:'+str(ljy)+' 명입니다.')
sd = []
for z in s:
if z not in sd:
sd.append(z)
print('Q:중복을 제거한 이름을 출력하세요.')
print(' A:'+str(sd))
sd.sort(key=None, reverse=False)
print('Q:중복을 제거한 이름을 오름차순으로 정렬하여 출력하세요.')
print(' A:'+str(sd))
null=[]
target=target.split(',')
print(target)
for i in range(0,len(target)):
if target[i:].count(target[i]) !=1:
null.append(target[i])
else:
pass
print(null)
for j in null:
target.remove(j)
print(target)
#정렬
target.sort()
print(target)
names = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌"
name_list = names.split(",")
first_name = [name[0] for name in name_list]
print('김씨는 %d 명 입니다. 이씨는 %d 명 입니다.'%(first_name.count("김"),first_name.count("이")))
print('이재영은 %d 번 반복됩니다.'%name_list.count('이재영'))
a=set(name_list)
print(a)
b=list(a)
b.sort()
print(b)
import java.util.Scanner;
import java.util.ArrayList;
public class KimSanghyeop
{
public static void main(String[] args)
{
String str = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌";
String[] arr = str.split(",");
ArrayList<String> list = new ArrayList<String>();
// 연산부
int f1,f2;
int cnt1=0,cnt2=0,cnt3=0;
String temp;
boolean ok = true;
for(f1=0;f1<arr.length;f1++)
{
temp= arr[f1].substring(0, 1);
if(temp.equals("김"))
{
cnt1+=1;
}
if(temp.equals("이"))
{
cnt2+=1;
}
if(arr[f1].equals("이재영"))
{
cnt3+=1;
}
ok = true;
for(f2=0;f2<list.size();f2++)
{
if(arr[f1].equals(list.get(f2)))
{
ok=false;
}
}
if(ok)
{
list.add(arr[f1]);
}
}
// 출력부
System.out.println("김씨 : "+cnt1);
System.out.println("이씨 : "+cnt2);
System.out.println("이재영 : "+cnt3);
for(f1=0;f1<list.size();f1++)
{
System.out.print(list.get(f1)+" ");
}
list.sort(null);
for(f1=0;f1<list.size();f1++)
{
System.out.print(list.get(f1)+" ");
}
}
}
data = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌"
listdata = data.split(",")
kim = 0
lee = 0
for h in listdata:
if h[0] == "김":
kim += 1
elif h[0] == "이":
lee += 1
print("김 : " + str(kim) + ", 이 : " + str(lee))
print(data.count("이재영"))
print(set(listdata))
print(sorted(list(set(listdata))))
## 김 or 이 로 시작하는 숫자 : 8
s = 0
for name in a:
if name.startswith('김') or name.startswith('이'):
s += 1
print(s)
## 이재영 중복 숫자 : 3
lee_s = 0
for name in a:
if name == '이재영':
lee_s += 1
print(lee_s)
## 중복 이름 날리기
b = list(set(a))
## 오름차순으로 정렬하기
sorted(b)
import java.util.*;
public class Question_1 {
static final String NAMEs = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌";
public static void main(String[] args) {
String[] namelist = NAMEs.split(",");
LinkedHashSet set = new LinkedHashSet(Arrays.asList(namelist));
int count_kim = 0;
int count_lee = 0;
int count_ljy = 0;
System.out.println("---------------------------------- 원본데이터 ----------------------------------");
for(String str : namelist) {
System.out.print(str + " ");
if(str.charAt(0) == '김') {
count_kim++;
} else if(str.charAt(0) == '이') {
count_lee++;
}
if(str.equals("이재영")) {
count_ljy++;
}
}
System.out.println();
System.out.println("----------------------------------------------------------------------------");
System.out.println("1. 김씨와 이씨는 각각 몇 명 인가요?");
System.out.println("김씨:" + count_kim + " 이씨:" + count_lee);
System.out.println("----------------------------------------------------------------------------");
System.out.println("2. \"이재영\"이란 이름이 몇 번 반복되나요?");
System.out.println("이재영의 반복횟수:" + count_ljy);
System.out.println("----------------------------------------------------------------------------");
System.out.println("3. 중복을 제거한 이름을 출력하세요.");
for(Object obj : set) {
System.out.print((String)obj + " ");
}
System.out.println();
System.out.println("----------------------------------------------------------------------------");
Object[] str = set.toArray();
Arrays.sort(str);
System.out.print("4. 중복을 제거한 이름을 오름차순으로 정렬하여 출력하세요.\r\n");
for(Object tmp : str) {
System.out.print((String)tmp + " ");
}
}
}
names=['이유덕','이재영','권종표','이재영','박민호','강상희','이재영','김지완','최승혁','이성연','박영서','박민호'
,'전경헌','송정환','김재성','이유덕','전경헌']
from collections import Counter
PROBLEMS_NO1 = lambda name: 'Kim' if name[0]=='김' else 'Lee' if name[0]=='이' else 'OTHERS'
PROBLEMS_NO2 = lambda name: name.count('이재영')
PROBLEMS_NO3 = lambda name: sorted(set(name))
class Name():
def __init__(self,name_list):
self.name_list=name_list
def Kim_Lee_count(self):
Kim_counter = Counter(map(PROBLEMS_NO1,self.name_list))['Kim']
Lee_counter =Counter(map(PROBLEMS_NO1,self.name_list))['Lee']
return print("Kim's lastname: {0} times \nLee's lastname: {1} times ".format(Kim_counter ,Lee_counter))
def Lee_Jae_Young(self):
return PROBLEMS_NO2(self.name_list)
def No_iter(self):
return PROBLEMS_NO3(self.name_list)
name= Name(names)
name.Kim_Lee_count()
name.Lee_Jae_Young()
name.No_iter()
Data='이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌'
Data_lists=Data.split(',')
count=0
count2=0
for i in Data_lists:
if i[0] in '김' or i[0] in '이':
count+=1
if '이재영' in i:
count2+=1
print('1. 김씨와 이씨는 총',count,'명입니다.')
print('2. "이재영"이란 이름은 총',count2,'번반복됩니다.')
for j in set(Data_lists):
print(j,end=' ')
for k in sorted(set(Data_lists)):
print(k)
names = ['이유덕','이재영','권종표','이재영','박민호',
'강상희','이재영','김지완','최승혁','이성연',
'박영서','박민호','전경헌','송정환','김재성',
'이유덕','전경헌']
lee = 0
kim = 0
jy = 0
el = []
for n in names:
if n[0] == '이':
lee += 1
if n == '이재영':
jy += 1
elif n[0] == '김':
kim += 1
if n not in el:
el.append(n)
print(lee, kim, jy, el, sorted(el))
STR = '이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌'
STR_list = STR.split(',')
nkim = 0
nlee = 0
nLJY = 0
for x in STR_list:
if x[:1] == '김': nkim += 1
elif x[:1] == '이': nlee += 1
if x == '이재영': nLJY += 1
print(nkim, nlee, nLJY)
STR_list_set = list(set(STR_list))
print(STR_list_set)
print(sorted(STR_list_set))
답: 2 6 3 ['강상희', '박민호', '이재영', '김재성', '박영서', '이성연', '이유덕', '권종표', '전경헌', '김지완', '송정환', '최승혁'] ['강상희', '권종표', '김재성', '김지완', '박민호', '박영서', '송정환', '이성연', '이유덕', '이재영', '전경헌', '최승혁']
import re
namelist = list(input().split(','))
cntK = 0
cntL = 0
for i in namelist:
if re.search('^이', i):
cntL += 1
elif re.search('^김', i):
cntK += 1
else:
continue
print('김씨는 {}, 이씨는 {}명입니다'.format(cntK,cntL))
LJY = namelist.count('이재영')
print('이재영은 {} 번 반복됩니다'.format(LJY))
namelist = set(namelist)
print(namelist)
a = list(namelist)
a.sort()
print(a)
import re
str_names = ['이유덕','이재영','권종표','이재영','박민호','강상희','이재영','김지완','최승혁','이성연','박영서','박민호','전경헌','송정환','김재성','이유덕','전경헌']
def count(pattern):
cnt = 0
for name in str_names:
if None != re.match(pattern, name):
cnt += 1
return cnt
print(count('^[김|이]+'))
print(count('^이재영'))
print(len(set(str_names)))
print(sorted(list(set(str_names))))
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
public class Yclass {
public static void main(String[] args) {
String str = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌";
String[] names = str.split(",");
int number = 0;
int number2 = 0;
int number3 = 0;
ArrayList<String> array = new ArrayList<>();
for(int i = 0; i<names.length; i++) {
if(names[i].contains("김")) {
++number;
}
if(names[i].contains("이")) {
++number2;
}
if(names[i].contains("이재영")) {
++number3;
}
if(!array.contains(names[i])) {
array.add(names[i]);
}
}
System.out.println(number);
System.out.println(number2);
System.out.println(number3);
System.out.println(array);
Collections.sort(array);
System.out.println(array);
}
}
string = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌"
lis = string.split(',')
#1
sung = []
for i in lis: sung.append(i[0])
print("김씨 : %s번, 이씨 : %s번"%(sung.count("김"),sung.count("이")))
#2
print(len(list(i for i in lis if i=="이재영")),"번")
#3
lis = list(set(lis))
print(lis)
#4
lis.sort(reverse=True)
print(lis)
names = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌".split(",")
1번
a=[ i[0] for i in names ]
print("김씨 : {0}\n이씨 : {1}\n".format(a.count("김"), a.count("이")))
2번
print('"이재영"이란 이름이 {}번 반복되었습니다.'.format(names.count("이재영")))
3번
renames = list(set(names))
print(renames)
4번
renames.sort()
print(renames)
name="이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌"
name_etc=name.split(',')
name_cnt=0
lee_cnt=0
for name_find in name_etc:
if name_find[:1] in '김' or name_find[:1] in '이':
name_cnt+=1
if name_find in "이재영":
lee_cnt+=1
name_set=set(name_etc)
name_list=list(name_set)
print(name_cnt)
print(lee_cnt)
print(name_list)
name_list.sort()
print(name_list)
all_name="이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌"
name_list=list(all_name.split(','))
# 1번
first_name_list=[]
len_name_list = int(len(name_list))
for i in range(len_name_list):
first_name_list.append(name_list[i][0])
print(first_name_list.count("김"),"명 입니다.")
print(first_name_list.count("이"),"명 입니다.")
# 2번
print(name_list.count("이재영"),"명 반복됩니다.")
# 3번
set_name_list = set(name_list)
list_set_name_list = list(set_name_list)
for i in set_name_list:
print(i, end=" ")
print("")
# 4번
list_set_name_list.sort()
for i in set_name_list:
print(i, end=" ")
name = input("이름을 입력하세요. ").split(',')
print(len(list(filter(lambda x : x[0]=='김', name))))
print(len(list(filter(lambda x : x[0]=='이', name))))
print(name.count("이재영"))
set = list(set(name))
print(set)
set.sort()
print(set)
namespace codingdojang__
{
class Program
{
static void Main(string[] args)
{
string name = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌";
string[] name_array = name.Split(',');
int KIM = 0;
int LEE = 0;
int LEE_JaeYeong = 0;
HashSet<string> name_hashset = new HashSet<string>();
foreach (var i in name_array)
{
if (i.Substring(0, 1) == "김")
{
KIM += 1;
}
else if (i.Substring(0, 1) == "이")
{
LEE += 1;
}
}
Console.WriteLine("김씨 {0}명", KIM);
Console.WriteLine("이씨 {0}명", LEE);
foreach (var i in name_array)
{
if (i == "이재영")
{
LEE_JaeYeong += 1;
}
}
Console.WriteLine("이재영 {0}명", LEE_JaeYeong);
foreach (var i in name_array)
{
name_hashset.Add(i);
}
foreach (var i in name_hashset)
{
Console.Write(i + ' ');
}
Console.WriteLine("");
Array.Sort(name_array);
name_hashset.Clear();
foreach (var i in name_array)
{
name_hashset.Add(i);
}
foreach (var i in name_hashset)
{
Console.Write(i + ' ');
}
Console.WriteLine("");
}
}
}
name_str = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌"
count_kim=0
count_lee=0
count_jeayoung=0
list_list = name_str.split(',')
for i in list_list:
if i=='이재영':
count_jeayoung+=1
if i[0]=='이':
count_lee+=1
elif i[0]=='김':
count_kim+=1
print("김씨:%d명 이씨:%d명"%(count_kim,count_lee))
print("이재영 이름 횟수:%d번"%count_jeayoung)
list_set = set(list_list)
list_list = list(list_set)
list_list.sort()
print(list_list)
a = '이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌'
names = a.split(',')
print('1.', len(list(filter(lambda x: x[0] == '김' or x[0] == '이', names))))
print('2.', len(list(filter(lambda x: x == '이재영', names))))
print('3.', set(names))
print('4.', sorted(list(set(names))))
var input = '이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌';
var arr = input.split(',');
var kim = 0, lee = 0;
var obj = {};
for (var i = 0; i < arr.length; i++) {
if (obj[arr[i]] === undefined) {
obj[arr[i]] = 1;
} else {
obj[arr[i]]++;
}
if (arr[i].substring(0, 1) === '김') {
kim++;
} else if (arr[i].substring(0, 1) === '이') {
lee++;
}
}
console.log('김씨 : ' + kim);
console.log('이씨 : ' + lee);
console.log('이재영 이름반복 count : ' + obj['이재영']);
console.log(Object.keys(obj).join(','));
console.log(Object.keys(obj).sort().join(','));
static void Main(string[] args)
{
Console.WriteLine("*** 코딩도장 Q24 ***");
// 주어진 문자열
string exp = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌";
/// 쉼표 구분자로 문자열 배열 변환
string[] conv = exp.Split(',');
/*
foreach (string i in conv)
{
Console.WriteLine(i);
}*/
//김씨 이씨 몇명
int cntKimLee = 0;
// 이재영 몇명
int cntLee = 0;
foreach (string i in conv)
{
if (i[0]=='김' | i[0]=='이')
{
cntKimLee += 1;
}
if (i=="이재영")
{
cntLee += 1;
}
}
Console.WriteLine("김씨 또는 이씨는 {0} 명입니다.", cntKimLee);
Console.WriteLine("이재영 씨는 {0} 명입니다.", cntLee);
// 중복 제거
List<string> distName = new List<string>();
foreach (string j in conv)
{
if (distName.Contains(j))
{
Console.WriteLine("{0} 은 이미 포함된 이름입니다.", j);
}
else
{
Console.WriteLine("{0} 은 중복되지 않은 이름입니다.", j);
distName.Add(j);
}
}
// 중복 제거 후 정렬하고 출력
distName.Sort();
foreach (string k in distName)
{
Console.WriteLine(k);
}
}
names = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌"
name_list = names.split(",")
kim, lee = 0, 0
for name in name_list:
if name.startswith('김'):
kim+=1
if name.startswith('이'):
lee+=1
if __name__ == '__main__':
print('1. 김씨와 이씨는 각각 {0}, {1}명'.format(kim, lee))
print('2. "이재영"이란 이름은 {0}번 반복'.format(name_list.count('이재영')))
name_list = list(set(name_list))
print('3. ', name_list)
print('4. ', sorted(name_list))
import copy
def count_name(s):
result = []
name_list=s.split(",")
#1.김씨와 이씨는 각각 몇 명 인가요?
#2."이재영"이란 이름이 몇 번 반복되나요?
cnt_kim=0
cnt_lee=0
cnt_ljy=0
for i in range(0,len(name_list)):
cnt_kim+=name_list[i][0].count('김')
cnt_lee+=name_list[i][0].count('이')
cnt_ljy+=name_list[i].count('이재영')
#3. 중복을 제거한 이름을 출력
#4. 중복 제거한 이름을 오름차순으로 출력
name_list=list(set(name_list))
names=",".join(name_list)
name_list_sort=copy.deepcopy(name_list)
name_list_sort.sort()
names_sort=",".join(name_list_sort)
result.append('1. 김씨 : %d명 이씨 : %d명'%(cnt_kim, cnt_lee))
result.append('2. %d명'%cnt_ljy)
result.append('3. %s'%names)
result.append('4. %s' %names_sort)
return (result)
s="이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌"
count_name(s)
name = '이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌'
count_kim, count_lee, count_name_lee = 0, 0, 0
for x in name.split(','):
if x[0] == '김':
count_kim += 1
elif x[0] == '이':
count_lee += 1
if x == '이재영':
count_name_lee += 1
print('김씨 %d 이씨 %d' % (count_kim, count_lee))
print('"이재영"이란 이름의 반복 횟수 %d' % count_name_lee)
name = set(name.split(','))
print(name)
print(sorted(list(name)))
static void Main(string[] args)
{
string str = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌";
string outstr = "";
List<string> tmplist = new List<string>();
int sum = 0;
string[] tmp = str.Split(',');
for (int i = 0; i < tmp.Length; i++)
{
Console.Write(tmp[i][0]+" ");
if (tmp[i][0].ToString().Contains("김") || tmp[i][0].ToString().Contains("이"))
sum++;
}
Console.WriteLine("김,이 씨는 모두 {0}명 입니다", sum);
for (int i = 0; i < tmp.Length; i++)
{
if (tmp[i].Equals("이재영"))
sum++;
}
Console.WriteLine("이재영은 총 {0}번 반복됩니다", sum);
for (int i = 0; i < tmp.Length; i++)
{
if (!tmplist.Contains(tmp[i]))
{
outstr += tmp[i] + " ";
tmplist.Add(tmp[i]);
}
}
Console.WriteLine(outstr+"입니다");
var result = from tmpstr in tmplist orderby tmpstr[2],tmpstr[0] select tmpstr;
outstr = "";
foreach (string item in result)
{
outstr += item + " ";
}
Console.WriteLine(outstr+"입니다");
return;
}
요즘 공부중인 초보 개발자입니다..
data = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌"
names = data.split(',')
unique_names = set(names)
def count_by_family_name(family_name):
_count = 0
for name in names:
if family_name in name:
_count += 1
return _count
print("1. 김씨: %d명. 이씨: %d명" %(count_by_family_name("김"), count_by_family_name("이")))
print("2. 이재영 반복 횟수:", names.count("이재영"))
print("3. 중복 제거:", list(unique_names))
print("4. 이름 오름차순 정렬:", sorted(unique_names))
data='이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌'
names=data.split(',')
#Q1
firstName=[names[i][0] for i in range(len(names)-1)]
print('%d for 김, %d for 이'%(firstName.count('김'),firstName.count('이')))
#Q2
print('%d for 이재영'%names.count('이재영'))
#Q3
uniqueName=list(set(names))
print(uniqueName)
#Q4
uniqueName.sort()
print(uniqueName)
names = '이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌'
namelist = names.split(',')
count_kim = 0
count_lee = 0
count_leejaeyoung = 0
for name in namelist:
if name[0] == '김':
count_kim += 1
elif name[0] == '이':
count_lee += 1
if name == '이재영':
count_leejaeyoung += 1
print('김씨 %d명' % count_kim)
print('이씨 %d명' % count_lee)
print('이재영 %d번 반복' % count_leejaeyoung)
nameset = list(set(namelist))
print(nameset)
nameset = sorted(nameset)
print(nameset)
s= count_k=0 count_l=0 count_ljy=0
for i in s: if i=='ㄱㅣㅁ': count_k=count_k+1 elif i=='ㅇㅣ': count_l=count_l+1
l=s.split(',') for i in l: if i=='ㅇㅣㅈㅐㅇㅕㅇ ': count_ljy=count_ljy+1
p=set(l)
c=list(p) d=sorted(c)
print(count_k,count_l,count_ljy,p,d)
import sys
info_string = input().split(",")
num_dict = {}
for elem in info_string:
if elem in num_dict.keys():
num_dict[elem] += 1
else:
num_dict[elem] = 1
# 1. 김씨와 이씨는 각각 몇 명인가요
kim_count = 0
lee_count = 0
for name in info_string:
if name[0] == "김":
kim_count += 1
elif name[0] == "이":
lee_count += 1
print(kim_count, lee_count)
# 2. 이재영이라는 이름이 몇 번 반복되나요
print(info_string.count("이재영"))
#3. 중복을 제거한 이름을 출력하세요
for name in num_dict.keys():
sys.stdout.write(name + " ")
print(" ")
#4. 중복을 제거한 이름을 오름차순으로 출력하세요
first_name_list = list(num_dict.keys())
first_name_list.sort()
for name in first_name_list:
sys.stdout.write(name + " ")
name_str = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌"
# Question 1
cntKim = 0
cntLee = 0
name_list = name_str.split(",")
print(name_list[0])
print(name_list)
for name in name_list:
if name[0] == "김":
cntKim += 1
elif name[0] == "이":
cntLee += 1
print("="*30)
print("이: ", cntLee, "김: ", cntKim)
# Question 2
findLJY = 0
for name in name_list:
if name == "이재영":
findLJY += 1
print("="*30)
print("이재영의 갯수: ", findLJY)
# Question 3
name_only_list = set(name_list)
name_mod_list = list(name_only_list)
print("="*30)
("중복을 제거한 결과: ")
print(name_mod_list)
# Question 4
print("="*30)
name_mod_list.sort()
print(name_mod_list)
public class testmain {
public static void main(String[] args) {
// TODO Auto-generated method stub
String name = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌";
String[] arrName = name.split(",");
int cntKim = 0;
int cntLee = 0;
int cntLeejayoung = 0;
List<String> newNameList = new ArrayList<String>();
for(String data:arrName) {
if(data.substring(0,1).equals("김")) {
cntKim++;
} else if (data.substring(0,1).equals("이")) {
cntLee++;
if(data.equals("이재영")) cntLeejayoung++;
}
if(!newNameList.contains(data)) newNameList.add(data);
}
System.out.println("김씨:"+cntKim);
System.out.println("이씨:"+cntLee);
System.out.println("이재영:"+cntLeejayoung);
Collections.sort(newNameList);
for(String data:newNameList) {
System.out.println(data);
}
}
}
names = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌".split(",")
a= [ i[0] for i in names ] print(a)
print("김씨:%d\n이씨:%d\n"%(a.count("김"), a.count("이")))
print(names.count("이재영"))
unique = list(set(names))
print(unique)
unique.sort()
print(unique)
names = '이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌'
names1 = names.split(',')
cnt = 0
lastcnt = 0
# 1번
for i in range(0, len(names), 4):
if names[i] == '이' or names[i] == '김':
lastcnt = lastcnt +1
print(lastcnt)
# 2번
for i in range(len(names1)):
if names1[i] == '이재영':
cnt = cnt +1
print(cnt)
# 3번
names3 = set(names1)
print(names3)
# 4번
names4 = list(names3)
print(sorted(names4))
name = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌"
kim_count = 0
ee_count = 0
ejy_count = 0
name_array = name.split(",")
for i in range(len(name_array)):
compare = ''.join(name_array[i])
if "김" in compare: # 김씨성을 가진 사람의 명수
kim_count += 1
elif "이" in compare: # 이씨성을 가진 사람의 명수
ee_count += 1
for i in range(len(name_array)):
compare = ''.join(name_array[i])
if "이재영" == compare: #이재영이 몇명이나 있나
ejy_count += 1
new_name = list(set(name_array)) #중복 제거를 위해 자료형변환
print("김씨는 %d 명 있습니다." % kim_count)
print("이씨는 %d 명 있습니다." % ee_count)
print("'이재영'이라는 이름은 %d 번 반복 됩니다." % ejy_count)
print(new_name)
new_name.sort()
print(new_name)
def LastNames(names, s):
return len(list(filter(lambda x : True if x[0] == s else False, names.split(',')))) #이씨 성만 필터링
def filterNames(names, s):
return (names.split(',')).count(s)
def removeRep(names):
return ','.join(list(set(names.split(',')))) #중복 제거
def sortNames(names):
L = list(set(names.split(','))) #중복 제거
L.sort()
return ','.join(L)
>>> names = '이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌'
>>> print(LastNames(names, '김'))
2
>>> print(LastNames(names, '이'))
6
>>> print(filterNames(names, '이재영'))
3
>>> print(sortNames(names))
강상희,권종표,김재성,김지완,박민호,박영서,송정환,이성연,이유덕,이재영,전경헌,최승혁
Q = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌".split(',')
Kim = [i for i in Q if i[0] == '김']
Lee = [j for j in Q if j[0] == '이']
LJY = [k for k in Q if k == '이재영']
Set1 = set(Q)
Set2 = list(Set1)
Set2.sort(reverse = False)
print('김씨는 %d명, 이씨는 %d명'%(len(Kim), len(Lee)))
print('이재영 %d명 반복'%(len(LJY)))
print('중복을 제거한 이름 명단: ', Set1)
print('중복을 제거한 이름을 오름차순으로 정렬한 명단: ', Set2)
n = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌".split(',')
k = 0
l = 0
for i in range(len(n)):
print(i)
if n[i][0] =='김':
k += 1
elif n[i][0] == '이':
l += 1
k
l
n.count('이재영')
n = list(set(n))
n.sort()
a = '이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌'
b=a.split(',')
c=0
d=0
e= []
for i in b: #문제1
if i[0] == "김": c+=1
elif i[0] == "이": d+=1
print("김씨 수:", c)
print("이씨 수:", d)
print("이재영 수:", a.count('이재영')) #문제2
for n in b: #문제3
if n not in e:
e.append(n)
e.sort() #문제4
print(e)
#92230
p_list = '이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌'
p_list = p_list.split(',')
##특정 성이 몇명 있는지 알려주는 함수 만들기
def FindFn(fn):
fnList = []
for name in p_list:
if name[0] == fn:
fnList.append(name)
return fn, len(fnList)
print(FindFn('김'))
print(FindFn('이'))
##특정 이름이 몇명 있는지 알려주는 함수 만들기
def FindPs(ps):
result = 0
for name in p_list:
if name == ps:
result += 1
return ps, result
print(FindPs('이재영'))
##중복을 제거한 이름 출력하기
re_list = []
for name in p_list:
if name not in re_list:
re_list.append(name)
print(re_list)
##중복을 제거한 이름을 오름차순으로 정렬하여 출력
re_list.sort()
print(re_list)
num = 0
Kim = 0
Lee = 0
Uniq_Name = []
Data = ['이유덕','이재영','권종표','이재영','박민호','강상희','이재영','김지완','최승혁','이성연','박영서','박민호','전경헌','송정환','김재성','이유덕','전경헌']
for i in range(len(Data)):
if Data[i] == Data[1]:
if i == 1: pass
else : num += 1
Filter = Data[i][0]
if Filter == "김":
Kim +=1
if Filter == "이":
Lee +=1
#1
print(Kim, "," ,Lee)
#2
print(num)
#3
Uniq_Name = list(set(Data))
print(Uniq_Name)
#4
Uniq_Name.sort()
print(Uniq_Name)
name = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌"
name_list = name.split(",")
#1
kim = 0
lee = 0
for i in name_list:
if i[0] == "이":
kim += 1
elif i[0] == "김":
lee += 1
print(kim)
print(lee)
#2
count = 0
for i in name_list:
if i == "이재영":
count += 1
return count
print(count)
#3
name_set = set(name_list)
new_name_list = list(name_set)
print(new_name_list)
#4
print(sorted(new_name_list))
name_init='이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌' name=name_init.split(',')
num_Kim=0 num_Yee=0 num_YJY=0
for i in name: if i[0]=='김': num_Kim+=1
elif i[0]=='이':
num_Yee+=1
if i=='이재영':
num_YJY+=1
print("1번. 김가:{} \t 이가:{}\n".format(num_Kim,num_Yee)) print("2번. 이재영 반복횟수:{}\n".format(num_YJY)) print("3번. 중복을 제거한 이름:\n\t{}\n".format(set(name))) print("4번. 중복을 제거한 이름을 오름차순으로 정렬:\n\t{}".format(sorted(list(set(name)))))
a = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌"
aa=a.split(",")
c = []
cc = []
d = []
#1
for b in aa :
if b.startswith("김") :
c.append(b)
elif b.startswith("이"):
cc.append(b)
print(len(c))
print(len(cc))
#2
print(aa.count("이재영"))
#3
aaa= list(set(aa))
print(aaa)
#4
aaa.sort()
print(aaa)
파이썬 3.7.2
ex = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌"
ex_list = []
cut = 0
for x in range(len(ex)):
if ex[x] == ",":
ex_list.append(ex[cut:x])
cut = x+1
ex_list.append(ex[cut:])
kim = 0
lee = 0
jy = 0
for x in range(len(ex_list)):
if ex_list[x][0] == "이":
lee += 1
if ex_list[x][0] == "김":
kim += 1
if ex_list[x] == "이재영":
jy += 1
print("1. 김씨와 이씨는 각각 몇 명인가요? 김씨 : "+str(kim)+"번, 이씨 : "+str(lee)+"번")
print('''2. "이재영"이란 이름이 몇 번 반복되나요? '''+str(jy)+"번")
ex_set = set(ex_list)
ex_set_str = str(ex_set)
print("3. 중복을 제거한 이름을 출력하세요. "+ex_set_str[1:len(ex_set_str)-1])
ex_list = list(ex_set)
ex_list.sort()
ex_list_str = str(ex_list)
print("4. 중복을 제거한 이름을 오름차순으로 정렬하여 출력하세요. "+ex_list_str[1:len(ex_list_str)-1])
names = ['이유덕', '이재영', '권종표', '이재영', '박민호', '강상희', '이재영', '김지완', '최승혁', '이성연', '박영서',
'박민호', '전경헌', '송정환', '김재성', '이유덕', '전경헌']
# 김씨와 이씨는 각각 몇 명인가요?
count_lee = 0
count_kim = 0
for i in range(len(names)):
if names[i][0] == '이':
count_lee += 1
if names[i][0] == '김':
count_kim += 1
print('김씨는 {}명, 이씨는 {}명 입니다.'.format(count_kim, count_lee))
# "이재영"이란 이름이 몇 번 반복되나요?
count_ljy = 0
for i in range(len(names)):
if names[i] == '이재영':
count_ljy += 1
print("이재영씨는 {}번 반복 되었습니다".format(count_ljy))
# 중복을 제거한 이름을 출력하세요.
new_names = list(dict.fromkeys(names))
print(new_names)
# 중복을 제거한 이름을 오름차순으로 정렬하여 출력하세요.
print(sorted(new_names))
data = '이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌'
김씨와 이씨는 각각 몇 명 인가요? 풀이 Names = data.split(",") cnt_lee = 0 cnt_kim = 0 for Name in Names: if Name[0] == '이': cnt_lee += 1 elif Name[0] == '김': cnt_kim += 1 print(cnt_lee, cnt_kim)
Names.count("이재영")
Set_Names = set(Names) print(Set_Names)
List_Names = list(Set_Names) List_Names.sort() print(List_Names)
name="이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌"
namelist= name.split(',')
count_kim = 0
count_lee = 0
n = len(namelist)
while n > 0:
eachname = namelist.pop(n-1)
list(eachname)
count_kim += eachname.count('김')
count_lee += eachname.count('이')
n = len(namelist)
print("김씨는 총 "+ str(count_kim) + "명 입니다")
print("이씨는 총 "+ str(count_lee) + "명 입니다")
nlist = name.split(',')
repeat = nlist.count("이재영")
print("이재영이란 이름은 총" + str(repeat) + "번 반복됩니다.")
set_name = set(nlist)
new = list(set_name)
print(new)
print(sorted(new))
a ='이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌'
#1. 김씨와 이씨는 각각 몇 명 인가요?
a = a.split(',')
lee = 0
kim = 0
for i in range(len(a)) :
if a[i][0]=='이' :
lee = lee + 1
elif a[i][0]=='김' :
kim = kim + 1
print('이씨는 {}명, 김씨는 {}명'.format(lee,kim)) # 이씨 6명 김씨 2 명
#2. "이재영"이란 이름이 몇 번 반복되나요?
cnt = 0
for i in a :
if i == '이재영' :
cnt = cnt + 1
print('"이재영"이란 이름이 {} 번 반복된다'.format(cnt))
#3. 중복을 제거한 이름을 출력하세요.
print(set(a))
#4. 중복을 제거한 이름을 오름차순으로 정렬하여 출력하세요.
b = list(set(a))
b.sort()
b
question = ['이유덕', '이재영', '권종표', '이재영', '박민호', '강상희', '이재영', '김지완', '최승혁', '이성연', '박영서', '박민호', '전경헌', '송정환', '김재성', '이유덕', '전경헌']
count1 = 0
for a in question:
if a[0:1] == '김' or a[0:1] == '이':
count1 = count1 + 1
print('1번 정답은 {}번'.format(count1))
print('2번 정답은 {}번'.format(question.count('이재영')))
print('3번 정답: {}'.format(list(set(question))))
ans4 = sorted(question)
print('4번 정답: {}'.format(ans4))
member = ['이유덕', '이재영', '권종표', '이재영', '박민호', '강상희', '이재영', '김지완', '최승혁', '이성연', '박영서', '박민호', '전경현', '송정환', '김재성', '이유덕', '전경현']
cnt_k=0 #김씨
cnt_l=0 #이씨
cnt_j=0 #이재영
for name in member:
if name[0] == "김":
cnt_k += 1
if name[0] == "이":
cnt_l += 1
if name == "이재영":
cnt_j += 1
print("#1. answer is Kim %i, Lee %i" %(cnt_k, cnt_l))
print("#2. Leejaeyoung repeats {} times".format(cnt_j))
print("#3. Duplicated data will be removed soon.")
set_member = set(member)
for name in set_member:
print(name + ' ')
print("#4 arange")
for name in sorted(set_member):
print(name)
Python 3.6
names = ['이유덕', '이재영', '권종표', '이재영', '박민호', '강상희', '이재영', '김지완',
'최승혁', '이성연', '박영서', '박민호', '전경헌', '송정환', '김재성', '이유덕', '전경헌']
kim_count = 0
lee_count = 0
names2 = [] # not duplicated list
for name in names:
if name[0] == '김':
kim_count += 1
elif name[0] == '이':
lee_count += 1
else:
pass
if name not in names2:
names2.append(name)
print(f" 김씨 {kim_count}, 이씨 {lee_count}")
print(f" 이재영 {names.count('이재영')} ")
print(names2)
print(sorted(names2))
names = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌"
a = names.split(",")
print("1. 김씨는 {}명이고, 이씨는 {}이다.".format(names.count("김"),names.count("이")))
print("2. \"이재영\"이라는 이름은 {}번 반복된다.".format(names.count("이재영")))
print("3.", set(a))
b= set(a)
c= list(b)
c.sort()
print("4.",c)
1번 문제에서 성만 확인하도록 만들어 보았습니다.
names = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌".split(",")
i = 0
name_lee = 0
name_kim = 0
for i in range (0, len(names)) :
if names[i][:1] == "이":
name_lee += 1
elif names[i][:1] == "김":
name_kim += 1
print("이 씨는 %d 명 이고, 김 씨는 %d 명 입니다." % (name_lee, name_kim))
print("이재영은 %d 번 반복됩니다." % names.count("이재영"))
names2 = list(set(names))
print(names2)
names2.sort()
print(names2)
data = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌".split(",")
#1
a = [ i[0] for i in data ]
print('김씨 : %d\n이씨 : %d\n' %(a.count('김'), a.count('이')))
#2
print(data.count('이재영'))
#3
b = (list(set(data)))
print(b)
#4
b.sort()
print(b)
import java.util.Iterator; import java.util.LinkedHashSet; import java.util.TreeSet;
public class PlayWithNames {
public static void main(String[] args) {
String input = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌";
String[] names = input.split(",");
//1)
answer1(names);
System.out.println();
//2
answer2(names);
System.out.println();
//3
answer3(names);
System.out.println();
//3
answer4(names);
}
// TreeSet is not allowing duplicate value and automatically ordered
private static void answer4(String[] names) {
TreeSet<String> set = new TreeSet<String>();
for( int i=0; i<names.length; i++) {
set.add(names[i]);
}
Iterator<String> it = set.iterator();
while(it.hasNext()) {
System.out.print(it.next()+" ");
}
}
// LinkedHashSet is not allowing duplicate and stores as input order
private static void answer3(String[] names) {
LinkedHashSet<String> set = new LinkedHashSet<String>();
for( int i=0; i<names.length; i++) {
set.add(names[i]);
}
Iterator<String> it = set.iterator();
while(it.hasNext()) {
System.out.print(it.next()+" ");
}
}
private static void answer2(String[] names) {
int count = 0;
for( int i=0; i<names.length; i++) {
if( names[i].equals("이재영")) {
count++;
}
}
System.out.println("이재영: "+ count);
}
private static void answer1(String[] names) {
int countKim = 0;
int countLee = 0;
for( int i=0; i<names.length; i++) {
if( names[i].startsWith("김")) {
countKim++;
}
if( names[i].startsWith("이")) {
countLee++;
}
}
System.out.println("김: "+ countKim);
System.out.println("이: "+ countLee);
}
}
a = ['이유덕','이재영','권종표','이재영','박민호','강상희','이재영','김지완','최승혁','이성연','박영서','박민호','전경헌','송정환','김재성','이유덕','전경헌']
num1 = 0
num2 = 0
for name in a:
#문제 2
if( name =="이재영"):
num2 = num2 + 1
#문제 1
b = name.find('김')
c = name.find('이')
if (b == 0):
num1 = num1 + 1;
elif(c == 0):
num1 = num1 +1;
print("문제 1번 : ",num1)
print("문제 2번 : ",num2)
#문제 3
sameN =[]
for name in a:
for i in sameN:
if (i == name):
sameN.remove(i)
sameN.append(name)
print("문제 3번 : ")
print(sameN)
print("문제 4번 : ")
sameN.sort() #문제4
print(sameN)
""" 주어진 문자열(공백 없이 쉼표로 구분되어 있음)을 가지고 아래 문제에 대한 프로그램을 작성하세요.
이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌
kim_count = 0 lee_count = 0
while name: fb = name.pop() if fb[0]=="김": kim_count += 1 elif fb[0]=="이": lee_count += 1
print("김씨는 총 %d명 입니다." % kim_count) print("이씨는 총 %d명 입니다." % lee_count)
name = str_name.split(",")
ljy_count = 0 i = 0 for i in name: if i == "이재영": ljy_count += 1 print(ljy_count)
name = str_name.split(",") only_name = list(set(name)) only_str = "" for i in only_name: only_str +=(i+" ") print ("중복 제거된 이름은 \n %s\n입니다." %only_str)
so_name = sorted(only_name) so_str = "" for i in so_name: so_str +=(i+" ") print ("중복 제거된 오름차순 이름은 \n %s\n입니다." %so_str)
메모리 아끼려고 배열을 먼저 출력했습니다.
#include <iostream>
#include <list>
using namespace std;
int Compare(char* a, char* b)
{
for (int i = 0; a[i] != 0 && b[i] != 0; ++i)
{
if (a[i] != b[i])
{
return a[i] - b[i];
}
}
return 0;
}
bool IsContain(list<char*>* nameList, char* name)
{
list<char*>::iterator iter;
for (iter = nameList->begin(); iter != nameList->end(); ++iter)
{
if (Compare(*iter, name) == 0)
{
return true;
}
}
return false;
}
void PrintList(list<char*>* nameList)
{
list<char*>::iterator iter;
bool isFirst = true;
for (iter = nameList->begin(); iter != nameList->end(); ++iter)
{
if (isFirst)
{
isFirst = false;
cout << *iter;
}
else
{
cout << ", " << *iter;
}
}
}
void SortedInsert(list<char*>* nameList, char* name)
{
list<char*>::iterator iter;
for (iter = nameList->begin(); iter != nameList->end(); ++iter)
{
int comp = Compare(*iter, name);
if (comp > 0)
{
nameList->insert(iter, name);
return;
}
}
nameList->push_back(name);
}
void main()
{
char names[] = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌";
const char* lee = "이";
const char* kim = "김";
const char* jaeyoung = "재영";
int cKim = 0, cLee = 0, cLeeJaeYoung = 0;
list<char*>* uniqueNameList = new list<char*>();
int startIdx = 0;
char ch;
bool isLast = false;
cout << "중복되지 않은 이름 리스트 : ";
for (int i = 0; true; ++i)
{
ch = names[i];
if (ch == ',' || ch == '\0')
{
if (ch == '\0')
isLast = true;
names[i] = '\0';
// 김씨 카운트 증가
if (names[startIdx] == kim[0] && names[startIdx+1] == kim[1])
{
++cKim;
}
// 이씨 카운트 증가
else if (names[startIdx] == lee[0] && names[startIdx+1] == lee[1])
{
if (names[startIdx + 2] == jaeyoung[0] && names[startIdx + 3] == jaeyoung[1] &&
names[startIdx + 4] == jaeyoung[2] && names[startIdx + 5] == jaeyoung[3])
{
++cLeeJaeYoung;
}
++cLee;
}
if (!IsContain(uniqueNameList, names + startIdx))
{
if (startIdx == 0)
cout << names + startIdx;
else
cout << ", " << names + startIdx;
SortedInsert(uniqueNameList, names + startIdx);
}
if (isLast)
break;
else
startIdx = i+1;
}
}
cout << endl;
cout << "정렬된 이름 리스트 : ";
PrintList(uniqueNameList);
cout << endl;
cout << "전체 김씨 수 : " << cKim << endl;
cout << "전체 이씨 수 : " << cLee << endl;
cout << "전체 이재영 수 : " << cLeeJaeYoung << endl;
}
나중에 다시 풀겠습니다. 일단 저장
string = '이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌'
# 김씨와 이씨는 각각 몇 명 인가요?
stringList = string.split(',')
count = 0
for i in range(len(stringList)):
if stringList[i][0] == '김' or left(stringList[i][0],1) =='이':
count += 1
print(count)
# "이재영"이란 이름이 몇 번 반복되나요?
print(string.count('이재영'))
# 중복을 제거한 이름을 출력하세요.
# 중복을 제거한 이름을 오름차순으로 정렬하여 출력하세요.
a="이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌"
print(a.count("이"))
print(a.count("김"))
a=a.split(',')
print(a.count("이재영"))
set_names = set(a)
print(set_names)
for name in sorted(set_names):
print(name)
names = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌"
a = names.split(",")
dict = {}
for name in a:
if(name in dict):
dict[name] += 1
else:
dict[name] = 1
b = list(dict.keys())
kim = 0; lee = 0
for i in b:
if i[0] == "김":
kim += 1
elif i[0] == "이":
lee += 1
print("김씨는 " + str(kim) + "명, 이씨는 " + str(lee) + "명입니다")
print("이재영이라는 이름은 " + str(dict['이재영']) + "번 반복됩니다")
print(b)
b.sort()
print(b)
NameString = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌"
nameBook = NameString.split(',')
kim = 0
lee = 0
jaeyoung = 0
for i in range(0, len(nameBook)):
if nameBook[i][0] == "김":
kim = kim + 1
elif nameBook[i][0] == "이":
lee = lee + 1
if nameBook[i] == "이재영":
jaeyoung += 1
print("1. 김씨: %d, 이씨: %d" %(kim, lee))
print("2. 이재영 : %d명" %(jaeyoung))
print("3. 중복을 제거한 이름 \n{0}".format(set(nameBook)))
print("4. 중복을 제거하고 오름차순 이름 \n{0}".format(sorted(set(nameBook))))
python
names = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌"
list_names = names.split(',')
# 1. 김씨와 이씨는 각각 몇 명 인가요?
cnt_kang = 0
cnt_Lee = 0
for name in list_names:
if name[0] == '강':
cnt_kang += 1
if name[0] == '이':
cnt_Lee += 1
print(cnt_kang)
print(cnt_Lee)
# 2. "이재영"이란 이름이 몇 번 반복되나요?
list_names.count('이재영')
# 3. 중복을 제거한 이름을 출력하세요.
ex_names = list(set(list_names))
print(ex_names)
# 4. 중복을 제거한 이름을 오름차순으로 정렬하여 출력하세요.
print(ex_names.sort())
names = '이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌'
names = names.split(',')
a=0
c=0
# 1. 김씨와 이씨는 각각 몇 명인가요?
for i in range(len(names)):
if names[i][0]=='김':
a+=1
elif names[i][0]=='이':
c+=1
print('김씨: ',a)
print('이씨: ',c)
# 2. '이재영'이란 이름이 몇 번 반복되나요?
print(names.count('이재영'),'번 반복')
# 3. 중복을 제거한 이름을 출력하세요.
names=(list(set(names)))
print(names)
# 4. 중복을 제거한 이름을 오름차순으로 출력하세요.
names=sorted(names)
print(names)
파이썬
name = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌"
n_spl = name.split(",")
x = 0
lcnt = 0
kcnt = 0
while x < len(n_spl):
if n_spl[x][0] == "이":
lcnt += 1
elif n_spl[x][0] == "김":
kcnt += 1
x += 1
ljy = n_spl.count("이재영")
setN = list(set(n_spl))
n_sort = sorted(setN)
print("김씨:",kcnt," ","이씨:",lcnt)
print("이재영:",ljy)
print("중복제거:",setN)
print("정렬:",n_sort)
a='이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌'.split(',') q=0 w=0 for i in range(0,len(a)): if a[i][0]=='김': q+=1 if a[i][0]=='이': w+=1 print('김:%d, 이:%d'%(q,w)) print(a.count('이재영')) e=list(set(a)) print(e) e.sort() print(e)
a='이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌'.split(',')
q=0
w=0
for i in range(0,len(a)):
if a[i][0]=='김':
q+=1
if a[i][0]=='이':
w+=1
print('김:%d, 이:%d'%(q,w))
print(a.count('이재영'))
e=list(set(a))
print(e)
e.sort()
print(e)
sNames = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌"
lsNames = sNames.split(",")
print("이씨 : %d 명" % len(list(sName for sName in lsNames if sName[0]=="이")))
print("김씨 : %d 명" % len(list(sName for sName in lsNames if sName[0]=="김")))
print("이재영 : %d 번 반복" % len(list(sName for sName in lsNames if sName=="이재영")))
print("중복제거 : " + ",".join(list(set(lsNames))))
print("중복제거 오름차순 정렬 : " + ",".join(sorted(set(lsNames))))
input_string = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌"
name_list = input_string.split(",")
kim = 0
lee = 0
for name in name_list:
if name[0] == "이":
lee += 1
elif name[0] == "김":
kim += 1
print("김씨는 {}명이고 이씨는 {}명입니다".format(kim, lee))
print("{}번 반복됩니다".format(name_list.count("이재영")))
print(list(set(name_list)))
print(sorted(set(name_list)))
파이썬 초보입니다
name = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌"
namelist = name.split(',')
find_n = []
for n in namelist:
f1=n.find('김')
if f1==0:
find_n.append(n)
f2=n.find('이')
if f2==0:
find_n.append(n)
print(find_n)
print("김씨와 이씨의 수:",len(find_n))
find_lj = []
for n in namelist:
if n == '이재영':
find_lj.append(n)
print("이재영의 수:",len(find_lj))
remov = []
for n in namelist:
if n in remov:
continue
else:
remov.append(n)
print("중복을 제거한 이름 리스트",remov)
print("오름차순으로 정렬:",sorted(remov))
python 3.7
a = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌".split(',')
print("1. 김씨와 이씨는 각각 몇 명 인가요?")
f = [i[0] for i in a]
print("김씨 :",str(f.count('김'))+"명\n이씨 :",str(f.count('이'))+"명\n")
print('2. "이재영"이란 이름이 몇 번 반복되나요?')
print(str(a.count('이재영'))+"번\n")
print("3. 중복을 제거한 이름을 출력하세요.")
u = []
for i in a:
if i not in u:
u.append(i)
print(','.join(u)+"\n")
print("4. 중복을 제거한 이름을 오름차순으로 정렬하여 출력하세요.")
u.sort()
print(','.join(u))
3번에 set을 사용하면 순서가 섞이게 되어서 순서를 유지하기 위해 for와 if를 사용함
파이썬으로 작성했습니다.
names = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌".split(",")
print(names)
Kim = 0
Lee = 0
Leejeayong = 0
for i in names:
#김씨 찾기, 혹시 이름에 '김'이 들어갈 수 있어, 인덱스로 했습니다.
if i[0] == '김':
Kim += 1
#이씨 찾기, 혹시 이름에 '이'가 들어갈 수 있어, 인덱스로 했습니다.
if i[0] == '이':
Lee += 1
#이재영 찾기
if i == "이재영":
Leejeayong +=1
#중복을 제거한 이름을 출력
while names.count(i) > 1:
names.remove(i)
#중복을 제거한 이름을 오름차순 정렬 출력
sort_names = sorted(names)
print("김 씨의 수는", Kim, "명입니다.", sep=" ")
print("이 씨의 수는", Lee, "명입니다.", sep=" ")
print("이재영 씨의 수는" , Leejeayong, "명입니다.", sep=" ")
print("중복을 제거한 이름입니다.", names, sep=" ")
print("오름차순한 이름입니다." , sort_names, sep = " ")
Python
import string
# 1. 김씨와 이씨는 각각 몇 명 인가요?
names = ','.join(map(str,input().split())) # 실행 후 아래와 같이 입력
# 이유덕 이재영 권종표 이재영 박민호 강상희 이재영 김지완 최승혁 이성연 박영서 박민호 전경헌 송정환 김재성 이유덕 전경헌
names
res1_1 = []
res1_2 = []
name_list = names.split(',')
for i in range(len(name_list)):
if str(name_list[i])[0] == '김':
res1_1.append(True)
else:
res1_1.append(False)
if str(name_list[i])[0] == '이':
res1_2.append(True)
else:
res1_2.append(False)
res1 = dict(zip(['김씨','이씨'],[sum(res1_1),sum(res1_2)]))
print(res1)
# 2. "이재영"이란 이름이 몇 번 반복되나요?
names.count('이재영')
# 3. 중복을 제거한 이름을 출력하세요.
name_set = list(set(name_list))
print(name_set)
# 4. 중복을 제거한 이름을 오름차순으로 정렬하여 출력하세요.
name_sort = sorted(name_set)
print(name_sort)
더 간결한 코딩을 하고 싶었지만... 이를 위해서는 수련이 더 필요하겠네요...
names = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌"
namelist = names.split(",")
namelistlen = len(namelist)
Kcount = 0
Lcount = 0
for x in range(namelistlen):
if namelist[x][0] == '이':
Lcount = Lcount + 1
elif namelist[x][0] == '김':
Kcount = Kcount + 1
print("이씨는 ",Lcount, "명 있다.")
print("김씨는 ",Kcount, "명 있다.")
ljycount =0
for x in range(namelistlen):
if namelist[x] == '이재영' :
ljycount += 1
print("이재영은 ", ljycount, "번 반복됨")
setnamelist = list(set(namelist))
print(setnamelist)
setnamelist.sort()
print(setnamelist)
a="이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌"
print("1. 김씨와 이씨는 각각 몇 명인가요?\n")
count1=0
count2=0
for i in a:
if i=='김':
count1 +=1
elif i=='이':
count2 +=1
print(count1, count2)
print('\n\n')
print('2. \"이재영\"이란 이름이 몇 번 반복되나요?')
count3=0
index=0
while index<=len(a)-1:
if a[index:index+3]=="이재영":
count3 +=1
index +=4
print(count3)
print('\n\n')
print("3. 중복을 제거한 이름을 출력하세요")
index=0
b=[]
while index<=len(a)-1:
b.append(a[index:index+3])
index +=4
b=set(b)
print(b)
print('\n')
print('4. 중복을 제거한 이름을 오름차순으로 정렬하여 출력하세요')
c=list(b)
c.sort()
print(c)
k=['이유덕','이재영','권종표','이재영','박민호','강상희','이재영','김지완','최승혁','이성연','박영서','박민호','전경헌','송정환','김재성','이유덕','전경헌']
k1=k
n=int(len(k))
##1) 풀이
def knb(k):
kim=0
park=0
for i in range(0,n):
indx=str(k[i])
if indx[0]=="김":
kim+=1
elif indx[0]=="박":
park+=1
print(kim)
print(park)
##2) 풀이
def jae(k):
cnt=0
for i in range(0,n):
if k[i]=='이재영':
cnt+=1
return cnt
##3) 풀이 set 안에서는 Unique
def thrid(k):
uniq_names = list(set(k))
print(uniq_names)
##4) 풀이
def sort(k):
uniq_names = list(set(k))
uniq_names.sort()
print(uniq_names)
import java.util.Arrays;
public class jungbokjeger {
public static void main(String[] args) {
// TODO Auto-generated method stub
String Name = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌";
String NewString="";//중복제거한 스트링
String Imsi="";
int W=0;
int Kim=0,Lee=0;
int LeeJaeYoung=0;
Name=Name.replaceAll(",", "");//쉼표제거
String[] JungBok = new String[Name.length()/3];//중복있는 모든인원
for(int x=0; x<JungBok.length; x++)
{
JungBok[x]=Name.substring(W,W+3);
W+=3;
}
for(int i=0; i<JungBok.length; i++)
{
if(JungBok[i].charAt(0)=='김')
{
Kim++;//김씨 몇명?
}
else if(JungBok[i].charAt(0)=='이')
{
Lee++;//이씨몇명?
}
if(JungBok[i].equals("이재영"))
{
LeeJaeYoung++;//이재영 몇명?
}
}
W=0;
while(true)
{
Imsi=Name.substring(W,W+3);
NewString+=Imsi;
Name=Name.replaceAll(Imsi, "김빵빵");
if(W+3==Name.length())
{
break;
}
W+=3;
}
NewString=NewString.replaceAll("김빵빵", "");
String[] NotJungBok = new String[NewString.length()/3];//중복없는 모든인원
W=0;
int i=0;
while(true)
{
NewString.substring(W,W+3);
NotJungBok[i] = NewString.substring(W,W+3);
i++;
if(W+3==NewString.length())
{
break;
}
W+=3;
}
Arrays.sort(NotJungBok);
System.out.println("김씨는 몇명? : " + Kim);
System.out.println("이씨는 몇명? : " + Lee);
System.out.println("이재영은 몇명? : " + LeeJaeYoung);
System.out.println("중복제거한 인원 : " + NewString);
System.out.println("중복제거한 인원 및 오름차순: ");
for(int h=0; h<NotJungBok.length; h++)
{
System.out.print(NotJungBok[h]);
}
}
}
Java 1.11
import java.util.Arrays;
import java.util.Comparator;
import java.util.stream.Collectors;
public class Test {
public static void main(String[] args) {
String[] tokens =
"이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌".split(",");
System.out.println("1. 김씨와 이씨는 각각 몇 명 인가요?");
System.out.println("김씨 : " + Arrays.stream(tokens).filter(x -> x.startsWith("김")).count());
System.out
.println("이씨 : " + Arrays.stream(tokens).filter(x -> x.startsWith("이")).count() + "\n");
System.out.println("2. \"이재영\"이란 이름이 몇 번 반복되나요?");
System.out.println(Arrays.stream(tokens).filter(x -> x.equals("이재영")).count() + "\n");
System.out.println("3. 중복을 제거한 이름을 출력하세요.");
System.out.println(Arrays.stream(tokens).distinct().collect(Collectors.toList()) + "\n");
System.out.println("4. 중복을 제거한 이름을 오름차순으로 정렬하여 출력하세요.");
System.out.println(Arrays.stream(tokens).distinct().sorted(Comparator.reverseOrder()) + "\n");
}
}
kim = 0
lee = 0
st = '이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌'
st = st.split(',')
for i in range(0, len(st)):
if st[i][0].count('김') == 1:
kim += 1
elif st[i][0].count('이') == 1:
lee += 1
print(int(kim)+int(lee))
print(st.count('이재영'))
print(set(st))
st = set(st)
print(sorted(st))
#코딩도장 사이냅소프트 면접문제
a="이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌"
a= a.split(",")
kim=0
lee=0
for i in a:
if i[0]=='김':
kim= kim+1
if i[0]=='이':
lee= lee+1
print("김씨 %d명 이씨 %d명" %(kim ,lee))
jeayoung=0
for i in a:
if i=='이재영':
jeayoung+=1
print(jeayoung)
set_a = list(set(a))
print(set_a)
set_a.sort()
print(set_a)
#! python3
names = '이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌'.split(',')
# 김씨와 이씨는 각각 몇 명 인가요?
lastNames = [i[0] for i in names]
print('김씨: %d' %(lastNames.count('김')))
print('이씨: %d' %(lastNames.count('이')))
# "이재영"이란 이름이 몇 번 반복되나요?
print('이재명: %d' %(names.count('이재영')))
# 중복을 제거한 이름을 출력하세요
uniqueNames = set(names)
print(uniqueNames)
# 중복을 제거한 이름을 오름차순으로 정렬하여 출력하세요
print(sorted(uniqueNames))
string="이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌"
last_name_cout=0 for a in string.split(','): if a.startswith("이") or a.startswith("김") : last_name_cout+=1 print("1."+str(last_name_cout))
last_name_cout=0 for a in string.split(','): if a=="이재영": last_name_cout+=1 print("2."+str(last_name_cout))
name=[] for a in string.split(","): if a not in name: name.append(a) print (name)
name.sort() print(name)
파이썬 입문한 지 한달도 안된 신생아입니다 ㅜㅜ 코드가 혐오스러워도 이해 부탁드립니다.
책 봐가면서 이것저것 찾아본 결과 이게 지금은 제 한계네요.
a = ["이유덕"],["이재영"],["권종표"],["이재영"],["박민호"],["강상희"],["이재영"],["김지완"],["최승혁"],["이성연"],["박영서"],["박민호"],["전경헌"],["송정환"],["김재성"],["이유덕"],["전경헌"]
# 김씨와 이씨는 각각 몇 명 인가요? - 다른 방법이 생각이 안남..
print(a[0], a[1], a[3], a[7], a[-3])
print("이씨 3명 김씨 2명")
# 이재영은 몇번이 반복? - 더 방대한 자료의 경우 이 방법은 옳지 않을거라고 생각합니다..
print(a[1], a[3], a[6])
print("총 3번")
# 중복을 제거한 이름을 출력하세요. - "집합 자료형" 의 특징인 "중복 제거" 가 생각나서..
s1 = set(["이유덕","이재영","권종표","이재영","박민호","강상희","이재영","김지완","최승혁","이성연","박영서","박민호","전경헌","송정환","김재성","이유덕","전경헌"])
print(s1)
# 중복 제거한 이름을 오름차순으로 정렬하여 출력하세요. - 위키독스에서 읽었던 걸 사용..
x = sorted(s1)
print(x)
P.S
그런데 여기서 궁금한점이
처음엔 s1.sort() 로 실행 하려고 했었지만
'set' object has no attribute 'sort'
오류가 일어나는 이유가 무엇인가요?
결국에 안되서 위의 방법을 사용해봤구요..
static void Main(string[] args)
{
int Count_Lee = 0;
int Count_Kim = 0;
int Count_JaeYoung = 0;
string Name = "이유덕,이재영,권종표,이재영," +
"박민호,강상희,이재영,김지완," +
"최승혁,이성연,박영서,박민호," +
"전경헌,송정환,김재성,이유덕," +
"전경헌";
// ',' 제거
string [] NameArray = Name.Split(",");
// 중복 제거
string [] NameArrayDeduplication = NameArray.Distinct().ToArray();
// 김씨, 이씨, 이재영 이란 이름을 가진 사람이 몇명인지 카운트
for (int i = 0; i < NameArray.Length; i++)
{
string GetName = NameArray[i].Substring(0,1);
string GetJaYoung = NameArray[i];
if (GetName.Equals("이"))
{
Count_Lee++;
}
if (GetName.Equals("김"))
{
Count_Kim++;
}
if (GetJaYoung.Equals("이재영"))
{
Count_JaeYoung++;
}
}
//중복을 제거한 이름을 오름차순으로 정렬하여 출력.
var Result = from Print in NameArrayDeduplication
orderby Print
select Print;
foreach (string NamePrint in Result)
{
Console.WriteLine(NamePrint);
}
//결과
Console.WriteLine("이씨 : {0}, 김씨 : {1}, 이재영 : {2}",Count_Lee, Count_Kim, Count_JaeYoung);
}
초보개발자 입니다. 피드백은 언제나 환영입니다.
X = list(input().split(","))
kim = 0
lee = 0
name = 0
for x in X:
if "김" == x[0]:
kim = kim + 1
elif "이" == x[0]:
lee = lee + 1
if "이재영" == x:
name = name + 1
print("김씨는 %d명이고 이씨는 %d명입니다." % (kim, lee))
print("이재영이란 이름은 %d번 반복됩니다." % name)
X = list(set(X))
X.sort()
for x in X:
print(x+" ", end="")
names = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌"
# 문자열에서 ',' 기준으로 이름 분할하여 리스트 생성
namelist = names.split(',')
# 김씨, 이씨, 이재영 카운터값 초기화
kim, lee, ljy = 0, 0, 0
# 문자열 비교함수
namediff = lambda name1, name2:name1==name2
for name in namelist:
if namediff(name[0], '김'): kim += 1
elif namediff(name[0], '이'): lee += 1
if namediff(name, '이재영'): ljy += 1
# 중복 제거를 위하여 집합 자료형으로 변환
nameset = set(namelist)
# 결과 출력
print("김씨 : [%d 명], 이씨 : [%d 명], 이재영 : [%d 번 반복]" %(kim, lee, ljy))
# 중복 제거
print("제거 : ", nameset)
# 내장함수로 정렬
print("정렬 : ", sorted(nameset))
name = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌"
list_name = name.split(',')
##Q1
Kim = [names for names in list_name if names[0] == '김']
print(Kim, len(Kim))
Lee = [names for names in list_name if names[0] == '이']
print(Lee, len(Lee))
##Q2
jy_Lee = [names for names in list_name if names == '이재영']
print(len(jy_Lee))
##Q3
nameSet = set(list_name)
print(nameSet)
##Q4
nameSet = sorted(nameSet)
print(nameSet)
names = '이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최숭혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌'
lstName = names.split(',')
#No.1
print(len(list(filter(lambda x: x[0] == '김', lstName))))
print(len(list(filter(lambda x: x[0] == '이', lstName))))
#No.2
print(len(list(filter(lambda x: x == '이재영', lstName))))
#No.3
print(set(lstName))
#No.4
print(sorted(list(set(lstName))))
PHP
$str = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌";
//# 1. 김씨와 이씨는 각각 몇 명 인가요?
$result = [
preg_match_all('/(^|,)[김]/u', $str) ?: 0,
preg_match_all('/(^|,)[이]/u', $str) ?: 0
];
print_r($result); // [2, 6]
//# 2. "이재영"이란 이름이 몇 번 반복되나요?
$result = substr_count($str, '이재영');
print_r($result); // 3
//# 3. 중복을 제거한 이름을 출력하세요.
$result = implode(',', array_unique(explode(",", $str)));
print_r($result); // 이유덕,이재영,권종표,박민호,강상희,김지완,최승혁,이성연,박영서,전경헌,송정환,김재성
//# 4. 중복을 제거한 이름을 오름차순으로 정렬하여 출력하세요.
$arr = array_unique(explode(",", $str));
sort($arr);
$result = implode(',', $arr);
print_r($result); // 강상희,권종표,김재성,김지완,박민호,박영서,송정환,이성연,이유덕,이재영,전경헌,최승혁
member = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌".split(",")
a = [] for i in member: a += i[0]
print("김씨 : %d\n이씨 : %d\n"%(a.count("김"), a.count("이")))
print(member.count("이재영"))
setting = list(set(member)) print(setting)
setting.sort() print(setting)
input_data = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌"
input_data_list = input_data.split(",")
# 1
ans1_1 = len([x for x in input_data_list if x[0] == "김" or x[0] == "이"])
ans1_2 = len([x for x in input_data_list if x[0] == "김" or x[0] == "이"])
ans1 = '김씨: {kim}명, 이씨: {lee}명'.format(kim=ans1_1, lee=ans1_2)
print(ans1)
# 2
ans2 = len([x for x in input_data_list if x == "이재영"])
print(ans2)
# 3
ans3 = list(set(input_data_list))
print(ans3)
# 4
ans4 = sorted(ans3)
print(ans4)
갓갓 파이썬
data='이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌'
names=data.split(',')
#1
kim=0;lee=0
for name in names:
if name[0]=='김':kim+=1
elif name[0]=='이':lee+=1
print('김씨:%d 명, 이씨 %d 명' %(kim,lee))
#2
print(names.count('이재영'))
#3
a=list(set(names))
print(','.join(a))
#4
a.sort()
print(','.join(a))
#사이냅소프트 면접문제
names="이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌"
namelist = names.split(',')
kl_num = 0
LJY=0
for name in namelist:
if name[0]=='김':
kl_num=kl_num+1
elif name[0]=='이':
kl_num = kl_num + 1
print("김씨와 이씨의 수는?: ",kl_num)
for name in namelist:
if name == '이재영':
LJY = LJY+1
print("이재영은 몇 번 반복되었나요?:",LJY)
name_new=[]
for name in namelist:
if name not in name_new:
name_new.append(name)
print("중복을 제거한 이름:",name_new)
print("오름차순으로 정리:", sorted(name_new))
import re
inp = '이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌'
inp_list = " ".join(inp.split(','))
kim, lee = re.compile("김[^0-9]{2}"), re.compile("이[^0-9]{2}")
k_list, l_list = kim.findall(inp_list), lee.findall(inp_list)
print("1.김씨 : %d명, 이씨 : %d명" %(len(k_list), len(l_list)))
print('2.', inp.split(',').count("이재영"), "번")
print("3.", set(inp.split(',')))
print("4.", sorted(list(set(inp.split(',')))))
결과
1.김씨 : 2명, 이씨 : 6명
2.3 번
3.{'강상희', '전경헌', '송정환', '최승혁', '이재영', '박영서', '권종표', '이성연', '이유덕', '김지완', '김재성', '박민호'}
4.['강상희', '권종표', '김재성', '김지완', '박민호', '박영서', '송정환', '이성연', '이유덕', '이재영', '전경헌', '최승혁']
name_str = '이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경현,송정환,김재성,이유덕,전경현'
#Case 1
#How many people whose family name is 'Lee' or 'Kim' in the group?
Kim_count , Lee_count = 0, 0
name_list = name_str.split(',')
for name in name_list:
if name[0] == '김': Kim_count += 1
if name[0] == '이': Lee_count += 1
print('김씨 : %d명, 이씨 : %d명' % (Kim_count, Lee_count))
#Case 2
#How many 'Lee Jaeyeong' in the group?
print('이재영 : %d명' % (name_list.count('이재영')))
#Case 3
#Remove the duplicates
name_set = set(name_list)
print(name_set)
#Case 4
#Output the names with duplicates sorted in ascending order
temp = list(name_set)
print(sorted(temp))
names = ['이유덕','이재영','권종표','이재영','박민호','강상희','이재영',
'김지완','최승혁','이성연','박영서','박민호','전경헌','송정환','김재성',
'이유덕','전경헌']
first = []
for name in names:
first.append(name[0])
print("김씨 : ",first.count("김"))
print("이씨 : ",first.count("이"))
print("이재명 몇번 반복 : ",names.count("이재영"))
print("중복제거 :")
names = list(set(names))
print(names)
print("중복제거 오름차순 : ")
names.sort()
print(names)
Python 3.7.4
Snames = '이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌'
Lnames = Sname.split(",")
#1
Lsur = [i[0] for i in Lname]
print("1. 김씨는 {}명이며, 이씨는 {}명입니다.".format(Lsur.count('김'), Lsur.count('이')))
#2
print("2. 이재영은 {}명입니다.".format(Sname.count('이재영')))
#3
Luni = list(set(Lname))
print("3.",", ".join(Luni))
#4
Luni.sort()
print("4.",", ".join(Luni))
s = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌"
s_list = s.split(',')
kim, lee = 0,0
leejaeyoung = 0
for i in range(len(s_list)):
if s_list[i][0] == '김':
kim += 1
elif s_list[i][0] == '이':
lee += 1
if s_list[i] == '이재영':
leejaeyoung += 1
print('김씨 : %d, 이씨 : %d' %(kim, lee))
print('이재영 : %d' %leejaeyoung)
s_set = list(set(s_list))
print(s_set)
print(sorted(s_set))
JAVA입니다.
public class DuplicatedName {
public static void main(String[] args) {
String[] str = {"이유덕","이재영","권종표","이재영","박민호","강상희","이재영","김지완","최승혁","이성연","박영서","박민호","전경헌","송정환","김재성","이유덕","전경헌"};
int cntFamilyKim = 0;
int cntFamilyLee = 0;
int cntLeejy = 0;
List<String> list = new ArrayList<String>();
for(int i=0; i<str.length; i++) {
if(str[i].startsWith("김") ) {
cntFamilyKim++;
if(cntFamilyKim > 1) { //중복 제거하기
str[i] = str[i]+"중복";
}
}
else if( str[i].startsWith("이")) {
cntFamilyLee++;
if(cntFamilyLee > 1 && (!"이재영".equals(str[i]))) {
str[i] = str[i]+"중복";
}
}
}
for(int i=0; i<str.length; i++) {
if( str[i].startsWith("이재영") ) { // 이재영 세기
cntLeejy++;
if(cntLeejy > 1) {
str[i] = str[i]+"중복";
}
}
} // end of for
System.out.println("김씨, 이씨의 수는 : "+cntFamilyKim+cntFamilyLee);
System.out.println("이재영의 수는 : "+cntLeejy);
Arrays.sort(str);
for(String s : str) {
if(! s.endsWith("중복") ) {
list.add(s);
}
}
System.out.print("중복을 제거하고 정렬하면 : ");
for(int i=0; i<list.size(); i++) {
String s = (i==list.size()-1)?"":", ";
System.out.print(list.get(i)+s);
}
}
}
답 : 강상희, 권종표, 김지완, 박민호, 박민호, 박영서, 송정환, 이유덕, 이재영, 전경헌, 전경헌, 최승혁
package CodingDojang;
import java.util.ArrayList;
import java.util.Collections;
public class SinapSoftQuiz {
public static void main(String[] args) {
String ans = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,"
+ "김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌";
String[] name = ans.split(",");
int result_lee = 0, result_kim = 0, result_ljy = 0;
for(int i = 0; i < name.length; i++) {
if(name[i].startsWith("이")) result_lee += 1;
else if(name[i].startsWith("김")) result_kim += 1;
if(name[i].equals("이재영")) result_ljy += 1;
}
System.out.println("1.이씨의 수 :"+result_lee+" 김씨의 수 :"+result_kim);
System.out.println("2.이재영 이름의 반복의 수 :"+result_ljy);
ArrayList<String> array_name = new ArrayList<String>();
int array_count = 0;
for(int i = 0; i < name.length; i++) {
for(int j = i + 1; j < name.length; j++) {
if(name[i].equals(name[j])) {
name[i] = "";
}
}
if(name[i] != "") {
array_name.add(array_count, name[i]);
array_count++;
}
}
System.out.print("3.중복을 제거한 이름 출력 :");
for(int i = 0; i < array_name.size() - 1; i++) {
String n = array_name.get(i);
System.out.print(n+",");
}
System.out.println(array_name.get(array_name.size() - 1));
Collections.sort(array_name);
System.out.print("4.중복을 제거한 이름 오름차순 으로 출력 :");
for(int i = 0; i < array_name.size() - 1; i++) {
String n = array_name.get(i);
System.out.print(n+",");
}
System.out.println(array_name.get(array_name.size() - 1));
}
}
오늘도 노가다를 하는 개발자가 되고 싶은 1인...
data =['이유덕','이재영','권종표','이재영','박민호','강상희','이재영','김지완','최승혁','이성연','박영서','박민호','전경헌','송정환','김재성','이유덕','전경헌'] num_of_kim = 0 num_of_lee = 0 num_of_J = 0
for x in data: if data[0] == '김': num_of_kim =+ 1 elif data[0] == '이': numnum_of_lee += 1
print('{},{}'.format(num_of_kim,num_of_lee))
for x in data: if data == '이재영': num_of_J += 1 pring("{}".format(num_of_J))
newlist = list(set(data)) print(newlist)
newlist.sort() pring(newlist)
package Practice;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.TreeSet;
public class 사이냅소프트면접문제 {
public static void main(String[] args) {
String input = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌";
String[] names = input.split(",");
ArrayList<String> list = new ArrayList<String>();
for(int k =0; k<names.length; k++) {
list.add(names[k]);
}
int theNumberOfLee = 0;
int theNumberOfKim = 0;
int theNumberOf이재영 = 0;
for(int i=0; i<names.length; i++) {
if(names[i].startsWith("이")) {
theNumberOfLee+=1;
}
else if(names[i].startsWith("김")) {
theNumberOfKim+=1;
}
}
System.out.println("김씨는 총 "+theNumberOfKim+"명 입니다.");
System.out.println("이씨는 총 "+theNumberOfLee+"명 입니다.");
for(int j = 0; j<names.length; j++) {
if(names[j].equals("이재영")) {
theNumberOf이재영 +=1;
}}
System.out.println("\"이재영\"이란 이름은 총 "+theNumberOf이재영+"번 반복됩니다.");
HashSet<String> names_list = new HashSet<String>(list);//HashSet은 중복을 제거할때
System.out.println(names_list);
TreeSet<String> 오름차순 = new TreeSet<String>(names_list);//TreeSet은 오름차순 정렬
System.out.println(오름차순);
}
}
names = "LYD,LJY,KJP,LJY,PMH,KSH,LJY,KJW,CSH,LSY,PYS,PMH,JKH,SJH,KJS,LYD,JKH"
count_L = 0
count_K = 0
count_LJY = 0
list_name = []
for name in names.split(','):
if name[:1] == "L":
count_L += 1
if name[:1] == "K":
count_L += 1
if name == "LJY":
count_LJY += 1
list_name.append(name)
print count_L, count_K, count_LJY
print set(list_name)
print sorted(set(list_name))
k = '이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌'
a = list(k.split(','))
count_kim = 0
count_lee = 0
count_leejaeyoung = 0
for i in a:
if i[0] == '김':
count_kim += 1
if i[0] == '이':
count_lee += 1
if i == '이재영':
count_leejaeyoung += 1
print(j)
print(p)
print(r)
unique = set(a)
unique = sorted(unique, reverse = True)
print(unique)
names = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌".split(",")
a = [i[0] for i in names] print("김씨 : %d"%(a.count("김"))) print("이씨 : %d"%(a.count("이")))
print(names.count("이재영"))
uniq_names = list(set(names)) print(uniq_names)
uniq_names.sort() print(uniq_names)
names = '이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌'
# 1. 김씨와 이씨는 각각 몇 명 인가요?
names_list = names.split(',')
lee = 0
park = 0
for name in names_list:
if name[0] == '박':
park += 1
elif name[0] == '이':
lee += 1
print(lee)
print(park)
# 2. '이재영'이란 이름이 몇 번 반복되나요?
names_list.count('이재영')
# 3. 중복을 제거한 이름을 출력하세요.
set(names_list)
# 4. 중복을 제거한 이름을 오름차순으로 정렬하여 출력하세요.
names_unique = list(set(names_list))
names_unique.sort()
names_unique
names='이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌'
countLee = 0; kim=0 lee=0
name = names.split(',')
setNames=set()
for i in name: if i[0] == '김': kim+=1 elif i[0] == '이': lee+=1 if i == '이재영': countLee+=1 setNames.add(i)
print(kim) print(lee) print(countLee)
listNames=list(setNames) for i in listNames: print(i,end=' ') print() listNames.sort() for i in listNames: print(i,end=' ')
파이썬입니다.
# Q1.
member = '이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌'.split(',')
a = [i[0] for i in member]
print('김씨는 {}명 입니다. \n이씨는 {}명 입니다.'.format(a.count('김'), a.count('이')))
# Q2.
print(member.count('이재영'))
# Q3.
unq_member = list(set(member))
print(unq_member)
# Q4.
unq_member.sort()
print(unq_member)
name= '이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌' print(name.count('김')) print(name.count('이'))
name = '이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌' b = name.split(',') print(b.count('이재영'))
name = '이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌' b = name.split(',') c = set(b) print(c)
print(sorted(c))
names = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌".split(",")
family_name=[i[0] for i in names]
print(family_name.count("김"), family_name.count("이"))
print(names.count("이재영"))
ex_names = list(set(names))
print(ex_names)
print(sorted(ex_names))
파이썬
import re
a = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌"
m1 = re.findall('(이\w{2})',a) m2 = re.findall('(김\w{2})',a) m3 = re.findall('(이재영)',a)
a=a.split(',')
print(len(m1)) print(len(m2)) print(len(m3)) print(set(a)) b=list(set(a)) b.sort() print(b)
a="이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌"
b=a.split(",")
kc=0
lc=0
for name in b:
sex=name[0]
if sex=="이":
lc+=1
if sex=="김":
kc+=1
print("김씨는",kc,"명이고", "이씨는",lc,"명입니다.") #1번 문제 답변
print("이재영은",b.count("이재영"),"번 반복됩니다") #2번 문제 답변
print(list(set(b))) #3번 문제 답변
print(sorted(list(set(b)))) #4번 문제 답변
names = input('이름을 입력하시오: ')
names_list = names.split(',')
First = [i[0] for i in names_list]
Kim = First.count('김')
Lee = First.count('이')
LJY = names_list.count('이재영')
print('김씨와 이씨는 각각 몇 명인가요? ')
print(f'김씨와 이씨는 각각 {Kim}, {Lee} 명 입니다.\n')
print('"이재영"이란 이름이 몇 번 반복되나요?')
print('{0}번 반복됩니다.\n'.format(LJY))
names = list(set(names_list))
for i in range(len(names)-1):
print(names[i], end = ',')
print(names[i+1],'\n')
names.sort()
for i in range(len(names)-1):
print(names[i], end = ',')
print(names[i+1])
names = '이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌'
nameLst = names.split(",")
k_cnt = 0
l_cnt = 0
ljy_cnt = 0
for i in nameLst:
if (i[0] == "김"):
k_cnt = k_cnt+1
if (i[0]== "이"):
l_cnt = l_cnt+1
if i == "이재영":
ljy_cnt = ljy_cnt+1
print("Kim :%d\t Lee:%d"%(k_cnt,l_cnt))
print("이재영: %d"%(ljy_cnt))
noDupleLst = list(set(nameLst))
print("중복x: ")
print(noDupleLst)
noDupleLst.sort()
print("오름차순: ")
print(noDupleLst)
파이썬!
line = '이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌'.split(',')
# 1
kim = 0
lee = 0
for i in line:
if i[0]=='김': kim += 1
elif i[0]=='이': lee += 1
print('김씨와 이씨는 각각 {0}명, {1}명 입니다'.format(kim,lee))
print()
# 2
print('이재영이라는 이름은 {}번 반복됩니다'.format(line.count('이재영')))
print()
# 3
name_once = list(set(name for name in line))
print('중복을 제거한 이름은 {}입니다'.format(name_once))
print()
# 4
name_once.sort()
print('중복을 제거한 이름의 오름차순 나열은 {}입니다'.format(name_once))
names = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌"
list1 = names.split(',')
def FirstName(list1):
countKim = 0
countLee = 0
countLJM = 0
for name in list1:
if name[0] == '김':
countKim += 1
if name[0] == '이':
countLee += 1
if name == '이재영':
countLJM += 1
return countKim, countLee, countLJM
# 1,2
print(FirstName(list1))
# 3
print(list(set(list1)))
# 4
print(sorted(list(set(list1))))
a="이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌"
a=a.split(",")
print("김씨:",sum(1 for i in a if i[0] == "김")," 이씨:",sum(1 for i in a if i[0] == "이")) #1번
print([a[x][0] for x in range(len(a))].count("김"),[a[x][0] for x in range(len(a))].count("이")) #1번
print("이재영:" + str(a.count("이재영")))
a = list(set(a))
print(a)
a.sort()
print(a)
----------
반복되는 사람만 세기
a=a.split(",")
b=set(a)
print(list( x +":"+ str(a.count(x))+"명" for x in b if a.count(x) !=1))
names='이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌'.split(',')
frist_name=[i[0] for i in names]
print('김:{} 이:{}'.format(frist_name.count('김'),frist_name.count('이')))
print('이재영:{}'.format(names.count('이재영')))
print('{}'.format(set(names)))
only=list(set(names))
only.sort()
print('{}'.format(only))
Nlist = ['이유덕','이재영','권종표','이재영','박민호','강상희','이재영','김지완','최승혁','이성연','박영서','박민호','전경헌','송정환','김재성','이유덕','전경헌']
Na1,Na2,Na3 = 0,0,0
Nset = set(Nlist)
Nfinish = list(Nset)
Nfinish.sort()
for i in range(len(Nlist)):
if Nlist[i][0] == "김":
Na1 += 1
if Nlist[i][0] == "이":
Na2 += 1
if Nlist[i] == "이재영":
Na3 += 1
print(f'1.김씨는 {Na1}명이고 이씨는 {Na2}명이다.')
print(f'2.이재영은 {Na3}번 반복된다.')
print(f'3.{Nset}')
print(f'4.{Nfinish}')
A = ['이유덕','이재영','권종표','이재영','박민호','강상희', '이재영','김지완','최승혁','이성연','박영서','박민호', '전경헌','송정환','김재성','이유덕','전경헌']
#1번
result1 = [] result2 = [] i = 0 for A[i] in A: if A[i][0] == "김": result1.append(A[i]) elif A[i][0] == "이": result2.append(A[i])
print(len(result1))print(len(result2))
A.count("이재영")
A_list = list(set(A)) print(A_list)
A_list.sort() print(A_list)
class Search {
private val names: String =
"이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌"
private val kim: String = "김"
private val lee: String = "이"
private val leejaeyoung: String = "이재영"
var familyNameCount: Int = 0
var nameCount: Int = 0
fun init() {
var nameArray: List<String> = names.split(",")
var nameSet: MutableSet<String> = mutableSetOf()
for (i in 1 until nameArray.size) {
if (nameArray[i].startsWith(kim) || nameArray[i].startsWith(lee)) {
familyNameCount++
}
if (nameArray[i].contains(leejaeyoung)) {
nameCount++
}
nameSet.add(nameArray[i])
println(i)
}
println("Kim + Lee? : $familyNameCount")
println("LeeJaeYoung? : $nameCount")
println("RemoveRepeat : $nameSet")
println("Sort : " + nameSet.toList().sorted());
}
}
import collections
def question(s):
s = s.split(',')
answer = 0
for i in s:
if i[0] == '김' or i[0] == '이':
answer += 1
print('1번', answer)
checklist = collections.Counter(s)
print('2번', checklist['이재영'])
print('3번', list(checklist.keys()))
print('4번', sorted(checklist.keys()))
python 3.8
a="이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌".split(",")
print([str([i[0] for i in a].count(j))+":"+ j for j in ['김','이']] ) # 김,이 각각 몇 명
print('이재영 : ' + str(a.count('이재영'))) # 이재명은 몇 명
print(set(a)) # 중복이름 제거
print(sorted(set(a))) # 중복이름 오름차순 정렬
name_list = ["이유덕","이재영","권종표","이재영","박민호","강상희","이재영","김지완","최승혁","이성연","박영서","박민호","전경헌","송정환","김재성","이유덕","전경헌"]
#1. 김씨와 이씨는 각각 몇 명인가요?
kim_list = []
lee_list = []
for name in name_list:
if name[0] == "김":
kim_list.append(name)
elif name[0] == "이":
lee_list.append(name)
kim_num = len(kim_list)
lee_num = len(lee_list)
print("1. 김씨와 이씨는 각각 몇 명인가요?")
print("김씨: %d명" % kim_num)
print("이씨: %d명" % lee_num)
print("")
#2. "이재영"이라는 이름이 몇 번 반복되나요?
jy = name_list.count("이재영")
print("2. \"이재영\"이라는 이름이 몇 번 반복되나요?")
print("\"이재영\"이라는 이름은 %d번 반복되었습니다." % jy)
print("")
#3. 중복을 제거한 이름을 출력하세요.
name_set = set(name_list)
print("3. 중복을 제거한 이름을 출력하세요.")
print(name_set)
print("")
#4. 중복을 제거한 이름을 오름차순으로 정렬하여 출력하세요.
print("4. 중복을 제거한 이름을 오름차순으로 정렬하여 출력하세요.")
print(sorted(name_set))
print("")
쓰고 보니 여러 함수들이 많아서 더 간략하게도 작성이 가능하군요;; 역시 아직 공부가 부족합니다.
import string
name_List = ['이유덕','이재영','권종표','이재영','박민호','강상희','이재영','김지완','최승혁','이성연','박영서','박민호','전경헌','송정환','김재성','이유덕','전경헌']
count_LeeJaeYoung = 0
count_Kim = 0
count_Lee = 0
for i in range(0, len(name_List)-2):
if name_List[i] == '이재영':
count_LeeJaeYoung += 1
if count_LeeJaeYoung > 1:
name_List.pop(i)
for name in name_List:
if name.startswith('김'):
count_Kim += 1
if name.startswith('이'):
count_Lee += 1
print(name_List)
name_List.sort()
print(count_LeeJaeYoung)
print(count_Kim)
print(count_Lee)
print(name_List)
names = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌"
a = names.split(',')
count_K = 0;
count_L = 0;
for name in a:
if name[0] == '김':
count_K += 1
elif name[0] == '이':
count_L += 1
continue
print("김씨 성을 가진 사람들 : ",end='')
for name in a:
if name[0] == '김':
print(name,end=' ')
print("\n이씨 성을 가진 사람들 : ",end='')
for name in a:
if name[0] == '이':
print(name,end=' ')
print("\n김씨 성의 개수 : ",count_K)
print("이씨 성의 개수 : ",count_L)
count_LEE = 0
for name in a :
if name == '이재영':
count_LEE += 1
print("이재영이란 이름이 나온 횟수",count_LEE)
set_names = set(a)
print("중복을 제거한 이름 : ",set_names)
print("오름차순으로 정렬한 이름들")
for name in sorted(set_names):
print(name,end=' ')
name = ['이유덕','이재영','권종표','이재영','박민호','강상희','이재영','김지완','최승혁','이성연','박영서','박민호','전경헌','송정환','김재성','이유덕','전경헌']
#1
n1 = 0
for x in name:
if '김' in x:
n1 += 1
elif '이' in x:
n1 += 1
#2
n2 = 0
for y in name:
if '이재영' in y:
n2 += 1
#3
name3 = set(name)
#4
name4 = list(name3)
name4.sort()
print(n1)
print(n2)
print(name3)
print(name4)
names = list(map(str, input().split(',')))
count_k = 0 count_y = 0
for i in names: if i[0] == '김': count_k +=1 elif i[0] =='이': count_y +=1
print("1. number of Kim: {0} and number of Yi: {1}".format(count_k, count_y))
counting_lee = names.count("이재영") print("2.'이재영'이란 이름이 몇 번 반복되나요? {0}".format(counting_lee))
set_no_red = set(names) print(set_no_red)
convert_l = list(set_no_red) sorting_set = sorted(convert_l, reverse=True) print(sorting_set)
counting_lee = names.count("이재영") print("2.'이재영'이란 이름이 몇 번 반복되나요? {0}".format(counting_lee))
set_no_red = set(names) print(set_no_red)
convert_l = list(set_no_red) sorting_set = sorted(convert_l, reverse=True) print(sorting_set)
class Program
{
static string input = "이유덕, 이재영, 권종표, 이재영, 박민호, 강상희, 이재영, 김지완, 최승혁, 이성연, 박영서, 박민호, 전경헌, 송정환, 김재성, 이유덕, 전경헌";
static void Main(string[] args)
{
int K_count = 0 ; int L_count = 0; int ijy_count = 0;
string[] result = input.Split(',');
List<string> list = new List<string>();
for (int i = 0; i<result.Length; i++)
{
string final = result[i].Replace(" ","");
if (final.Equals("이재영")) ijy_count += 1;
if (final.Contains("김")) K_count += 1;
else if (final.Contains("이")) L_count += 1;
list.Add(final);
}
Console.WriteLine("1. 김씨는 {0}명, 이씨는 {1}명",K_count, L_count);
Console.WriteLine("2 .이재영씨는 {0}번 나옵니다.", ijy_count);
result = result.Distinct().ToArray();
Console.Write("3. 중복 제거한 이름은 :");
for (int j=0; j<list.Count; j++)
{
Console.Write("{0} ",list[j]);
}
Console.WriteLine();
Console.Write("4. 정렬한 이름은 :");
list.Sort();
for (int j = 0; j < list.Count; j++)
{
Console.Write("{0} ", list[j]);
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
string prob = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌";
string[] name = prob.Split(",");
int[] count ={0, 0, 0};
foreach(string n in name)
{
if (n == "이재영") { count[2]++; }
n.ToCharArray();
if (n[0] == '김')
{
count[0]++;
}
else if(n[0]=='이')
{
count[1]++;
}
}
Console.WriteLine("김씨는 {0}명, 이씨는 {1}명, 이재영은 {2}번 반복된다.",count[0],count[1],count[2]);
name = name.Distinct().ToArray();
foreach(string a in name)
{
Console.Write("{0}, ", a);
}
Console.WriteLine("");
List<string> answer=name.ToList();
answer.Sort();
foreach (string a in answer)
{
Console.Write("{0}, ", a);
}
}
}
}
names = ['이유덕','이재영','권종표','이재영','박민호','강상희','이재영','김지완','최승혁','이성연','박영서','박민호','전경헌','송정환','김재성','이유덕','전경헌']
kim=0
lee=0
for name in names:
if '김' in name:
kim += 1
elif '이' in name:
lee += 1
print("김씨는 %d 명이고 이씨는 %d 명입니다."%(kim,lee))
ljy = 0
for name in names:
if name == '이재영':
ljy += 1
print('"이재영"이라는 이름은 %d 번 반복됩니다.'% ljy)
newnames = []
for name in names:
if name not in newnames:
newnames.append(name)
print('중복제외한 명단:',newnames)
newnames.sort()
print('오름차순 명단:', newnames)
list1 = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완," \
"최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌"\
.split(',')
# 1.
kim = 0
lee = 0
for x in range(len(list1)):
if tuple(list1[x])[0] == '김':
kim += 1
elif tuple(list1[x])[0] == '이' :
lee += 1
print(kim, lee) # 2 , 6
# 2.
leejeayung = 0
for x in range(len(list1)):
if list1[x] == '이재영':
leejeayung += 1
print(leejeayung) # 3
# 3.
again = 0
list2 = list()
for x in range(len(list1)):
for i in range(x + 1, len(list1)):
if list1[x] == list1[i]:
again = 1
if again == 1:
again = 0
continue
list2.append(list1[x])
print(list2)
# 4.
list2.sort()
print(list2)
names = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌".split(',')
# 김씨와 이씨는 각각 몇 명 인가요?
cntKim = 0
cntLee = 0
for lastName in names:
if lastName[0] == "김":
cntKim += 1
elif lastName[0] == "이":
cntLee += 1
print("김씨는" + str(cntKim) + "명,", "이씨는" + str(cntLee) + "명")
# "이재영"이란 이름이 몇 번 반복되나요?
cnt = 0
for name in names:
if name == "이재영":
cnt += 1
print("이재영씨는 " + str(cnt) + "번")
# 중복을 제거한 이름을 출력하세요.
print(set(names))
# 중복을 제거한 이름을 오름차순으로 정렬하여 출력하세요.
print(sorted(set(names)))
mylist=input().split(',') cnt1 , cnt2, cnt3= 0,0,0 for i in range(len(mylist)): if mylist[i][0] == '김': cnt1 = cnt1+1 if mylist[i][0]=='이': cnt2= cnt2+1 if mylist[i] =="이재영": cnt3 = cnt3+1 print("{}\n{}\n{}".format(cnt1, cnt2, cnt3)) mylist2=[] for i in range(len(mylist)): flag =True for j in range(len(mylist2)): if mylist2[j]==mylist[i]: flag=False if flag==True: mylist2.append(mylist[i]) print(mylist2) print(sorted(mylist2))
name = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌"
name_list = name.split(',')
name_lee = 0
name_kim = 0
name_leejayoung = 0
for i in range(len(name_list)):
if name_list[i][0] == '이':
name_lee += 1
if name_list[i][0] == '김':
name_kim += 1
print(name_lee, name_kim)
for i in range(len(name_list)):
if name_list[i] == '이재영':
name_leejayoung += 1
print(name_leejayoung)
uniq_name_list = list(set(name_list))
print(uniq_name_list)
uniq_name_list.sort()
print(uniq_name_list)
나름 제 스타일대로 풀어봣어요 ㅋㅋ 리스트 수작업한게 후회되군요
name_list = ['이유덕','이재영','권종표','이재영','박민호','강상희','이재영','김지완','최승혁','이성연','박영서','박민호','전경헌','송정환','김재성','이유덕','전경헌']
kim=0
lee=0
leejae=0
for i in name_list:
if list(i)[0]=='김':
kim = kim+1
elif list(i)[0]=='이':
lee = lee+1
if i == '이재영':
leejae = leejae+1
print('성이 김씨인 사람의 수 : ' + str(kim) + '성이 이씨인 사람의 수 : ' + str(lee) + '이름이 이재영인 사람인 사람의 수 : ' + str(leejae))
print((set(name_list)))
print(sorted(set(name_list)))
kim = 0
lee = 0
names = ["이유덕", "이재영", "권종표", "이재영", "박민호", "강상희", "이재영", "김지완", "최승혁", "이성연", "박영서", "박민호", "정경헌", "송정환", "김재성", "이유덕", "전경헌"]
for i in range(0, len(names)): #1, #2
namei = names[i]
if namei[0] == "김":
kim += 1
elif namei[0] == "이":
lee += 1
names_del = set(names) #3
asc_order = sorted(names_del) #4
print(kim)
print(lee)
print(names_del)
print(asc_order)
names = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌"
names_list = names.split(",")
# 1
count = 0
for i in names_list:
if i[0] == "김" or i[0] == "이":
count += 1
print(count)
# 2
count = 0
for i in names_list:
if i == "이재영":
count += 1
print(count)
# 3
names_set = set(names_list)
print(set(names_list))
# 4
print(sorted(names_set))
파이썬 초보인데 이정도면 어느정도 수준인지 알 수 있을까요?
i = input('이름을 작성하세요 : ')
i = i.split(',')
#-----------------------------------------------
# 성과 이름을 구분시켜서 딕셔너리에 저장해주는 함수
iiii = []
j = {}
def Classification_Last_Name(a):
# 성만 골라서 분류하기
global ii
ii = []
for B in range(len(a)):
ii.append(a[B][0])
ii = list(set(ii))
def Classification_Full_Name(a):
# 성별로 이름 분류하기
Classification_Last_Name(a)
for C in range(len(ii)):
global iii
iii = []
for A in range(len(i)):
if ii[C] == i[A][0]:
iii.append(i[A])
iiii.append(iii)
# 성 : 이름 으로 딕셔너리 만들기
for D in range(len(ii)):
j.setdefault('%s' %ii[D],'%s' %iiii[D])
print(j)
Classification_Full_Name(i)
#-----------------------------------------------
# 성 별로 몇 명이 있는지 확인해주는 함수
def Find_Full_Name(a):
print('해당하는 성을 가진 이름은 ', j[a])
E = '%s' %j[a].strip('[]')
E = E.split(',')
print('해당하는 성을 가진 이름의 개수는 ', len(E))
print("")
print("--------------------------------------------")
I = input('찾고 싶은 성을 작성하세요 : ')
Find_Full_Name(I)
print("--------------------------------------------")
print("")
#-----------------------------------------------
#반복되는 이름 찾아주는 함수
def Find_Repeated_Name(a):
F = 0
for aa in range(len(iiii)):
for aaa in range(len(iiii[aa])):
if a == iiii[aa][aaa]:
F += 1
print('해당하는 이름(%s)이 쓰인 수는 ' %a, F)
#-----------------------------------------------
#반복되는 이름을 제거한 리스트를 만들고 제거된 이름을 출력해주는 함수
aaaa = []
def Remove_Repeated_Name(a):
for aa in range(len(iiii)):
for aaa in range(len(iiii[aa])):
if a == iiii[aa][aaa]:
for xxx in range(len(iiii[aa])):
aaaa.append(iiii[aa][xxx])
aaaa = list(set(iiii[aa]))
print("제거된 이름은 %s 이며 따라서 %s와 같은 성을 가지는 이름은 " %(a,a))
print(aaaa, '이고 개수는 %s개입니다. ' %len(aaaa))
print("")
print("--------------------------------------------")
ii = input('중복되었는지 확인하고 싶은 이름을 작성하세요 : ')
Find_Repeated_Name(ii)
print("--------------------------------------------")
Remove_Repeated_Name(ii)
print("")
#-----------------------------------------------
#반복되는 이름 찾아 오름차순으로 정렬시켜 출력해주는 함수
def Sorted_Removed_Name(a):
II = list(set(a))
II.sort()
a.sort()
B = []
for BB in range(len(a)):
B.append(a[BB])
for bb in range(len(II)):
if II[bb] in a:
B.remove(II[bb])
B = list(set(B))
print('반복되는 이름은 %s입니다. ' %B)
print("")
print("--------------------------------------------")
Sorted_Removed_Name(i)
print("--------------------------------------------")
print("")
name = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌"
a = name.split(',')
stack = 0
find_jae = 0
for i in a:
if i[0] == '김' or i[0] == '이':
stack += 1
if i == '이재영':
find_jae += 1
bs = list(set(a))
bs.sort()
print("김과 이가 들어간 이름의 수는 총",stack,"개 입니다.")
print("이재명이라는 이름은 총",find_jae,"개 입니다.")
print(bs)
파이썬 3,4번은 풀의과정을 보고 set()가 중복된 것을 걸러 주는 것을 배워갑니다
people = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌"
people_list = people.split(',')
count1 = 0
count2 = 0
count3 = 0
for i in people_list:
if i[0] == '이':
count1 += 1
if i[0] == '김':
count2 += 1
if i == '이재영':
count3 += 1
print("1번 이씨 : {a}명 , 김씨 : {b}명".format(a = count1, b = count2))
print("2번 :",format(count3))
s = list(set(people_list))
print("3번 :",s)
print("4번 :",sorted(s))
str1 = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌"
int1 = 0
int2 = 0
int3 = 0
lst1 = str1.split(",")
for i in lst1 :
if i[0] == "김" : int1 += 1
if i[0] == "이" : int2 += 1
if i.count("이재영") : int3 += 1
print("김씨 : " + str(int1) +"\n이씨 : " + str(int2))
print("이재영 수 : " + str(int3))
set1 = set(lst1)
print(set1)
lst2 = list(set1)
lst2.sort()
print(lst2)
파이썬 공부하고 있습니다.. 나오긴 하는데 코드가 깔끔하진 않은것 같아요.
a="이유덕","이재영","권종표","이재영","박민호","강상희","이재영","김지완","최승혁","이성연","박영서","박민호","전경헌","송정환","김재성","이유덕","전경헌"
#1. 김씨와 이씨는 각각 몇명인가요?
listA = list(a)
Lee =0
Kim =0
for i in a:
if i[0] =="이": Lee+=1
elif i[0] =="김": Kim+=1
print("이씨는 %s명 입니다" %Lee)
print("김씨는 %s명 입니다" %Kim)
#2. 이재영이라는 이름이 몇 번 반복되나요?
num_of_ljy = listA.count("이재영")
print("이재영은 %s번 반복됩니다."%num_of_ljy)
#3. 중복을 제거한 이름을 출력하세요.
setList = list(set(listA))
print(",".join(setList))
#4. 중복을 제거한 이름을 오름차순으로 정렬하여 출력하세요.
setList.sort()
print(",".join(setList))
names = '이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌'
namelist = names.split(',') #이름들을 , 로 나눠 리스트로 저장
def HowManyKimLee(a): #1번 문제 김씨와 이씨
kim = [] #김씨들을 담을 리스트
lee = [] #이씨들을 담을 리스트
for indvName in a:
if '김' in indvName[0]: #김 이 들어간 리스트의 항목들을 김씨 리스트에 저장
kim.append(indvName)
if '이' in indvName[0]: #이 가 들어간 리스트의 항목들을 이씨 리스트에 저장
lee.append(indvName)
kims = int(len(kim)) #김씨 리스트에 저장된 김씨들의 수
lees = int(len(lee)) #이씨 리스트에 저장된 이씨들의 수
print('김씨는 %d명 있습니다.'%kims)
print('이씨는 %d명 있습니다.'%lees)
def HowManyJaeYoung(a): #2번 문제 이재영 몇명?
jaeyoungs = [] #이재영들을 담을 리스트
for jaeyoung in a:
if jaeyoung == '이재영': #이름 리스트에 있는 이재영들을 이재영 리스트에 추가
jaeyoungs.append(jaeyoung)
ljy = int(len(jaeyoungs)) #이재영 리스트의 길이를 구함 ('이지영'의 갯수)
print('이재영은 %d번 반복 됩니다.'%ljy)
def NoDupName(a): #3번 문제 중복 제거
NoDup = list(set(namelist)) #set로 중복 제거 후 리스트로 변환
print(NoDup)
def SortedNameList(a): #4번 문제 중복 제거 후 오름차순
sortlist = sorted(list(set(a))) #set 로 중복 제거 - 리스트로 변환 - 정렬
print(sortlist)
HowManyKimLee(namelist)
HowManyJaeYoung(namelist)
NoDupName(namelist)
SortedNameList(namelist)
_name = '이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌'
x = 0
y = 3
_kim_num = 0
_lee_num = 0
_num_ljy = 0
_list = []
_num = int(len(_name)/4)
if len(_name)%4>0:
_num += 1
for i in range(_num):
_list.append(_name[x:y])
x += 4
y += 4
#_list = _name.split(',')
for j in range(0, _num):
if _list[j][0] == "김":
_kim_num += 1
elif _list[j][0] == "이":
_lee_num += 1
#_kim_num = _name.count(김)
#_lee_num = _name.count(이) 이름이 '김김이' 인 사람이 있다면 잘못 된 값을 출력할 것
print('김씨는 총 %s명, 이씨는 총 %s명입니다.'%(_kim_num, _lee_num))
for j in range(0, _num):
if _list[j] == "이재영":
_num_ljy += 1
#_num_ljy = _list.count(이재영)
print('이재영은 총 %s번 나옵니다.' %(_num_ljy))
_list = list(set(_list))
print('중복 제거한 이름', _list)
_list_sort = sorted(_list)
print('정렬한 이름', _list_sort)
파이썬입니다 #으로 쓴건 간단하게 대체 가능한 부분입니다.
import re
def test(name): # 중복이름 제거하는 함수
result=[]
for i in range(len(name)):
if name[i] not in result:
result.append(name[i])
return result
name = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌"
name=name.split(",") # str의 split함수는 문자열을()안의 ,로 나누어 list형태로 돌려준다. 따라서 list[0]은 이유덕, list[1]은 이재영 이렇게 순차적으로 담긴다.
#1. 김씨와 이씨는 각각 몇명인가요?
lee=re.compile("이..") #정규식으로 세글짜중 첫번째 즉, 성만 일치할경우 Match 됨
kim=re.compile("김..")
kim_result=kim.findall(str(name))
lee_result=lee.findall(str(name))
print("문제1답: 김씨는 %s명, 이씨는 %s명 입니다" %(len(kim_result),len(lee_result)))
#2. 이재영이란 이름이 몇번 반복되나요?
lee1=re.compile("이재영")
lee1_result=lee1.findall(str(name))
print("문제2답: %s명" %len(lee1_result))
#3.중복을 제거한 이름을 출력하세요
one_name = test(name)
print("문제3답: %s" %one_name)
#4.중복을 제거한 이름을 오름차순으로 정렬하여 출력하세요.
print("문제4답: %s" %sorted(one_name)) #sorted(interable)함수는 입력값을 정렬할 후 그 결과를 리스트로 돌려주는 함수이다. one_name.sort()로 쓸수도 있는데 이는 정렬할 데이터가 one_name이란 변수로 다시 저장되는것이다. 따라서 print문으로 one_name을 찍어야된다.
#즉 차이점은 sorted함수를 사용하면 정렬해서 결과를 출력해주고 변수자체는 그대로 정려려이 안된상태로 있으며, list.sort()는 변수 자체를 정렬해주는 함수이다.
var names = '이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌';
var name_list = names.split(',');
var kims = 0;
var lees = 0;
var jys = 0;
for(var i of name_list){
if(i.match('김')){
kims ++;
}
if(i.match('이')){
lees++;
}
if(i.match("이재영")){
jys++;
}
}
var noDup = Array.from(new Set(name_list));
console.log(kims);
console.log(lees);
console.log(jys);
console.log(noDup);
console.log(noDup.sort());
names=['이유덕','이재영','권종표','이재영','박민호','강상희','이재영','김지완','최승혁','이성연','박영서','박민호','전경헌','송정환','김재성','이유덕','전경헌']
print ('주어진 문자열 : ', names)
print()
lee, kim, ljy=0,0,0
for i in range(len(names)):
if names[i][0]=='이':
lee+=1
elif names[i][0]=='김':
kim+=1
if names[i]=='이재영':
ljy+=1
print('1. 김씨 :',kim,'명, 이씨 :', lee,'명 입니다')
print('2. 이재영은',ljy,'명입니다')
i=0
while (i<len(names)):
# print (names[i])
j=0
while (j<len(names)):
if names[i]==names[j] and i!=j:
del names[j]
j-=1
break
j+=1
i+=1
if i>=len(names):
break
print ('3. 중복제거 : ', names)
names.sort()
print ('4. 오름차순 정렬 : ', names)
name = '이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌'
list_name = name.split(',')
print(list_name)
count_k = 0
count_l = 0
count_ljl = 0
for i in list_name :
if i[0] == '김' :
count_k += 1
if i[0] == '이' :
count_l += 1
if i == "이재영" :
count_ljl += 1
print("성이 김씨인 사람은 ", count_k, "명 입니다.")
print("성이 이씨인 사람은 ", count_l, "명 입니다.")
print("'이재영' 이름은 ", count_ljl, '번 반복됩니다.')
set_name = set(list_name)
print("중복제거 이름 : ", set_name)
sort_name = sorted(set_name, reverse = False)
print("오름차순 정렬 : ", sort_name)
String nm = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌";
String[] name = nm.split(",");
for (int i=0; i< name.length; i++)
System.out.println(name[i]);
ArrayList<String> array = new ArrayList<>();
System.out.println("1. 김씨와 이씨는 각각 몇 명 인가요?");
int kim=0; int lee=0;
for (int i=0; i< name.length; i++)
if(name[i].startsWith("김"))
kim++;
for (int i=0; i< name.length; i++)
if(name[i].startsWith("이"))
lee++;
System.out.println("김씨: "+kim+", 이씨: "+lee);
System.out.println("2. 이재영이란 이름이 몇 번 반복되나요?");
int ljy=0;
for (int i=0; i< name.length; i++)
if(name[i].startsWith("이재영"))
ljy++;
System.out.println(ljy);
System.out.println("3. 중복을 제거한 이름을 출력하세요.");
for (int i=0; i< name.length; i++)
if(!array.contains(name[i]))
array.add(name[i]);
System.out.println(array);
System.out.println("4. 중복을 제거한 이름을 오름차순으로 정렬하여 출력하세요.");
Collections.sort(array);
System.out.println(array);
정규표현식 이런거 잘 몰라서 의식의 흐름대로 작성하였습니다
s = '이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌'
# 리스트로 구분
s= s.split(',')
# 1. 김씨와 이씨의 각각 몇명인가
kim_cnt = 0
lee_cnt = 0
for i in range(len(s)):
if s[i].startswith('김'):
kim_cnt += 1
if s[i].startswith('이'):
lee_cnt += 1
print('김씨: {}명, 이씨: {}명'.format(kim_cnt, lee_cnt))
# 2. 이재영이란 이름이 나오는 횟수
print('이재영이란 이름이 나오는 횟수: ', s.count('이재영'))
# 3. 중복 제거한 이름
print('중복 제거한 이름 명단: ', list(set(s)))
# 4. 중복제거 후 오름차순으로 정렬후 출력
s_sort = list(set(s))
s_sort.sort()
print('중복 제거후 정렬한 명단', s_sort)
li=['이유덕','이재영','권종표','이재영','박민호','강상희','이재영','김지완','최승혁','이성연','박영서','박민호','전경헌','송정환','김재성','이유덕','전경헌']
b=li.count('이재영')
li2=list(set(li))
print(li)
print('이재영 몇번 나오냐 ? :',b)
print()
print('이것은 중복제거 리스트 :')
print(li2)
print()
print('가나다 소팅하면 :')
li2.sort()
print(li2)
cnt1=0
cnt2=0
for n in range(len(li)):
if li[n][0]=='이':
cnt1=cnt1+1
elif li[n][0]=='김':
cnt2=cnt2+1
print()
print('이씨는 : ',cnt1)
print('김씨는 : ',cnt2)
list_temp=['이유덕','이재영','권종표','이재영','박민호','강상희','이재영','김지완','최승혁','이성연','박영서',
'박민호','전경헌','송정환','김재성','이유덕','전경헌']
#4-1) 주어진 문자열 중에서 김씨와 이씨가 몇 명인지 골라내기
count_kim=0
count_lee=0
for i in range(0,len(list_temp)) :
for j in range(0,len(list_temp[0])):
if list_temp[i][j]=='김':
count_kim+=1
elif list_temp[i][j]=='이':
count_lee+=1
print(count_kim)
print(count_lee)
#4-2) "이재영"이라는 이름이 몇 번 반복되는지 확인
#4-3) 중복되는 "이재영" 제거하기
temp='이재영'
total_leejaeyoung = 0
for i in list_temp:
if i==temp and total_leejaeyoung==0 :
total_leejaeyoung+=1
elif total_leejaeyoung==1 and i==temp:
list_temp.remove(i)
#4-4) 중복을 제거한 이름을 오름차순으로 정렬하기
print(sorted(list_temp))
파이선 풀이입니다.
stringData="이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌"
strList=stringData.split(",")
kimCount=0
leeCount=0
leeJaYongCount=0
for data in strList:
charData=list(data)
if "김" in charData:
kimCount+=1
elif "이" in charData:
leeCount+=1
if "이재영" in data:
leeJaYongCount+=1
removeDupleList=list(set(strList))
sortList=removeDupleList
sortList.sort()
print("김씨 수 : {}".format(kimCount))
print("이씨 수 : {}".format(leeCount))
print("중복제거리스트 : ",removeDupleList);
print("정렬리스트 : ",sortList);
list_name=["이유덕","이재영","권종표","이재영","박민호","강상희","이재영","김지완","최승혁"] kim_person=0 lee_person=0 jae_young=0 list_name2=[] for key in list_name: a=0 if key[0]=='이': lee_person+=1 if key[0]=='김': kim_person+=1 if key=="이재영": jae_young+=1 if not key in list_name2: list_name2.append(key) print("김씨 : {}명\n이씨 : {}명\n이재영씨 : {}명".format(kim_person,lee_person,jae_young)) print(sorted(list_name2))
def names(s):
print('1, 김씨와 이씨는 각각 몇명 인가요?')
names_Lst = s.split(',')
kim = 0
lee = 0
LJY = 0
for i in names_Lst:
if i[0] == '김':
kim += 1
elif i[0] == '이':
lee += 1
print('{}명, {}명'.format(kim, lee), '\n')
print('2, 이재영"이란 이름이 몇 번 반복되나요?')
for i in names_Lst:
if i == '이재영':
LJY += 1
print('{}번'.format(LJY), '\n')
print('3, 중복을 제거한 이름을 출력하세요.')
print(', '.join(list(set(names_Lst))), '\n')
print('4, 중복을 제거한 이름을 오름차순으로 정렬하여 출력하세요')
names_set = list(set(names_Lst))
names_set.sort()
print(', '.join(names_set))
names('이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌')
파이썬
a = '이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌'
b = a.split(",")
j = 0; #김씨
k = 0; #이씨
for i in b:
if i[0] == "김":
j = j + 1
elif i[0] == "이":
k = k + 1
print("김씨는 %d명, 이씨는 %d명" % (j, k))
print("이재영 이름은 %d번 반복" % b.count("이재영"))
c = list(set(b)) # 중복제거
print(c)
d = sorted(c) #오름차순
print(d)
names="이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌"
names_list = names.split(sep=',')
#1
kim = [i for i in names_list if i[0]=="김"]
lee = [i for i in names_list if i[0]=="이"]
print(len(kim), len(lee))
#2
print(names_list.count("이재영"))
#3
print(*set(names_list))
#4
print(*sorted(set(names_list)))
input1 = input("값을 입력하세요.")
input2 = list(range(0,100,4))
result = []
for i in input2:
if input1[i:i+3] != "":
result.append(input1[i:i+3])
countlee = 0
countkim = 0
for i in result:
if "이" in i:
countlee += 1
elif "김" in i:
countkim += 1
result1 = (countlee,countkim)
result2 = result.count("이재영")
result3 = set(result)
result.sort()
result4 = result
print(result1)
print(result2)
print(result3)
print(result4)
import re
namelist = ['이유덕', '이재영', '권종표', '박민호', '강상희', '이재영', '김지완', '최승혁', '이성연', '박영서', '박민호', '전경헌', '송정환', '김재성', '이유덕', '전경헌']
# test 1 김씨와 이씨는 각각 몇 명 인가요?
firstname = re.compile(r'[이|김][가-힣]{0,2}')
test = ",".join(namelist)
count = firstname.findall(test)
print(f'result : {len(count)}')
# test 2 "이재영"이란 이름이 몇 번 반복되나요?
countdict = dict()
for i in namelist:
try:
countdict[i] += 1
except:
countdict[i] = 1
print(countdict['이재영'])
# test 3 중복을 제거한 이름을 출력하세요.
print(set(namelist))
# test 4 중복을 제거한 이름을 오름차순으로 정렬하여 출력하세요.
sortlist = list(set(namelist))
print(sorted(sortlist))
파이썬으로 작성했습니다.
names = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌"
list_name = names.split(",")
#김씨와 이씨는 각각 몇명인가
list_kimNlee = [x for x in list_name if x[0] == "김" or x[0] == "이"]
print(len(list_kimNlee))
#이재영이라는 이름이 몇번 반복되는가?
list_jaeyoungLee = [x for x in list_name if x == "이재영"]
print(len(list_jaeyoungLee))
#중복을 제거한 이름을 출력하라
set_list = list(set(list_name))
print(set_list)
#중복을 제거한 이름을 오름차순으로
set_list.sort()
print(set_list)
import java.util.ArrayList;
import java.util.HashSet;
import java.util.TreeSet;
public class Q24 {
String name = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,"
+"최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌";
String[] splitName;
String[] lastName;
// 문자열 name을 ","를 기준으로 분할해서 splitName 배열로 반환
public String[] splitName() {
return splitName = name.split(",");
}
// 배열 splitName을 hashSet을 이용하여 중복을 제거하고 reName리스트로 반환
public ArrayList<String> reName() {
HashSet<String> hashName = new HashSet<String>();
for (int i = 0; i < splitName.length; i++) {
hashName.add(splitName[i]);
}
ArrayList<String> reName = new ArrayList<String>(hashName);
return reName;
}
// 중복을 제거한 reName 리스트를 TreeSet을 이용하여 오름차순 정렬후 arrNameList 리스트로 반환
public ArrayList<String> arrName(){
TreeSet<String> arrName = new TreeSet<String>(reName());
ArrayList<String> arrNameList = new ArrayList<String>(arrName);
return arrNameList;
}
// splitName에서 "이재영"에 해당하는 배열을 leeJY 리스트에 반환
public int leeJY() {
ArrayList<String> leeJY = new ArrayList<String>();
for (int i = 0; i < splitName.length; i++) {
if ((splitName[i].toString()).equals("이재영")) {
leeJY.add(splitName[i]);
}
}
return leeJY.size();
}
// reName 리스트를 lastName 배열로 반환
public String[] lastName() {
String[] lastName = new String[reName().size()];
for (int i = 0; i < reName().size(); i++) {
lastName[i] = reName().get(i);
}
return this.lastName = lastName;
}
// lastName 배열의 첫글자가 "김"이면, kim 리스트에 반환
public int lastNameKim() {
ArrayList<String> kim = new ArrayList<String>();
for (int i = 0; i < lastName.length; i++) {
if (lastName[i].substring(0, 1).equals("김")) {
kim.add(lastName[i].substring(0, 1));
}
}
return kim.size();
}
// lastName 배열의 첫글자가 "이"이면, lee 리스트에 반환
public int lastNameLee() {
ArrayList<String> lee = new ArrayList<String>();
for (int i = 0; i < lastName.length; i++) {
if (lastName[i].substring(0, 1).equals("이")) {
lee.add(lastName[i].substring(0, 1));
}
}
return lee.size();
}
// 각 메서드를 생성자에서 실행
public Q24() {
splitName();
reName();
leeJY();
lastName();
lastNameKim();
lastNameLee();
}
public static void main(String[] args) throws Exception {
Q24 q24 = new Q24();
System.out.println("김씨는 총 " + q24.lastNameKim() + "명");
System.out.println("이씨는 총 " + q24.lastNameLee() + "명");
System.out.println("이재영은 총 "+ q24.leeJY() + "번 반복");
System.out.println("중복을 제거한 이름 : "+q24.reName());
System.out.println("중복을 제거하고 정렬한 이름 : "+q24.arrName());
}
}
java
string = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌"
string_list = string.split(",")
#1
num_kim = sum(map(lambda x: x[0] == "김", string_list))
num_lee = sum(map(lambda x: x[0] == "이", string_list))
#2
count = string_list.count("이재영")
#3
for name in set(string_list):
print(name)
#4
for name in sorted(list(set(string_list))):
print(name)
#1
list = ['이유덕','이재영','권종표','이재영','박민호','강상희','이재영','김지완','최승혁','이성연','박영서','박민호','전경헌','송정환','김재성','이유덕','전경헌']
cnt_l = 0
cnt_k = 0
i = 0
while i < len(list):
if list[i][0] == '이':
cnt_l += 1
i += 1
elif list[i][0] == '김':
cnt_k += 1
i += 1
else:
i += 1
print(cnt_l)
print(cnt_k)
#2
list = ['이유덕','이재영','권종표','이재영','박민호','강상희','이재영','김지완','최승혁','이성연','박영서','박민호','전경헌','송정환','김재성','이유덕','전경헌']
cnt_leejae = 0
i = 0
while i < len(list):
if list[i] == '이재영':
cnt_leejae += 1
i += 1
else:
i += 1
print(cnt_leejae)
#3
list = ['이유덕','이재영','권종표','이재영','박민호','강상희','이재영','김지완','최승혁','이성연','박영서','박민호','전경헌','송정환','김재성','이유덕','전경헌']
print(set(list))
#4
list = ['이유덕','이재영','권종표','이재영','박민호','강상희','이재영','김지완','최승혁','이성연','박영서','박민호','전경헌','송정환','김재성','이유덕','전경헌']
list_set = set(list)
list_set_sort = sorted(list_set)
print(list_set_sort)
# 리스트로 분리
a = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌".split(",")
# 성씨만 추출
b = [i[0] for i in a]
# 1번 문제 출력
print("김씨는 {0}명, 이씨는 {1}명".format(b.count("김"), b.count("이")))
# 2번 문제 출력
print("이재영이란 이름은 {0}번 반복 되었다.".format(a.count("이재영")))
# set으로 중복 제거
c = list(set(a))
# 3번 문제 출력
print(c)
# 4번 문제 출력
c.sort()
print(c)
'''
김씨는 2명, 이씨는 6명
이재영이란 이름은 3번 반복 되었다.
['권종표', '송정환', '이성연', '강상희', '박민호', '이재영', '박영서', '최승혁', '김재성', '김지완', '전경헌', '이유덕']
['강상희', '권종표', '김재성', '김지완', '박민호', '박영서', '송정환', '이성연', '이유덕', '이재영', '전경헌', '최승혁']
'''
names = ["이유덕","이재영","권종표","이재영","박민호","강상희","이재영","김지완","최승혁","이성연","박영서","박민호","전경헌","송정환","김재성","이유덕","전경헌"]
##내가 쓴 정답
#(1)
a = 0
for name in names:
if "이" in name:
a += 1
print("이씨 성을 가진 사람은 {}명 입니다.".format(a))
b = 0
for name in names:
if "김" in name:
b += 1
print("김씨 성을 가진 사람은 {}명 입니다.".format(b))
#(2)
print(names.count("이재영"))
#(3)
non_overlap_names = []
for name in names:
if name not in non_overlap_names:
non_overlap_names.append(name)
print(non_overlap_names)
#(4)
non_overlap_names.sort()
print(non_overlap_names)
코드가 길어졌네요 ㅎㅎ
name1 = '이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌'.split(",")
a = []
for i in name1:
a.append(i[0])
print('1. 김씨: {}\n 이씨:{}'.format(a.count("김"), a.count("이")))
print('2. 이재영: {}'.format(name1.count("이재영")))
print('3. {}'.format(list(set(name1))))
name2 = list(set(name1))
name2.sort()
print("4. {}".format(name2))
#파이썬
givenNames = '''
이유덕,이재영,권종표,이재영,박민호,강상희,
이재영,김지완,최승혁,이성연,박영서,박민호,
전경헌,송정환,김재성,이유덕,전경헌'''
givenNames = givenNames.split(',') #,기준으로 이름 분리
####
for i in range(len(givenNames)):
givenNames[i] = givenNames[i].strip() #줄바꿈 문자 제거
####
Kim = 0
Lee = 0
LJY = 0
for i in givenNames:
word = list(i)
if(word[0] == '김'): ## 김씨의 수 카운트
Kim+=1
elif(word[0] == '이'):## 이씨의 수 카운트
Lee+=1
if(i == '이재영'):
LJY += 1
print(f'김씨 : {Kim} 이씨: {Lee}') #김씨| 이씨의 수
print(f'이재영 : {LJY}') #이재영 이름의 수
print(' '.join((set(givenNames)))) #set을 통해 중복 제거
print(' '.join(sorted(set(givenNames))))#정렬한 뒤 set통해 중복 제
ori = '이유덕','이재영','권종표','이재영','박민호','강상희','이재영','김지완','최승혁','이성연','박영서','박민호','전경헌','송정환','김재성','이유덕','전경헌'
a = '이유덕','이재영','권종표','이재영','박민호','강상희','이재영','김지완','최승혁','이성연','박영서','박민호','전경헌','송정환','김재성','이유덕','전경헌'.split(',')
b = [i[0] for i in a]
print("김: {}\n이: {}\n".format(b.count("김"), b.count("이")))
print(a.count("이재영"))
b = list(set(ori))
b
b.sort()
b
#name.py
name_list = ['이유덕','이재영','권종표','이재영','박민호','강상희','이재영','김지완','최승혁','이성연','박영서','박민호','전경헌','송정환','김재성','이유덕','전경헌']
name_set = set(name_list)
num_of_kim = 0
num_of_lee = 0
for name in name_list:
if(name[:1]=='김'):
num_of_kim+=1
elif(name[:1]=='이'):
num_of_lee+=1
print("1. 김씨 : %d명, 이씨 : %d명" %(num_of_kim,num_of_lee))
print("2. \"이재영\"이란 이름은 %d번 반복됩니다."%name_list.count('이재영'))
print("3. %s"%','.join(name_set))
data = list(name_set)
data.sort()
print("4. %s"%','.join(data))
'''
1. 김씨 : 2명, 이씨 : 6명
2. "이재영"이란 이름은 3번 반복됩니다.
3. 최승혁,이성연,권종표,김지완,박영서,전경헌,이유덕,송정환,김재성,박민호,강상희,이재영
4. 강상희,권종표,김재성,김지완,박민호,박영서,송정환,이성연,이유덕,이재영,전경헌,최승혁
'''
파이썬3입니다.
nl = '이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌'.split(',')
print(nl)
fn = [i[0] for i in nl]
k = fn.count('김')
l = fn.count('이')
ljy = nl.count('이재영')
un = list(set(nl))
sun = sorted(un)
print(f'1. 김씨는 {k}명이고 이씨는 {l}명입니다.')
print(f'2. 이재영은 {ljy}명입니다.')
print(f'3. 중복되지 않는 이름 목록 = {un}')
print(f'4. 중복되지 않는 이름 오름차순 정렬 = {sun}')
package codingdojang;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class example004_사이냅소프트면접문제 {
public static void main(String[] args) {
// TODO Auto-generated method stub
String inputName="이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌";
String[] name = inputName.split(",");
for (int i = 0; i < name.length; i++) {
System.out.print(name[i]);
}
System.out.println();
System.out.println("1.김씨와 이씨는 각각 몇명일까요?");
int kimNum =0, leeNum=0;
for (int i = 0; i < name.length; i++) {
String firstName="";
firstName = name[i].substring(0, 1);
if(firstName.equals("김")) {
kimNum++;
}else if(firstName.equals("이")) {
leeNum++;
}
}
System.out.println("김씨는"+kimNum+"명이고,이씨는"+leeNum+"명입니다.");
System.out.println("2. '이재영' 이란 이름이 몇 번 반복되나요?");
int leejaeyoungNum = 0;
for (int i = 0; i < name.length; i++) {
if(name[i].equals("이재영")) {
leejaeyoungNum++;
}
}
System.out.println("이재영 이란 이름은 총"+leejaeyoungNum+"번 반복 되었씁니다.");
System.out.println("중복을 제거한 이름을 출력하세요.");
Set<String> set = new HashSet<String>();
for(String i : name)
set.add(i);
List<String> list = new ArrayList<String>(set);
for(String i : list)
System.out.print(i+" ");
System.out.println();
System.out.println("중복을 제거한 이름입니다.");
Collections.sort(list);
System.out.println("중복을 제거한 이름을 오름차순으로 정렬하여 출력하세요.");
for(String i : list)
System.out.print(i+" ");
}
}
x_name = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서," \
"박민호,전경헌,송정환,김재성,이유덕,전경헌".split(',')
print(len(x_name))
# 문제 1번 : 김씨와 이씨는 각각 몇 명인가요?
kim =[ idx for idx in range(0,17) if x_name[idx][0] == "김"]
lee =[ idx for idx in range(0,17) if x_name[idx][0] =="이"]
print(len(kim))
print(len(lee))
# 문제 2번 : "이재영: 이란 이름은 몇 번 반복되나요?
print(x_name.count("이재영"))
# 문제 3번 : 중복을 제거한 이름을 출력하세요.
s1 = set(x_name)
print(s1)
# 문제 4번 : 중복을 제거한 이름을 오름차순으로 정렬하여 출력하세요.
x_name.sort()
print(x_name)
names = '''이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌'''
names = names.split(',')
# 1. 김씨와 이씨는 각각 몇 명 인가요?
kim = 0
lee = 0
for name in names:
if name[0] == '이':
lee = lee + 1
elif name[0] == '김':
kim = kim + 1
print('김씨:%d 이씨:%d' % (kim, lee))
# 2. "이재영"이란 이름이 몇 번 반복되나요?
count = 0
for name in names:
if name == '이재영':
count = count + 1
print (count)
# 3. 중복을 제거한 이름을 출력하세요.
print (set(names))
# 4. 중복을 제거한 이름을 오름차순으로 정렬하여 출력하세요.
ordered = list(set(names))
ordered.sort()
print(ordered)
김씨:2 이씨:6 3 {'이성연', '송정환', '강상희', '김지완', '이유덕', '전경헌', '최승혁', '박영서', '이재영', '김재성', '권종표', '박민호'} ['강상희', '권종표', '김재성', '김지완', '박민호', '박영서', '송정환', '이성연', '이유덕', '이재영', '전경헌', '최승혁']
배운거: string.startsWith() array_list.contains()
import java.util.ArrayList;
import java.util.Scanner;
public class main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int kim = 0;
int lee = 0;
int leeGY=0;
System.out.println("입력 스타트~");
String text = scan.next();
String[] name =text.split(",");
ArrayList<String> name_list = new ArrayList<String>();
for(int i=0;i<name.length;i++)
{
if(name[i].startsWith("김"))
kim++;
else if(name[i].startsWith("이"))
lee++;
if(name[i].equals("이재영"))
leeGY++;
if(!name_list.contains(name[i]))
name_list.add(name[i]);
}
System.out.println("김씨는: "+ kim+"명");
System.out.println("이씨는: "+ lee+"명");
System.out.println("이재영씨는 "+ leeGY+"번 반복되었다");
System.out.println("중복된 이름 지운 결과물!!");
for(int i=0;i<name_list.size();i++)
System.out.print(name_list.get(i)+ " ");
}
}
public static int numLastName(String str, String...lastName) {
int result =0;
for(String temp: str.split(",")) {
if(temp.startsWith(lastName[0]) || temp.startsWith(lastName[1])) {
result++;
}
}
return result;
}
public static int numName(String str,String name) {
int result =0;
for(String temp:str.split(",")) {
if(temp.equals(name)) {
result ++;
}
}
return result;
}
public static ArrayList<String> dispNoDupli(String str) {
String[] arr = str.split(",");
ArrayList<String> list =new ArrayList<String>(Arrays.asList(arr));
for(int i=0;i<arr.length-1;i++) {
for(int j=i+1;j<arr.length;j++) {
if(arr[i].equals(arr[j])) {
list.remove(arr[j]);
}
}
}
return list;
}
public static void main(String[] args) {
String str = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌";
System.out.println(numLastName(str,"김","이"));
System.out.println("이재영은 ? " + numName(str,"이재영"));
ArrayList<String> noDupli = dispNoDupli(str);
System.out.println("정렬전 : "+ noDupli);
Collections.sort(noDupli);
System.out.println("정렬후 : "+ noDupli);
}
a='이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌'.split(',')
print("1. "+ str(sum([x[0].count('김') for x in a]))+"명")
print("2. "+ str(sum([x[0].count('이') for x in a]))+"명")
print("3. "+str(set(a)))
L=list(set(a))
L.sort()
print("4. "+str(L))
names = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌"
# 1
lee_count = 0
kim_count = 0
for i in names.split(',') :
lee = i.count('이')
if lee == 1 :
lee_count += lee
kim = i.count('김')
if kim == 1 :
kim_count += kim
print("김씨:",kim_count)
print("이씨:",lee_count)
# 2
count_LJY = names.count('이재영')
print("이재영:",count_LJY)
# 3
list_names = list(names.split(','))
Del_name = list(set(list_names))
print("중복 제거:",Del_name)
# 4
Del_name.sort()
print("오름차순:",Del_name)
names = ['이유덕','이재영','권종표','이재영','박민호','강상희','이재영','김지완','최승혁','이성연','박영서','박민호','전경헌','송정환','김재성','이유덕','전경헌']
count_kim=0
count_lee=0
for i in names:
if i[0] == "김":
count_kim+=1
elif i[0] == "이":
count_lee+=1
print("김씨는 ",count_kim, "명, 이씨는 ", count_lee, "명")
count_ljy=0
for i in names:
if i == "이재영":
count_ljy+=1
print("이재영은 ",count_ljy, "번 반복")
unique_names = list(set(names))
print(unique_names)
unique_names.sort()
print(unique_names)
import java.util.*;
public class nameCheck {
public static void main(String[] args) {
String chN = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁"
+",이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌";
Set<String> set = new TreeSet<String>();
String [] array = chN.split(",");
int lee=0,kim =0,jayo=0;
for(int i = 0 ; i < array.length ; ++i) {
if(array[i].indexOf('이') != -1) {
lee++;
}
else if(array[i].indexOf('김') != -1) {
kim++;
}
if(array[i].equals("이재영")) {
jayo++;
}
set.add(array[i]);
}
System.out.println("이 : " + lee);
System.out.println("김 : " + kim);
System.out.println("이재영 : " + jayo);
Iterator<String> it = set.iterator();
while(it.hasNext()) {
System.out.print(it.next()+ " ");
}
}
}
#24 사이냅소프트 면접문제
prob = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌"
# 1. 김씨와 이씨는 각각 몇 명 인가요?
kim_number = 0
lee_number = 0
name_list = prob.split(',')
for name in name_list:
if name[0] == "김":
kim_number += 1
elif name[0] == "이":
lee_number += 1
else:
continue
print("1. 김씨 성을 가진 사람의 수는",kim_number,"명 이다.")
print("1. 이씨 성을 가진 사람의 수는",lee_number,"명 이다.")
# 2. "이재영"이란 이름이 몇 번 반복되나요?
leejaeyoung_number = 0
for name in name_list:
if name == "이재영":
leejaeyoung_number += 1
print("2. 이재영이라는 이름은",leejaeyoung_number,"번 반복됩니다.")
# 3. 중복을 제거한 이름을 출력하세요.
print("3. 중복을 제거한 이름을 출력하면 다음과 같습니다.")
print(" ".join(list(set(name_list))))
# 4. 중복을 제거한 이름을 오름차순으로 정렬하여 출력하세요.
new_list = list(set(name_list))
new_list.sort()
print("4. 중복을 제거한 이름을 오름차순으로 정렬하면 다음과 같습니다.")
print(" ".join(new_list))
가장 핵심은 주어진 문자열을 쉼표를 기준으로 구분되는 리스트로 만드는 것입니다. split을 이용하였습니다.
names = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌"
list_names = names.split(",")
print("이름 리스트 : {}".format(names))
print("구분된 이름 : {}".format(list_names))
print("")
# 김씨와 이씨는 각각 몇 명 인가요?
print("1. 김씨와 이씨는 각각 몇 명인가요?")
i = 0
lee = 0
kim = 0
while i < len(list_names):
if list_names[i][0] == "이":
lee += 1
elif list_names[i][0] == "김":
kim += 1
else:
pass
i += 1
print("==> 김씨는 {}명, 이씨는 {}".format(kim, lee))
print("")
# "이재영"이란 이름이 몇 번 반복되나요?
print('2. "이재영"이란 이름이 몇 번 반복되나요?')
print("==> {}번 반복됨".format(list_names.count("이재영")))
print("")
# 중복을 제거한 이름을 출력하세요.
print("3. 증복을 제거한 이름을 출력하세요")
new_list_names = []
for l in list_names:
if l not in new_list_names:
new_list_names.append(l)
print("==> {}".format(new_list_names))
print("")
# 중복을 제거한 이름을 오름차순으로 정렬하여 출력하세요.
print("4. 중복을 제거한 이름을 오름차순으로 정렬")
new_list_names.sort()
print("==> {}".format(new_list_names))
name_list = '이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌'
name_list = name_list.split(',')
result_kim = 0
result_lee = 0
for name in name_list:
if name[0] == '김':
result_kim += 1
elif name[0] == '이':
result_lee += 1
print(result_lee)
print(result_kim)
result = 0
for name in name_list:
if name == '이재영':
result += 1
print(result)
print(set(name_list))
print(sorted(list(set(name_list))))
names = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌" nameArray = names.split(',')
#1. 김씨와 이씨는 각각 몇 명인가요?
kim = 0 lee = 0 for i in nameArray: if i[0] == '김': kim += 1 elif i[0] == '이': lee += 1
print("김씨: " + str(kim) + "명, 이씨: " + str(lee) + "명")
#2. 이재영이란 이름이 몇 번 반복되나요?
LJY = 0 for i in nameArray: if i == "이재영": LJY += 1
print("\"이재영\"이란 이름은 " + str(LJY) + "번 반복됩니다.")
#3. 중복을 제거한 이름을 출력하세요.
newArray = [""] chk = 0 for i in nameArray: for j in newArray: if i == j: chk = 1 break else: chk = 0 if chk == 0: newArray.append(i)
del newArray[0]
print(newArray)
#4. 중복을 제거한 이름을 오름차순으로 정렬하여 출력하세요.
newArray.sort() print(newArray)
# Q92203 사이냅소프트 면접문제
# 명단
list_names=['이유덕','이재영','권종표','이재영','박민호','강상희','이재영','김지완','최승혁','이성연','박영서','박민호','전경헌','송정환','김재성','이유덕','전경헌']
# 결과 변수
count_kim=0
count_lee=0
count_ljy=0
uniq_names=[]
uniq_names_sorted=[]
# 1. 김씨와 이씨는 각각 몇 명 인가요?
for name in list_names:
if name[0]=='김':
count_kim+=1
elif name[0]=='이':
count_lee+=1
print("김씨는" + str(count_kim) + "명 입니다.")
print("이씨는" + str(count_lee) + "명 입니다.")
#2. "이재영"이란 이름은 몇 번 반복되나요?
for name in list_names:
if name == "이재영":
count_ljy+=1
print('"이재영"은 ' + str(count_ljy) + "번 반복됩니다.")
#3. 중복을 제거한 이름을 출력하세요
temp=set(list_names)
uniq_names=list(temp)
print(uniq_names)
#4. 중복을 제거한 이름을 오름차순으로 정렬하여 출력하세요.
uniq_names_sorted=sorted(uniq_names)
print(uniq_names_sorted)
data = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완\
,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌"
names = data.split(",")
# 1
a = [x[0] for x in names]
print(a.count("이"), a.count("김"))
# 2
print(names.count("이재영"))
# 3
names2 = list(set(names))
print(','.join(names2))
# 4
names2.sort()
print(','.join(names2))
s='이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌'
names=s.split(',')
kim_cnt=0 lee_cnt=0 for i in range(len(names)):
if names[i][0]=='김':
kim_cnt +=1
elif names[i][0]=='이':
lee_cnt +=1
print('김씨:',kim_cnt,'명')
print('이씨:',lee_cnt,'명')
print(set(names))
print(names.sort())
import java.util.*;
public class test4 {
public static void main(String[] args) {
String name_list = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌";
name_list = name_list + "/";
ArrayList<String> name_arraylist = new ArrayList<>(); // 이름을 추가할 배열 선언
int idx = 0; // 인덱스 변수 선언
String name_idx = "";
while(true) {
if(name_list.charAt(idx) == ',') { // 이름을 추가
name_arraylist.add(name_idx);
name_idx = "";
}else if (name_list.charAt(idx) == '/') { // 마지막 이름 추가
name_arraylist.add(name_idx);
break;
}else { // 이름에 철자 추가
name_idx += name_list.charAt(idx);
}
idx++;
}
System.out.println("1번 문제");
int kim_num = 0;
int lee_num = 0;
for(String name : name_arraylist) {
if(name.charAt(0) == '김') {
kim_num++;
} else if(name.charAt(0) == '이') {
lee_num++;
}
}
System.out.println("김씨 : "+ kim_num+"명");
System.out.println("이씨 : "+ lee_num+"명");
System.out.println("");
System.out.println("2번 문제");
int lee_jae_yeong_num = 0;
for(String name : name_arraylist) {
if(name.equals("이재영")) {
lee_jae_yeong_num++;
}
}
System.out.println("이재영 : "+ lee_jae_yeong_num+"명");
System.out.println("");
System.out.println("3번 문제");
ArrayList<String> name_arraylist_without_duplicate = new ArrayList<>();
for(int a = 0; a < name_arraylist.size(); a++) {
if(!name_arraylist_without_duplicate.contains(name_arraylist.get(a))) {
name_arraylist_without_duplicate.add(name_arraylist.get(a));
}
}
for(String name : name_arraylist_without_duplicate) {
System.out.print(name+",");
}
System.out.println("");
System.out.println("4번 문제");
Collections.sort(name_arraylist_without_duplicate);
for(String name : name_arraylist_without_duplicate) {
System.out.print(name+",");
}
}
}
4번문제 오름차순이 맞을까요 저게
names="이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌".split(",")
cnt=0
cnt1=0
cnt2=0
for i in names:
if i[0]=='김':
cnt+=1
if i[0]=='이':
cnt1+=1
if i=='이재영':
cnt2+=1
print(set(names))
print(sorted(set(names)))
print(cnt,cnt1,cnt2)
names = ('이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌').split(',')
a = '이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌'
j = a.count('김')
k = a.count('이')
print('김씨 : ', j , '\n이씨 : ', k)
#이재영
for i in names:
p = names.count('이재영')
print('이재영이라는 이름이 몇 번 반복되나요? : ', p ,'번 반복됩니다.')
#중복제거
b = list(set(names))
print(b)
#오름차순
b.sort()
print(b)
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Find {
String data = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌";
String[] names = data.split(",");
//1. 김씨와 이씨는 각각 몇 명인가요?
void find() {
int countLee=0;
int countKim=0;
for(int i=0;i<names.length;i++) {
String lastName = names[i].substring(0,1);
if("이".equals(lastName)) countLee++;
if("김".equals(lastName)) countKim++;
}
System.out.println("김씨 : "+countKim);
System.out.println("이씨 : "+countLee);
}
//"이재영"이란 이름이 몇 번 반복되는가?
void fineLee() {
int count = 0;
for(int i=0;i<names.length;i++) {
if("이재영".equals(names[i])) count++;
}
System.out.println("'이재영'이란 이름이 반복 되는 횟수 : "+count);
}
//중복을 제거한 이름을 출력
void removeDup() {
//list이용
List<String> namelist = new ArrayList<String>();
for(String n : names) {
if(!namelist.contains(n)) namelist.add(n);
}
for(int i=0; i<namelist.size();i++) {
System.out.print(namelist.get(i));
if(i != namelist.size()-1) System.out.print(", ");
}
System.out.println();
}
//중복을 제거한 이름을 오름차순으로 정렬하여 출력
void removeDup2() {
List<String> namelist = new ArrayList<String>();
Arrays.sort(names);
for(String n : names) {
if(!namelist.contains(n)) namelist.add(n);
}
for(int i=0; i<namelist.size();i++) {
System.out.print(namelist.get(i));
if(i != namelist.size()-1) System.out.print(", ");
}
}
public static void main(String[] args) {
Find f = new Find();
f.find();
f.fineLee();
f.removeDup();
f.removeDup2();
}
}
using System; using System.Linq; using System.Collections.Generic;
namespace Qna
{
class MainApp
{
public static string User = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌";
public static string[] User_Data = User.Split(',');
int QnA_1()
{
int result_1 = 0;
for (int i = 0; i < User_Data.Length; i++)
{
if(true == User_Data[i].Contains("이") || User_Data[i].Contains("김"))
result_1 += 1;
}
return result_1;
}
int QnA_2()
{
int result_2 = 0;
for (int i = 0; i < User_Data.Length; i++)
{
if (true == User_Data[i].Contains("이재영"))
result_2 += 1;
}
return result_2;
}
string QnA_3()
{
List<string> List_Data = new List<string>();
for (int i = 0; i < User_Data.Length; i++)
List_Data.Add(User_Data[i]);
List_Data = List_Data.Distinct().ToList();
string result_3 = string.Join(",", List_Data.ToArray());
return result_3;
}
string QnA_4()
{
string[] User_List = QnA_3().Split(',');
Array.Sort(User_List);
string result_4 = string.Join(",", User_List.ToArray());
return result_4;
}
static void Main(string[] args)
{
MainApp Start = new MainApp();
Console.WriteLine("1.김씨와 이씨는 각각 몇 명 인가요?");
Console.WriteLine($"정답 : {Start.QnA_1()}명\n");
Console.WriteLine("2.이재영 이란 이름이 몇 번 반복되나요?");
Console.WriteLine($"정답 : {Start.QnA_2()}명\n");
Console.WriteLine("3.중복을 제거한 이름을 출력하세요.");
Console.WriteLine($"정답 : {Start.QnA_3()}\n");
Console.WriteLine("4.중복을 제거한 이름을 오름차순으로 출력하세요.");
Console.WriteLine($"정답 : {Start.QnA_4()}");
}
}
}
name = '이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌'
# 1.
name = name.split(',')
countKim = 0
countLee = 0
for i in name:
if i[0] == '김': countKim += 1
if i[0] == '이': countLee += 1
print('김씨',countKim,'명')
print('이씨',countLee,'명')
# 2.
count = 0
for i in name:
if i == '이재영':
count += 1
print('이재영의 반복 횟수 =', count)
# 3.
s = set(name)
print(s)
# 4.
print(sorted(s))
public static int lastName(String[] names, String last) {
int count = 0;
for(int i = 0; i < names.length; i++) {
if(names[i].startsWith(last)) {
count += 1;
}
}
return count;
}
public static int repeatName(String[] names, String name) {
int count = 0;
for(int i = 0; i < names.length; i++) {
if(names[i].equals(name)) {
count += 1;
}
}
return count;
}
public static List<String> delName(String[] names) {
List<String> list = new ArrayList<>();
for(String name : names) {
if(!list.contains(name)) {
list.add(name);
}
}
return list;
}
public static List<String> sortName(String[] names) {
List<String> list = new ArrayList<>();
for(String name : names) {
if(!list.contains(name)) {
list.add(name);
}
}
Collections.sort(list);
return list;
}
public static void main(String[] args) {
List<String> list = new ArrayList<String>();
String name = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌";
String names[] = name.split(",");
System.out.println(lastName(names, "이"));
System.out.println(lastName(names, "강"));
System.out.println(repeatName(names, "이재영"));
System.out.println(delName(names));
System.out.println(sortName(names));
}
people=['이유덕','이재영','권종표','이재영','박민호','강상희','이재영','김지완','최승혁','이성연','박영서','박민호','전경헌','송정환','김재성','이유덕','전경헌']
kim=0
lee=0
jaeyung=0
names=[]
for x in people:
if x[0]=='김':
kim+=1
if x[0]=='이':
lee+=1
if x=='이재영':
jaeyung+=1
if x in names:
pass
if x not in names:
names.append(x)
sortednames=list(names)
sortednames.sort()
print('김씨:',kim)
print('이씨:',lee)
print('이재영:',jaeyung,'번')
print(names)
print(sortednames)
public class Test {
private static final String NAMES = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌";
public static void main(String[] args) {
solution1(NAMES);
solution2(NAMES);
solution3(NAMES);
solution4(NAMES);
}
public static void solution1(String str) {
String name = "";
StringTokenizer token = new StringTokenizer(str, ",");
int cnt1 = 0;
int cnt2 = 0;
while (token.hasMoreTokens()) {
name = token.nextToken();
if(name.startsWith("김")) cnt1++;
else if(name.startsWith("이")) cnt2++;
}
System.out.println("1. 김씨와 이씨는 각각 몇 명인가요?"
+ " - 김씨: " + cnt1
+ " - 이씨: " + cnt2);
}
public static void solution2(String str) {
String name = "";
StringTokenizer token = new StringTokenizer(str, ",");
int cnt = 0;
while (token.hasMoreTokens()) {
name = token.nextToken();
if(name.equals("이재영")) cnt++;
}
System.out.println("2. '이재영'이란 이름이 몇 번 반복되나요? " + cnt);
}
public static void solution3(String str) {
String name = "";
StringTokenizer token = new StringTokenizer(str, ",");
ArrayList<String> arrlist = new ArrayList<String>();
while (token.hasMoreTokens()) {
name = token.nextToken();
arrlist.add(name);
}
arrlist = new ArrayList<String>(new LinkedHashSet<String>(arrlist));
System.out.println("3. 중복을 제거한 이름을 출력하세요.");
for (int idx = 0; idx < arrlist.size(); idx++) {
System.out.print(idx == 0 ? arrlist.get(idx) : ", " + arrlist.get(idx));
}
}
public static void solution4(String str) {
String name = "";
StringTokenizer token = new StringTokenizer(str, ",");
ArrayList<String> arrlist = new ArrayList<String>();
while (token.hasMoreTokens()) {
name = token.nextToken();
arrlist.add(name);
}
arrlist = new ArrayList<String>(new LinkedHashSet<String>(arrlist));
Collections.sort(arrlist);
System.out.println("\n4. 중복을 제거한 이름을 오름차순으로 정렬하여 출력하세요.");
for (int idx = 0; idx < arrlist.size(); idx++) {
System.out.print(idx == 0 ? arrlist.get(idx) : ", " + arrlist.get(idx));
}
}
}
``````{.python}
name = '이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌'
list = name.split(',')
#1
a=0
b=0
for i in range(len(list)) :
if list[i].startswith('김') == True :
a += 1
elif list[i].startswith('이') == True :
b += 1
#2
list.count('이재영')
#3
new_list = []
for j in range(len(list)) :
if list[j] not in new_list :
new_list.append(list[j])
#4
new_list.sort()
# coding=utf-8
import re
data = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌"
# 김씨와 이씨는 각각 몇 명?
kim = len(re.compile('[김..]', re.DOTALL).findall(data))
print("김 씨 = %d명" % kim)
lee = len(re.compile('[이..]', re.DOTALL).findall(data))
print("이 씨 = %d명" % lee)
# "이재영"이라는 이름이 몇 번 반복?
leejaeyoung = len(re.compile('[이][재][영]').findall(data))
print("이재영 이름 몇번? %d" % leejaeyoung)
# 중복을 제거한 이름을 출력
data_list = list(data.split(',')) # 문자열을 ,(쉼표)로 구분해 리스트 생성
del_over = []
try:
for x in range(len(data_list)):
if data_list[x] not in del_over:
del_over.append(data_list[x])
except IndexError as e:
print(e)
print(del_over)
# 중복을 제거한 이름을 오름차순으로 정렬하여 출력
print(sorted(del_over))
class Classifier:
def __init__(self):
self.list = []
self.sumKim = 0
self.sumLee = 0
def makeList(self,name):
self.list = name.split(",")
def makeUnique(self):
c = set(self.list)
self.list = list(c)
self.list.sort()
print(self.list)
def countKim(self):
for i in self.list:
if i[0]=="김":
self.sumKim += 1
return self.sumKim
def countLee(self):
for i in self.list:
if i[0]=="이":
self.sumLee += 1
return self.sumLee
name = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌"
a = Classifier()
a.makeList(name)
a.makeUnique()
print("Sum Kim = ",a.countKim())
print("Sum Lee = ",a.countLee())
파이썬입니다, 2, 3, 4, 1번 문제순으로 풀었어요 1.문제 중복된 이름 제외하고 김씨, 이씨 인원구했습니다.
names = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌"
name_list = names.split(',')
# 2. THE NUMBER OF NAME(이재영) OVERLAPPING.
print("the number of the name(이재영) is: ", name_list.count('이재영'))
# 3. NUMBER LIST OF UNIQUE NAMES.
unique_names = set(name_list)
print('\nUnique names are: ', unique_names)
# 1. THE NUMBER OF NAMES THAT START WITH '김','이'
import re
kim_numbers = re.findall(r'김..', str(unique_names))
lee_numbers = re.findall(r'이..', str(unique_names))
print('\nThe number of Kim',len(kim_numbers))
print('\nThe number of Lee',len(lee_numbers))
names = '이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌'
names = names.split(',')
kim = 0
lee = 0
jaeyoung = 0
for i in range(len(names)):
if names[i][0] == '김':
kim += 1
elif names[i][0] == '이':
lee += 1
if names[i] == '이재영':
jaeyoung += 1
names_overlap = set(names)
names_sorted = sorted(names_overlap)
print("김씨의 수:", kim)
print("이씨의 수:", lee)
print("이재영:", jaeyoung)
print("중복을 제거한 이름: ", names_overlap)
print("중복을 제거하고 오름차순으로 정렬한 이름:", names_sorted)
namelist =["이유덕","이재영","권종표","이재영","박민호","강상희","이재영","김지완","최승혁",
"이성연","박영서","박민호","전경헌","송정환","김재성","이유덕","전경현"]
kim=0
lee=0
leejaeyoung=0
for i in namelist:
str1=str(i)
if str1[0]=="김":
kim+=1
if str1[0]=="이":
lee+=1
if i =="이재영":
leejaeyoung+=1
print(kim,lee,leejaeyoung)
finallist=[]
for k in namelist:
if k not in finallist:
finallist.append(k)
print(finallist)
finallist.sort()
print(finallist)
python 입니다.
line = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌"
'''1. 김씨와 이씨는 각각 몇 명 인가요?'''
def getFirstName(line):
lee = len([item for item in line.split(",") if item[0:1] == "김"])
kim = len([item for item in line.split(",") if item[0:1] == "이"])
print("1. 김씨와 이씨는 각각 몇 명 인가요? 김씨는 {l} 명이고, 이씨는 {k} 명 입니다." .format(l=str(lee), k=str(kim)))
getFirstName(line)
'''2. "이재영"이란 이름이 몇 번 반복되나요? '''
print('2. "이재영"이란 이름이 몇 번 반복되나요? %d번 반복됩니다.' %(line.count("이재영")))
'''3. 중복을 제거한 이름을 출력하세요. '''
print("3. 중복을 제거한 이름을 출력하세요.\n {0}" .format(set(line.split(","))))
'''4. 중복을 제거한 이름을 오름차순으로 정렬하여 출력하세요. '''
l = list(set(line.split(",")))
l.sort()
print("4. 중복을 제거한 이름을 오름차순으로 정렬하여 출력하세요.")
for i in l:
print(i)
names = ["이유덕","이재영","권종표","이재영","박민호","강상희","이재영","김지완","최승혁","이성연","박영서","박민호","전경헌","송정환","김재성","이유덕","전경헌"]
leejaeyoung = 0
yee_len = 0
kim_len = 0
deoverLap = []
for i in names:
if i[0] == "이":
yee_len += 1
elif i[0] == "김":
kim_len += 1
if i == "이재영":
leejaeyoung += 1
if i not in deoverLap:
deoverLap.append(i)
print("이씨 %d, 김씨 %d, 이재영 %d" % (yee_len, kim_len, leejaeyoung))
print(deoverLap)
print(sorted(deoverLap))
aa = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌"
names = aa.split(",")
count_kim = 0
count_lee = 0
count_lee2 = 0
for name in names:
if name[0] == '김':
count_kim += 1
elif name[0] == '이':
count_lee += 1
if name == '이재영':
count_lee2 += 1
print(count_kim,count_lee,count_lee2)
print(list(set(names)))
nnames = list(set(names))
nnames.sort()
print(nnames)
name = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌"
names = name.split(",")
names1 = []
names2 = []
count = 0
for i in names:
if i.startswith("이"):
names1.append(i)
print(i, end=" ")
if i == "이재영":
count = count + 1
if i.startswith("김"):
names2.append(i)
print(i, end=" ")
print("\n이씨: "+ str(len(names1)))
print("김씨: "+ str(len(names2)))
print("2. 이재영 반복회수 : " + str(count))
print("중복 제거 이름: ", end = "")
print(set(names))
names = list(set(names))
print(sorted(names))
name=("이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌")
k=name.split(",")
kim=0
lee=0
leej=0
for i in k:
if i[0]=="김":
kim+=1
if i[0]=="이":
lee+=1
if i=="이재영":
leej+=1
print ("김 씨는 %d명, 이 씨는 %d명입니다\n" %(kim,lee))
print("이재영은 %d회 반복됩니다.\n" %leej)
k=list(set(k))
print ("%s\n"%k)
k.sort()
print(k)
str = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌"
print("1. {0}명".format(str.count("김") + str.count("이")))
str2 = str.split(",")
print("2. {0}번".format(str2.count("이재영")))
for i in str2:
if i not in str2:
str2.append(i)
print("3. {0}".format(str2))
str2.sort()
print("4. {0}".format(str2))
Name_Group=["이유덕","이재영","권종표","이재영","박민호","강상희","이재영","김지완","최승혁","이성연","박영서","박민호","전경헌","송정환","김재성","이유덕","전경헌"]
count_name=0
for i in Name_Group:
if i[0]=="이" or i[0]=="김":
count_name+=1
print ("{0} is exist".format(count_name))
count_lee=0
for i in Name_Group:
if i=="이재영":
count_lee+=1
print ("{0} of 이재영 is come in group".format(count_lee))
ReName_Group=[]
for i in Name_Group:
if i not in ReName_Group:
ReName_Group.append(i)
print(ReName_Group)
ReName_Group.sort()
print(ReName_Group
파이썬 3.7.2 버전입니다.
names = '이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌'
name_list = names.split(',')
# 1
print(f'김씨: {len([x for x in name_list if x.startswith("김")])} 명')
print(f'이씨: {len([x for x in name_list if x.startswith("이")])} 명')
# 2
print(f'{name_list.count("이재영")}번')
# 3
uniqe_name_list = list(set([x for x in name_list if name_list.count(x)>1]))
print(uniqe_name_list)
# 4
print(sorted(uniqe_name_list))
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class pro4 {
// 1.김씨와 이씨는 각각 몇 명 인가요?
// 2."이재영"이란 이름이 몇 번 반복되나요?
// 3.중복을 제거한 이름을 출력하세요.
// 4.중복을 제거한 이름을 오름차순으로 정렬하여 출력하세요.
public static void main(String[] args) {
// TODO Auto-generated method stub
String str = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌";
List<String> name = Arrays.asList(str.split(","));
ArrayList<String> name2 = new ArrayList<>();
int kimnum = 0;
int leenum = 0;
int ljy = 0;
for(String a : name){
if(a.charAt(0)=='이')
leenum ++;
if(a.charAt(0)=='김')
kimnum ++;
if(a.contains("이재영"))
ljy++;
if(!name2.contains(a))
name2.add(a);
}
System.out.println("김씨성은" + kimnum +"명" );
System.out.println("이씨성은" + leenum +"명" );
System.out.println("이재영은" + ljy +"명" );
System.out.println("중복제거하면 " + name2);
Collections.sort(name2);
System.out.println("오름차순 나열 "+name2);
}
}
package main;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
String[] name = {"이유덕","이재영","권종표","이재영","박민호","강상희","이재영","김지완",
"최승혁","이성연","박영서","박민호","전경헌","송정환",
"김재성","이유덕","전경헌"};
String[] overlap = new String[17];
int CntKim = 0;//김씨 이씨 넣을 변수
int CntLee = 0;
int JeoCnt = 0;//이재영 이름 반복 카운트
Main m = new Main();
m.KimLee(name, CntKim, CntLee);
m.Leejeo(overlap, JeoCnt);
m.over(name, overlap);
}
void KimLee(String[] name,int CntKim,int CntLee) {
for (int i = 0; i < name.length; i++) {
if(name[i].charAt(0)== '김') {
CntKim++;
}else if(name[i].charAt(0)== '이') {
CntLee++;
}
}
System.out.println("김씨 이름:"+CntKim);
System.out.println("이씨 이름:"+CntLee);
}
void Leejeo(String[] name,int JeoCnt) {
for (int i = 0; i < name.length; i++) {
if(name[i]=="이재영") {
JeoCnt++;
}
}
System.out.println("이재영 중복 횟수:"+JeoCnt);
}
void over(String[] name,String[] overlap) {
for (int i = 0; i < name.length; i++) {
for (int j = 0; j < name.length; j++) {
if(name[i]==name[j]) {
overlap[i] = name[i];
}
}
}
for (int i = 0; i < overlap.length; i++) {
System.out.print(overlap[i]+" ");
}
}
}
name_list = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌"
name_list_r = name_list.split(',')
print("명단은 다음과 다음과 같습니다")
print(name_list_r)
print("\n")
#1
count_kim = 0
count_lee = 0
for name in name_list_r:
if name[0] == "김":
count_kim += 1
elif name[0] == "이":
count_lee += 1
print("1. 명단에 있는 사람들 중 김씨는 {}명, 이씨는 {}명 입니다.\n".format(count_kim, count_lee))
#2
print("2. '이재영'이라는 이름은 {}번 반복됩니다.\n".format(name_list_r.count("이재영")))
#3
for name in name_list_r:
if name_list_r.count(name) != 1:
name_list_r.remove(name)
print("3. 중복되는 이름을 제거한 명단은 다음과 같습니다\n")
print(name_list_r)
print("\n")
#4
name_list_r.sort()
print("4. 오름차순 정렬 명단은 다음과 같습니다\n")
print(name_list_r)
import re
s = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌".split(",")
p1 = re.compile('^[김]')
p2 = re.compile('^[이]')
p3 = re.compile('이재영')
dic = {'김': 0, '이': 0, '이재영': 0}
for i in s:
if(p1.match(i)): dic['김'] += 1
elif(p2.match(i)): dic['이'] += 1
for i in s:
print(i)
if(p3.match(i)): dic['이재영'] += 1
print("김:%d, 이:%d 이재영:%d" %(dic.get('김'),dic.get('이'),dic.get('이재영')))
a = set(s)
print(a)
print(sorted(a))
역시 파이썬은 편하네여
a='이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌'
a1=a.count('이' or '김')
print(a1)
a2=a.count('이재영')
print(a2)
a3=set(a.split(sep=','))
print(a3)
a4=sorted(list(a3))
print(a4)
#1.김씨, 이씨 인원수
name = '이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌'.split(',')
len([x for x in name if x[0]=='김' or x[0]=='이'])
#2. '이재영' 반복수
len([x for x in name if x=='이재영'])
#3. 중복 제거 이름 출력
print(set(name))
#4. 중복 제거 이름 오름차순 출력
print(sorted(set(name)))
name.count('김')
Python 너무 복잡하게 짠 것 같네요...
a = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌".split(",")
cnt_김 = 0
cnt_이 = 0
cnt_이재영 = 0
for name in a:
if name[0] == "김":
cnt_김 += 1
if name[0] == "이":
cnt_이 += 1
if name == "이재영":
cnt_이재영 += 1
print("김씨는 %d명입니다." % cnt_김)
print("이씨는 %d명입니다." % cnt_이) # 1. 김씨와 이씨는 각각 몇 명 인가요?
print("\"이재영\"이란 이름은 %d번 반복됩니다." % cnt_이재영) # 2. "이재영"이란 이름은 몇 번 반복되나요?
set_names = set(a)
for name in set_names:
print(name, end=" ") # 3. 중복을 제거한 이름을 출력하세요.
up_sorted = sorted(set_names)
for name in up_sorted:
print(name, end=" ") # 4. 중복을 제거한 이름을 오름차순으로 정렬하여 출력하세요.
names = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌"
split_names = names.split(",")
#print(split_names)
kim = 0
lee = 0
for i in range(17):
if((split_names[i])[0] == "김"):
kim+=1
elif((split_names[i])[0] == "이"):
lee+=1
print(f'1. 김씨의 수는 {kim}, 이씨의 수는 {lee}')
jaeyoung_count = 0
for i in range(17):
if(split_names[i].count("이재영") != 0):
jaeyoung_count+=1
print(f'2. 이재영의 수는 {jaeyoung_count}')
print(f'3. {set(split_names)}')
lined_names = sorted(split_names)
print(f'4. {lined_names}')
갓 시작한 초보개발자입니다 ㅜ
public class Test15 {
public static void main(String[] args) {
String str = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌";
ArrayList<String> list = new ArrayList<String>();
String[] strArr = str.split(",");
int kimCount = 0;
int leeCount = 0;
int ljyCount = 0;
for(int i = 0; i<strArr.length; i++) {
if(strArr[i].substring(0,1).equals("김"))
kimCount++;
else if(strArr[i].substring(0,1).equals("이"))
leeCount++;
if(strArr[i].equals("이재영"))
ljyCount++;
}
System.out.println(kimCount + ", " + leeCount);
System.out.println(ljyCount);
for(String name : strArr) {
if(!list.contains(name)) {
list.add(name);
}
}
System.out.println(list);
Collections.sort(list);
System.out.println(list);
}
}
a = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌"
a = a.split(',')
x=0
y=0
for i in a:
if i[0] == "이":
x += 1
elif i[0] == "김":
y += 1
print("김씨는 %d명 이씨는 %d명" %(x,y))
lee = a.count("이재영")
print("이재영은 %d번 반복된다." %lee)
a = list(set(a))
print(a)
a.sort()
print(a)
Python Code 입니다.
list = ["이유덕","이재영","권종표","이재영","박민호","강상희","이재영","김지완","최승혁","이성연","박영서","박민호","전경헌","송정환","김재성","이유덕","전경헌"]
# 김씨와 이씨는 각각 몇 명 인가요?
leecnt = 0
kimcnt = 0
for i in range(len(list)):
if list[i][0] == '이':
leecnt = leecnt +1
if list[i][0] == '김':
kimcnt = kimcnt +1
print("이씨성을 가진 사람은 {0} 명입니다".format(leecnt))
print("김씨성을 가진 사람은 {0} 명입니다".format(kimcnt))
# "이재영"이란 이름이 몇 번 반복되나요?
cnt =0
for i in range(len(list)):
if list[i] == "이재영":
cnt = cnt +1
print("이재영이란 이름은 {0} 번 반복됩니다.".format(cnt))
# 중복을 제거한 이름을 출력하세요.
setlist = set(list)
print(setlist)
# 중복을 제거한 이름을 오름차순으로 정렬하여 출력하세요.
print(sorted(setlist))
names = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌".split(",")
#1
count1 = 0
count2 = 0
for i in names:
a = i[0]
if '김' in a:
count1 += 1
elif '이' in a:
count2 += 1
print("김씨 : ",count1, "명 있습니다")
print("이씨 : ",count2, "명 있습니다")
#2
count3 = 0
for i in names:
if i == '이재영':
count3 += 1
print(count3)
#3
name_dict = {}
for name in names:
if name in name_dict:
name_dict[name] += 1
else:
name_dict[name] = 1
result = set()
for name in name_dict:
if name_dict[name] >= 2:
result.add(name)
result = list(result)
print(result)
#4
result.sort()
print(result)
namelist='이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌'
names=namelist.split(",")
a=[i[0] for i in names]
print(a.count('김'))
print(a.count('이'))
print(names.count('이재영'))
names_set=set(names)
print(list(names_set))
list(names_set).sort()
print(list(names_set))
python 3.9.1입니다.
count 함수를 안썼더니 좀 지저분해졌네요.
names = '이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌'.split(',')
#1
cntKL = [0,0]
for name in names:
if name[0] == '김':
cntKL[0] += 1
elif name[0] == '이':
cntKL[1] += 1
print(cntKL)
#2
cntLJY = 0
for name in names:
if name == '이재영':
cntLJY += 1
print(cntLJY)
#3
noDuplicate = set(names)
print(noDuplicate)
#4
print(sorted(list(noDuplicate)))
name_txt = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌"
name_list = name_txt.split(",")
#1
count_kim = 0
count_lee = 0
for name in name_list:
if name.startswith('김') is True:
count_kim += 1
elif name.startswith('이') is True:
count_lee += 1
print(f"김씨: {count_kim}, 이씨: {count_lee}")
print()
#2
count_ljy = 0
for name in name_list:
if name == "이재영":
count_ljy += 1
print(count_ljy)
print()
#3
name_set = set(name_list)
print(name_set)
print()
#4
name_set_sort = list(name_set)
name_set_sort = sorted(name_set_sort)
print(name_set_sort)
# 리스트로 변환
name_list = '이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌'.split(
",")
# 각각 카운트
name = [i[0] for i in name_list]
print("김씨 : {0}, 이씨 : {1}".format(name.count('김'), name.count('이')))
# 이재영 중복 체크
print("중복 횟수 : ", name_list.count('이재영'))
# 중복 체크
name_list = set(name_list)
print(name_list)
# 오름차순
name_list = sorted(name_list)
print(name_list)
const names =
"이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌"
const namesArray = names.split(",")
/* 김씨와 이씨는 각각 몇 명 인가요? */
let kim = 0
let lee = 0
for (let i = 0; i < namesArray.length; i++) {
if (namesArray[i][0] === "김") {
kim++
} else if (namesArray[i][0] === "이") {
lee++
}
}
console.log(`김씨: ${kim}명, 이씨: ${lee}명`)
/* "이재영"이란 이름이 몇 번 반복되나요? */
let leejaeyoung = 0
//for (let i = 0; i < namesArray.length; i++) {
// if (namesArray[i] === "이재영") {
// leejaeyoung++
// }
//}
namesArray.map((v) => v === "이재영" && leejaeyoung++)
console.log(`이재영: ${leejaeyoung}명`)
/* 중복을 제거한 이름을 출력하세요. */
const result = []
for (let i = 0; i < namesArray.length; i++) {
if (!result.includes(namesArray[i])) {
result.push(namesArray[i])
}
}
console.log(`중복 제거한 이름: ${result}`)
/* 중복을 제거한 이름을 오름차순으로 정렬하여 출력하세요. */
console.log(`중복 제거한 이름 오름차순: ${result.sort()}`)
#왕초보
str1 = input("주어진 문자열:")
list1 = str1.split(",")
#1번문제
kimsum = 0
leesum = 0
for name in list1:
if name[0] == '김':
kimsum += 1
if name[0] == '이':
leesum += 1
print (kimsum, leesum)
#2번문제
n = 0
for i in range(len(list1)):
if list1[i] == '이재영':
n += 1
print(n)
#3번문제
set1 = set(list1)
print(set1)
#4번문제
set1.sort()
print(set1)
names = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌".split(",") #이 표현을쓰면 굳이 직접 ''를 써서이름을 안나눠도된다.
totk = 0
totl = 0
for i in names:
if i[0] == '김':
totk+=1
elif i[0] == '이':
totl+=1
print(totk) #1
print(totl) #1
print(names.count('이재영')) #2
print(set(names)) #3
A= set(names)
B = sorted(list(A)) #4
print(B)
names = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌"
#리스트로 변환
list_names = names.split(',')
cnt_k=0 #김씨 카운터
cnt_l=0 #이씨 카운터
cnt_j=0 #이재영 카운터
#각각 카운터
for name in list_names:
if name[0] == '김':
cnt_k += 1
if name[0] == '이':
cnt_l += 1
if name == '이재영':
cnt_j += 1
print("1. 김씨와 이씨는 각각 몇 명 인가요? 김씨: "+ str(cnt_k)+"명, 이씨: "+ str(cnt_l)+"명")
print("2. 이재영 이란 이름이 몇 번 반복되나요? "+ str(cnt_j) + "번")
#집합으로 변환하여 중복 제거
set_names = set(list_names)
print("3. 중복을 제거한 이름을 출력하세요.")
#중복제거 출력
for name in set_names:
print(name)
print("4. 중복을 제거한 이름을 오름차순으로 정렬하여 출력하세요.")
#오름차순 정렬 출력
for name in sorted(set_names):
print(name)
public class HelloWorld{
public static void main(String []args){
String text = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌";
String[] spl = text.split(",");
int numberOfKimLee = 0;
int dupl = 0;
for(int i = 0; i < spl.length; i++) {
if ((spl[i].indexOf("김") == 0)||(spl[i].indexOf("이") == 0))
numberOfKimLee++;
if (spl[i].equals("이재영"))
dupl++;
}
System.out.println("김씨와 이씨 : " + numberOfKimLee + "명");
System.out.println();
System.out.println("이재영 : " + dupl + "명");
System.out.println();
int i = 0;
System.out.println(spl[i]);
i++;
while(i < spl.length) {
int j = i-1;
while(j>=0) {
if(spl[i].equals(spl[j]))
break;
else
j--;
}
if(j==-1)
System.out.println(spl[i]);
i++;
}
}
}
# 1
print(len([i for i in name_list if i[0] == '김']))
print(len([i for i in name_list if i[0] == '이']))
# 2
print(len([i for i in name_list if i == '이재영']))
# 3
print(set(name_list))
# 4
print(sorted(list(set(name_list))))
#1
e_count = 0
k_count = 0
for i in list:
if i[0] == '이':
e_count += 1
if i[0] == '김':
k_count += 1
print(e_count, k_count)
#2
print(list.count('이재영'))
#3
print(set(list))
#4
print(sorted(set(list)))
#Prob 1 / 2
A = '이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌'
A = A.split(',')
kim = 0
lee = 0
for name in A:
if name[0] == '김':
kim += 1
elif name[0] == '이':
lee += 1
print('The number of Kim is %s' %kim)
print('The number of lee is %s' %lee)
#Prob.3
leeJY = 0
for name in A:
if name == '이재영':
leeJY += 1
print(leeJY)
member = []
for i,name in enumerate(A):
k = 0
for j in range(i,len(A)):
if name == A[j]:
k += 1
member.append([i,k])
new_list = []
for temp in member:
if temp[1] == 1:
new_list.append(A[temp[0]])
print(new_list)
#Prob.4
print(sorted(set(new_list)))
[파이썬]
information = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌"
# 1. 김씨와 이씨는 각각 몇 명 인가요?
# 2. "이재영"이란 이름이 몇 번 반복되나요?
# 3. 중복을 제거한 이름을 출력하세요.
# 4. 중복을 제거한 이름을 오름차순으로 정렬하여 출력하세요.
KimC = 0
LeeC = 0
jyLee = 0
names = information.split(",")
name_filter = []
for i in names:
lastname = i[0]
if i[0] == "김":
KimC += 1
elif i[0] == "이":
LeeC += 1
if i == "이재영":
jyLee += 1
if i in name_filter:
continue
name_filter += [i]
name_filter.sort()
print("김씨는 %s명입니다" % KimC)
print("이씨는 %s명입니다" % LeeC)
print("이재영이란 이름은 %d번 반복됩니다" % jyLee)
print(name_filter)
people = ("이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌")
people_list = people.split(",")
# 1
kim, lee = 0, 0
for i in range(len(people_list)):
if people_list[i][0] == "김":
kim += 1
elif people_list[i][0] == "이":
lee += 1
else:
None
print("{} : {} / {} : {}".format("김씨", kim, "이씨", lee))
# 2
lee_jae_young = people_list.count("이재영")
print('"이재영"이라는 이름은',lee_jae_young, "번 반복됩니다.")
# 3
del_overlap=list(set(people_list))
print(del_overlap)
# 4
del_overlap.sort()
print(del_overlap)
import re
x='이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌'
#1
k=re.compile('[김]+')
l=re.compile('[이]+')
print(len(k.findall(x)),len(l.findall(x)))
#2
lj=re.compile('[이]+[재]+[영]+')
print(len(lj.findall(x)))
#3
name=re.compile('\w{3}')
result=[]
for i in name.findall(x):
if i not in result:
result.append(i)
print(','.join(result))
#4
print(','.join(sorted(result)))
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import java.util.StringTokenizer;
public class main {
public static void main(String[] args) {
final String str = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌";
//위의 문자열에 대한 문제를 푸시오
/*
1.김씨와 이씨는 각각 몇 명인가요?
2."이재영"이란 이름이 몇 번 반복되나요?
3.중복을 제거한 이름을 촐력하세요.
4.중복을 제거한 이름을 오름차순으로 정렬하여 출력하세요.
*/
//1. StringTokenizer을 이용해서 이름을 구분하고 ArrayList에 저장후 성을 구분할 것이다.
ArrayList<String> list = new ArrayList<>();
int firstname = 0;
String delim = ",";
StringTokenizer st = new StringTokenizer(str, delim);
// ','을 기준으로 문자열을 구분하고 각 문자열을 리스트에 담는다.
while(st.hasMoreTokens()) {
list.add(st.nextToken());
}
for(String s : list) {
//charAt을 이용한 특정위치의 문자를 뽑아낸다.
if(s.charAt(0) == '김' || s.charAt(0) =='이') {
firstname ++;
}
}
System.out.printf("김씨와 이씨는 %d명 입니다. \n" , firstname);
//2. list를 반복문으로 돌리면서 같은 문자가 있으면 카운트
int nameCount = 0;
for(int i=0; i<list.size(); i++) {
if(list.get(i).equals("이재영")) { nameCount ++; }
}
System.out.printf("\"이재영\" 이란 이름은 %d번 반복됩니다.\n", nameCount);
//3. 중복을 확인하고 중복되어 있으면 list에서 제거한다.
for(int i=0; i<list.size(); i++) {
if(list.get(i).equals("이재영")) { list.remove(i); }
}
System.out.println(list.toString());
//4. Collections.sort를 이용한 오름차순 정리
Collections.sort(list);
System.out.println(list.toString());
}
}
name = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌"
name_list= name.split(",")
#1
get_name = [i[0] for i in name_list]
print("%d, %d" % (get_name.count("김"),get_name.count("이")))
#2
print(name_list.count("이재영"))
#3
print(' '.join(list(set(name_list))))
#4
print(' '.join(sorted(list(set(name_list)))))
names_ = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌"
names = names_.split(",")
last_names = []
for name in names:
last_names.append(name[i])
kim_count = last_names.count('김')
lee_count = last_names.count('이')
print('김씨는 {}명이고, 이씨는 {}명입니다.'.format(kim_count, lee_count))
print("'이재영'씨는 {}번 반복됩니다.".format(names.count("이재영")))
print(','.join(set(names)))
print(','.join(sorted(set(names))))
<파이썬 3>
Python입니다.
>>> names = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌".split(',')
>>> len([x for x in names if x.startswith('이')])
6
>>> len([x for x in names if x.startswith('김')])
2
>>> len([x for x in names if x == '이재영'])
3
>>> set(names)
{'전경헌', '송정환', '김지완', '이재영', '이성연', '권종표', '김재성', '이유덕', '최승혁', '박영서', '강상희', '박민호'}
>>> sorted(list(set(names)))
['강상희', '권종표', '김재성', '김지완', '박민호', '박영서', '송정환', '이성연', '이유덕', '이재영', '전경헌', '최승혁']
str_name = "유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌"
names = str_name.split(",")
# 1.김씨와 이씨는 각각 몇 명 인가요?
kim = lee = 0
for name in names:
last_name = name[:1]
if "김" == last_name:
kim += 1
elif "이" == last_name:
lee += 1
print(f"김씨는 {kim} 명이고 이씨는 {lee} 명 입니다.")
# 2."이재영"이란 이름이 몇 번 반복되나요?
ljy = 0
for name in names:
if "이재영" == name:
ljy += 1
print(f"이재영이란 이름은 {ljy} 번 반복 됩니다.")
# 3.중복을 제거한 이름을 출력하세요.
# 4.중복을 제거한 이름을 오름차순으로 정렬하여 출력하세요.
names.sort()
distinct_names = []
tmp = ""
for i, name in enumerate(names):
print(i , name, tmp)
if(tmp != name):
distinct_names.append(names[i])
tmp = name
print(distinct_names)
s='이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌'
inp = s.split(',')
#김씨와 이씨는 각각 몇 명 인가요?
print("이씨는 모두: {}".format(len([i for i in inp if i[0]=='이'])))
print("김씨는 모두: {}".format(len([i for i in inp if i[0]=='김'])))
#"이재영"이란 이름이 몇 번 반복되나요?
print(s.count("이재영"))
#중복을 제거한 이름을 출력하세요.
print(set(inp))
#중복을 제거한 이름을 오름차순으로 정렬하여 출력하세요
print(sorted(set(inp)))
python 3.9
>>> a = '이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌'
>>> b = a.split(',')
>>> # 1
>>> kim = 0
>>> lee = 0
>>> for i in b:
... if i[0] == '김':
... kim += 1
... elif i[0] == '이':
... lee += 1
...
>>> print(kim, lee)
2 6
>>> # 2
>>> b.count('이재영')
3
>>> # 3
>>> bset = set(b)
>>> c = list(bset)
>>> c
['강상희', '권종표', '김지완', '최승혁', '이유덕', '이재영', '박민호', '송정환', '전경헌', '이성연', '김재성', '박영서']
>>> # 4
>>> c.sort()
>>> print(c)
['강상희', '권종표', '김재성', '김지완', '박민호', '박영서', '송정환', '이성연', '이유덕', '이재영', '전경헌', '최승혁']
3번에서 집합을 썼더니 이름이 무작위가 됐네요.
name = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌"
name_li = name.split(",")
#1
a =[]
for i in name_li:
a.append(i[0])
print("김씨 : {} \n이씨 : {}".format(a.count("김"), a.count("이")))
#2
print(name_li.count("이재영"))
#3
u_name = list(set(name_li))
print(u_name)
#4
u_name.sort()
print(u_name)
names = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌" indi_names = names.split(',') last_name = [i[0] for i in indi_names] print("김씨: ",last_name.count("김\n"),"이씨: ",last_name.count("이"))
print(indi_names.count("이재영"))
one_name = list(set(indi_names)) print(one_name)
처음 코딩 해보는데 재밌네요~ 파이썬입니다.
Name_String = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌"
Name_List = Name_String.split(",")
First_Name = []
for Name in Name_List:
First_Name.append(Name[0])
# '1번 문제'
print("{} 명" .format(len([x for x in First_Name if x =="김" or x =="이"])))
# '2번 문제'
print("{} 번" .format(len([x for x in Name_List if x =="이재영"])))
# '3번 문제'
No_Overlap_NameList = list(set(Name_List))
print(No_Overlap_NameList)
# '4번 문제'
No_Overlap_NameList.sort()
print(No_Overlap_NameList)
strNames = '이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌'
listNames = strNames.split(',')
nHowManyLeeJeaYoung = 0
#1.김씨와 이씨는 각각 몇 명 인가요?
listLastNames = [strName[0] for strName in listNames]
nCountKim = listLastNames.count("김")
nCountLee = listLastNames.count("이")
print("김씨는", nCountKim, "명, 그리고 이씨는", nCountLee, "명입니다.")
#2."이재영"이란 이름이 몇 번 반복되나요?
print("총 이재영이름은", listLastNames.count("이재영"), "명입니다.")
#3.중복을 제거한 이름을 출력하세요.
for name in listNames:
while(listNames.count(name) > 1):
listNames.remove(name)
print("중복이름 제거한 이름: ", listNames)
listNames.sort()
print("Sorting된 이름: ", listNames)
public static void main(String []args) {
String input = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌";
String[] names = input.split(",");
int count_kim = 0;
int count_lee = 0;
int count_ljy = 0;
// 정렬을 위한 자료구조 사용
ArrayList<String> name_list = new ArrayList<String>();
for(int i = 0; i < names.length; i++) {
if(names[i].startsWith("김"))
count_kim++;
if(names[i].startsWith("이"))
count_lee++;
if(names[i].equals("이재영"))
count_ljy++;
if(!name_list.contains(names[i]))
name_list.add(names[i]);
}
System.out.println("\'김\'씨 성을 가진 사람 수: " + count_kim + "명");
System.out.println("\'이\'씨 성을 가진 사람 수: " + count_lee + "명");
System.out.println("\'이재영\' 이란 이름의 반복 수: " + count_ljy + "번\n");
//length()가 아닌 size()사용
System.out.println("중복을 제거한 이름의 출력 : ");
for(int i = 0; i < name_list.size(); i++) {
System.out.print(name_list.get(i)+ ((name_list.size() == i + 1)?"":","));
}
System.out.printf("\n\n");
//naem_list[i]가 아닌 get(i)사용
System.out.println("중복을 제거한 이름의 오름차순 정렬 후 출력 : ");
Collections.sort(name_list);
for(int i = 0; i < name_list.size(); i++) {
System.out.print(name_list.get(i)+((name_list.size() == i+1)?"":","));
}
}
}
string = '이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌'
list_string=string.split(',')
# 1번 문제
def number_of_Kim_and_Lee():
countkim = 0
countlee = 0
for i in list_string:
if i[0] == '이':
countlee += 1
elif i[0] == '김':
countkim += 1
return countkim, countlee
# 2번 문제
def number_of_LeeJaeYoung():
count = 0
i = 1
while True :
if list_string[i] == '이재영':
count += 1
i += 1
else:
i += 1
if len(list_string) == i:
break
return count
# 3번 문제
def no_dup_list():
return list(set(list_string))
# 4번 문제
def list_sorted():
a=no_dup_list()
b=a.sort()
return a
name = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌"
name_list = name.split(",")
def first_name_search(name_list):
count_1 = 0
count_2 = 0
for i in name_list:
count_1 += i.count("김")
count_2 += i.count("이")
return "김씨 : {}, 이씨 : {}".format(count_1, count_2)
def count(name_list):
count = 0
for i in name_list:
count += i.count("이재영")
return count
def unique_name(name_list):
unique_name = list(set(name_list))
return unique_name
def unique_sort(name_list):
unique_name = list(set(name_list))
unique_name.sort()
return unique_name
print(first_name_search(name_list))
print(count(name_list))
print(unique_name(name_list))
print(unique_sort(name_list))
#codingdojing_사이냅소프트
nameList = input("name: ")
nameList = nameList.split(',')
nameDic = {}
kim = 0
Lee = 0
for name in nameList:
nameDic.setdefault(name, 0)
nameDic[name] += 1
if name[0] == '김':
kim += 1
elif name[0] == '이':
Lee += 1
#1
print(f"""김: {kim}명 이: {Lee}명""")
#2
print(f"""이재영: {nameDic['이재영']}명""") #or nameList.count 사용
#3
for name in nameDic:
print(name, end = ',')
print()
#4
for name in sorted(nameDic):
print(name, end = ',')
names = ["이유덕","이재영","권종표","이재영","박민호","강상희","이재영","김지완","최승혁","이성연","박영서","박민호","전경헌","송정환","김재성","이유덕","전경헌"]
leekim_count = []
for i in names:
if i[0] == "이" or i[0] == "김":
leekim_count.append(i)
print("1번답: {0}명".format(len(leekim_count)))
print("2번답: {0}번".format(names.count("이재영")))
print("3번답: {0}".format(set(names)))
names_set_list = list(set(names))
names_set_list.sort()
print("4번답: {0}".format(names_set_list))
a="이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌"
김씨=a.count("김")
이씨=a.count("이")
print('김씨:',김씨,'이씨:',이씨)
이재영=a.count("이재영")
print(이재영,'번')
n=a.split(",")
print(n)
name_set=set(n)
name_new=list(name_set)
print(name_new)
name_new.sort()
print(name_new)
names = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌" split_name = names.split(",")
print(len(list(filter(lambda x:x[0]=='김', split_name)))) print(len(list(filter(lambda x:x[0]=='이', split_name))))
print(split_name.count("이재영"))
same_name = set(split_name) print(same_name)
for i in sorted(same_name): print(i)
string = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌"
def count_family_name(family_name): return len([x for x in string.split(",") if x[0] ==family_name])
def count_name(name): return len([x for x in string.split(",") if x ==name])
print("1. 김씨:{}명, 이씨:{}명".format(count_family_name("김"), count_family_name("이"))) print("2. 이재영씨는 {}명입니다".format(count_name("이재영"))) print("3. 중복을 제거한 이름의 수는 {}입니다".format(len(set(string.split(","))))) print("4. 중복을 제거한 이름을 오름차순으로 정렬하여 출력하면") print(sorted(list(set(string.split(",")))))
import UIKit
var nameStr = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌"
let nameArr = nameStr.split(separator: ",")
var countLee = Int()
var countKim = Int()
let famliyNameArr = nameArr.forEach { name in
if name.first == "이" {
countLee += 1
} else if name.first == "김" {
countKim += 1
}
}
// 1 번 문제 : 이씨와 김씨는 몇 명인가?
print("이씨는 \(countLee)명 입니다.")
print("김씨는 \(countKim)명 입니다.")
// 2 번 문제 : "이재영" 은 몇 번 반복되고 있는가?
var countMrLee = Int()
nameArr.forEach { name in
if name == "이재영" {
countMrLee += 1
}
}
print("이재영씨는 \(countMrLee)명 입니다.")
// 3 번 문제 : 중복 없이 이름을 출력해라.
var nameSet = Set<String>()
nameArr.forEach { name in
nameSet.insert(String(name))
}
print("DEBUG>> 중복을 제거한 이름 \(nameSet) ")
// 4 번 문제 : 중복없는 이름에 오름차순을 적용해라.
var nameArrJustOne = [String]()
nameSet.forEach { name in
nameArrJustOne.append(name)
}
var result = nameArrJustOne.sorted()
print("오름차순 \(nameArrJustOne)")
a = ['이유덕','이재영','권종표','이재영','박민호','강상희','이재영','김지완','최승혁','이성연','박영서','박민호','전경헌','송정환','김재성','이유덕','전경헌']
#1.김씨와 이씨는 각각 몇 명 인가요?
add = ''
for i in range(len(a)):
add += a[i]
print('김씨는 %d명이고, 이씨는 %d명입니다.' %(add.count('김'),add.count('이')))
#2."이재영"이란 이름이 몇 번 반복되나요?
print('"이재영"이라는 이름은 %d번 반복됩니다.' %(a.count('이재영')))
#3.중복을 제거한 이름을 출력하세요.
print(set(a))
#4.중복을 제거한 이름을 오름차순으로 정렬하여 출력하세요.
a_sort = list(set(a))
a_sort.sort()
print(a_sort)
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
public class Ex05 {
public static void main(String[] args) {
String name = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌";
String [] str = name.split(",");
// 4번 문제를 생각해서 중복을 제거
HashSet <String> nameList = new HashSet<String>();
System.out.println();
int countNameKim = 0;
int countNameLee = 0;
int nameLeejaey = 0;
for (int i =0; i <str.length; i++) {
if(str[i].equals("이재영")) {
nameLeejaey++;
}
if (str[i].startsWith("이")) {
countNameLee++;
}
else if (str[i].startsWith("김")) {
countNameKim++;
}
nameList.add(str[i]);
}
System.out.println("김씨는 " + countNameKim + "명 이고, 이씨는 " + countNameLee + "명이고, 이재영은 " + nameLeejaey + "번 반복 됩니다");
// Hashset -> list
ArrayList<String> list = new ArrayList<String>(nameList);
System.out.println(list);
// List 정렬
Collections.sort(list);
System.out.println(list);
java
#1
list=["이유덕","이재영","권종표","이재영","박민호","강상희","이재영","김지완","최승혁","이성연",
"박영서","박민호","전경헌","송정환","김재성","이유덕","전경헌"]
kim=[]
lee=[]
for i in list:
if i[0]=="김":
kim.append(i)
elif i[0]=="이":
lee.append(i)
print(len(kim),len(lee))
#2
list=["이유덕","이재영","권종표","이재영","박민호","강상희","이재영","김지완","최승혁","이성연",
"박영서","박민호","전경헌","송정환","김재성","이유덕","전경헌"]
repeat=0
for i in list:
if i=="이재영":
repeat+=1
print(repeat)
#3
list=["이유덕","이재영","권종표","이재영","박민호","강상희","이재영","김지완","최승혁","이성연",
"박영서","박민호","전경헌","송정환","김재성","이유덕","전경헌"]
result=[]
for i in list:
if i not in result:
result.append(i)
print(result)
#4
result.sort()
print(result)
import java.util.*;
public class FindName {
public static void main(String[] args) {
String names = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌";
String[] Array_Names = names.split(",");
//김씨와 이씨는 각각 몇명인가.
int name_kim = 0;
int name_lee = 0;
for (int i = 0; i < Array_Names.length; i++) {
if(Array_Names[i].startsWith("김"))
name_kim ++;
else if (Array_Names[i].startsWith("이"))
name_lee ++;
}
System.out.println("김씨: " + name_kim);
System.out.println("이씨:" + name_lee);
//이재영이란 이름이 몇 번 반복되는가.
int Jayung = 0;
for (int i = 0; i < Array_Names.length; i++) {
if(Array_Names[i].equals("이재영"))
Jayung ++;
}
System.out.println("이재영 반복 중복횟수: " + Jayung);
//중복을 제거한 이름 출력.
ArrayList<String> list = new ArrayList<String>();
for(String data : Array_Names) {
if(!list.contains(data))
list.add(data);
}
System.out.println(list);
//중복을 제거한 이름 오름차순 정렬
Collections.sort(list);
System.out.println(list);
}
}
# 이름 리스트를 입력 (자동으로 입력해놨음)
list_name = '이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌'
# # str을 list로 변환 (이름 문자에 '를제거하고, 3글자씩 리스트로 변경)
def sort_name(a):
n = len(a)
result = []
for i in range(int(len(list_name))):
if i % 4 == 0 or i == 0:
result.append(list_name[i:i+3])
else:
pass
return result
lists_name = sort_name(list_name)
# 리스트 내 김과 이를 찾아서 출력
count_kim = [i for i in lists_name if "김" in i]
count_lee = [i for i in lists_name if "이" in i]
input('1번 문제 : 김씨와 이씨는 각각 몇 명 인가요?')
print('1번 답변 : ', '김씨는 %d명 입니다.' % len(count_kim), '이씨는 %d명 입니다.' % len(count_lee))
print('')
# 리스트 내 이재영을 찾아서 출력
input('2번 문제 : "이재영"이란 이름이 몇 번 반복되나요?')
print('2번 답변 : ', '이재영은 %d번 반복됩니다.' % lists_name.count('이재영'))
print('')
# 동명의 이름을 찾는 함수
def find_same_name(a):
n = len(a)
result = set()
for i in range(0, n-1):
for j in range(i+1, n):
if a[i] == a[j]:
result.add(a[i])
return result
input('3번 문제 : 중복을 제거한 이름을 출력하세요.')
print('3번 답변 : ', find_same_name(lists_name))
print('')
# 이름 오름차순으로 변경하여 출력
set_name = set(lists_name)
set_lists_name = list(set_name)
input('4번 문제 : 중복을 제거한 이름을 오름차순으로 정렬하여 출력하세요.')
print('4번 답변 : ', sorted(set_lists_name))
print('')
law_t = '이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌'
list_t = law_t.split(',')
kcount, lcount, ljycount = 0, 0, 0
for name in list_t:
if name[0] == '김':
kcount += 1
elif name[0] == '이':
lcount += 1
if name == '이재영':
ljycount += 1
print("김씨: {}명 이씨: {}명 '이재영': {}번 반복".format(kcount, lcount, ljycount))
print(sorted(set(list_t)))
data = ['이유덕', '이재영', '권종표','이재영','박민호','강상희',
'이재영','김지완','최승혁','이성연','박영서','박민호',
'전경헌','송정환','김재성','이유덕','전경헌']
kim = 0
lee = 0
lej = 0
for i in data:
if '김' in i[0]:
kim += 1
if '이' in i[0]:
lee += 1
if '이재영' in i:
lej += 1
print('김=',kim,'이=',lee,'이재영=',lej)
data2 = set(data)
print(sorted(data2))
nlist = n.split(",")
kimc = 0
leec = 0
for name in nlist :
if name.startswith("김"):
kimc += 1
elif name.startswith("이"):
leec += 1
print("김씨 - %d명 , 이씨 - %d명" %(kimc, leec))
print("이재영 - %d명"%nlist.count("이재영"))
nameset = list(set(nlist))
print(nameset)
nameset.sort()
print(nameset)
name_list = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌"
names = name_list.split(',')
lee_count = 0
kim_count = 0
leejy = 0
one_name = []
for i in names:
if i[0] == "이":
lee_count += 1
elif i[0] == "김":
kim_count += 1
for i in names:
if i not in one_name:
one_name.append(i)
else:
pass
print("이씨는 {}명, 김씨는 {}명 입니다.".format(lee_count, kim_count))
print("이재영씨는 {}번 반복됩니다.".format(names.count("이재영")))
print(one_name)
print(sorted(one_name))
# 1번
names = ('이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌').split(',')
kimcount = 0
leecount = 0
for i in names:
if '김' in i:
kimcount += 1
elif '이' in i:
leecount += 1
print('김씨는 %d명, 이씨는 %d명입니다.\n'%(kimcount, leecount))
# 2번
print('이재영이란 이름은 %d번 반복됩니다.\n' %(names.count("이재영")))
# 3번
uniq_names = list(set(names))
print(uniq_names)
# 4번
uniq_names.sort()
print(uniq_names)
a = '이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌'
b=a.split(',')
count1K=0
count1L=0
for i in b:
if i[0]=='김':
count1K+=1
elif i[0]=='이':
count1L+=1
else:
pass
print('김씨는 %d명이고 이씨는 %d명입니다.'%(count1K, count1L))
count2=0
for i in b:
if i=='이재영':
count2+=1
else:
pass
print('"이재영"이라는 이름은 %d번 반복됩니다.'%count2)
c=set(b)
d=','.join(c)
print(d)
e=list(c)
e.sort()
f=','.join(e)
print(f)
names = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌" list_names = names.split(',')
count_k = 0 count_l = 0 count_ljy = 0
for name in list_names: if name[0] == '김': count_k = count_k + 1 if name[0] == '이': count_l = count_l + 1 if name == '이재영': count_ljy = count_ljy + 1
print("김씨:",count_k,"이씨:", count_l,"이재영:", count_ljy)
names_true = set(list_names) print(names_true)
print(sorted(names_true ))
name='이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌' name_list=list(name)
이=name.count('이') 김=name.count('김') print('이씨:%d'%'이') print('김씨:%d'%'김')
이재영=name.count('이재영') print('이재영:%d'%'이재영')
name1=set(name) print(name1)
new_list=list() for v in name_list: for v not in new_list: new_list.append(v) print(name_list)
sample= "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌"
sample = sample.split(",")
print(sample)
# 김씨와 이씨는 각각 몇 명인가요?
count = [0, 0]
for i in sample:
if i[0] == "김":count[0] += 1
elif i[0] == "이":count[1] += 1
else:continue
print("김씨 :", count[0])
print("이씨 :", count[1])
#"이재영"이란 이름이 몇 번 반복되나요?
count = 0
for i in sample:
if i == "이재영":
count += 1
else:
pass
print("이재영 :", count)
#중복을 제거한 이름을 출력하세요.
sample = list(set(sample))
print(sample)
#중복을 제거한 이름을 오름차순으로 정렬하여 출력하세요.
sample.sort()
print(sample)
public class Test {
public static void main(String[] args) {
String name[] = {"이유덕","이재영","권종표","이재영","박민호","강상희","이재영","김지완","최승혁","이성연","박영서","박민호","전경헌","송정환","김재성","이유덕","전경헌"};
System.out.println("1. 김씨와 이씨는 각각 몇 명 인가요?");
int kim = 0;
int lee = 0;
for(int i=0;i<name.length;i++){
if(name[i].substring(0,1).equals("김")){
kim++;
}else if(name[i].substring(0,1).equals("이")){
lee++;
}
}
System.out.println("김씨 : " + kim + "명");
System.out.println("이씨 : " + lee + "명");
System.out.println();
System.out.println("2. \"이재영\"이란 이름이 몇 번 반복되나요?");
int ljy = 0;
for(int i=0;i<name.length;i++){
if(name[i].equals("이재영")){
ljy++;
}
}
System.out.println(ljy + "번");
System.out.println();
System.out.println("3. 중복을 제거한 이름을 출력하세요.");
LinkedHashSet<String> linkedHashSet = new LinkedHashSet<String>(Arrays.asList(name));
String resultName[] = linkedHashSet.toArray(new String[0]);
for(int i=0;i<resultName.length;i++){
System.out.print(resultName[i]);
if(i!=resultName.length-1){
System.out.print(" ,");
}else {
System.out.println();
System.out.println();
}
}
System.out.println("4. 중복을 제거한 이름을 오름차순으로 정렬하여 출력하세요.");
Arrays.sort(resultName);
for(int i=0;i<resultName.length;i++){
System.out.print(resultName[i]);
if(i!=resultName.length-1){
System.out.print(" ,");
}
}
}
}
public static void main(String[] args) {
String[] str = { "이유덕", "이재영", "권종표", "이재영", "박민호", "강상희", "이재영", "김지완", "최승혁", "이성연", "박영서", "박민호", "전경헌",
"송정환", "김재성", "이유덕", "전경헌" };
String[] str1 = new String[str.length];
int x = 0, y = 0;;
for(int i = 0; i < str.length; i++) {
if(str[i].charAt(0) == '이'){
++x;
}else if(str[i].charAt(0) == '김'){
++y;
}
}
System.out.println("이씨는 "+ x + "명, 김씨는 "+ y+ "명");
for(int i = 0; i < str.length; i++) {
boolean isName = true;
for(String j : str1) {
if(str[i].equals(j)) {
isName = false;
}
}
if(isName) {
for(int j = 0; j<str1.length; j++) {
if(str1[j] == null) {
str1[j] = str[i];
break;
}
}
}
}
int nameNum = 0;
for(int i = 0; i < str1.length; i++) {
if(str1[i] != null) {
++nameNum;
System.out.print(str1[i] + " ");
}
}
System.out.println();
String[] str2 = new String[nameNum];
nameNum = 0;
for(int i = 0; i < str1.length; i++) {
if(str1[i] != null) {
str2[nameNum] = str1[i];
++nameNum;
}
}
Arrays.sort(str2);
System.out.println(Arrays.toString(str2));
}
var name = new Array("이유덕", "이재영", "권종표", "이재영", "박민호", "강상희", "이재영", "김지완", "최승혁", "이성연", "박영서", "박민호", "전경헌", "송정환", "김재성", "이유덕", "전경헌");
var nameArr = name.split(",");
var kimCnt = 0;
var leeCnt = 0;
var leejaeyoungCnt = 0;
for(var i = 0; i < nameArr.length; i++) {
if(nameArr[i].charAt(0) == "김") {
kimCnt ++;
continue;
}
if(nameArr[i].charAt(0) == "이") {
leeCnt ++;
if(nameArr[i] == "이재영") {
leejaeyoungCnt ++;
}
continue;
}
}
var del = Array.from(new Set(nameArr))
console.log("김씨 : " + kimCnt + ", 이씨 : " + leeCnt);
console.log("이재영 : " + leejaeyoungCnt);
console.log("중복제거 : " + del);
console.log("정렬 : " + del.sort());
x = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌"
y = []
y = x.split(",")
a1 = 0
a2 = 0
for a in range(len(y)):
if y[a][0] == "김":
a1 += 1
elif y[a][0] == "이":
a2 += 1
print("1번 : 김씨는 %s명, 이씨는 %s명입니다." % (a1, a2))
b = 0
for a in range(len(y)):
if y[a] == "이재영":
b += 1
print("2번 : 이재영은 %s번 반복됩니다." % b)
c1 = []
c2 = []
for a in range(len(y)):
if y.count(y[a]) > 1:
c1.append(y[a])
elif y.count(y[a]) == 1:
c2.append(y[a])
print("3번 : 중복을 제거한 명단은 ", c2, "입니다")
c2.sort()
print("4번 : 중복을 제거한 명단의 오름차순은" , c2, "입니다")
const name = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌"
let names = name.split(",")
let answer1 = 0;
let answer2 = 0;
let answer3 = 0;
for(i=0;i<names.length;i++) {
if(names[i].includes("김")) answer1++
if(names[i].includes("이")) answer2++
if(names[i] === "이재영") answer3++
for(j=i;j<names.length;j++) {
//i != j는 자기 자신을 조건으로 넣지 않기 위함
if(i != j && names[i] === names[j]) {
names.splice(j,1)
}
}
}
console.log("김씨는 몇명인가 ? " + answer1)
console.log("이씨는 몇명인가 ? " + answer2)
console.log("'이재영'은 몇 번 반복되는가 ? " + answer3)
console.log("중복을 제가한 이름을 출력 : " + names)
console.log("중복을 제가한 이름의 오름차순 : " + names.sort())
n ="이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌"
n = n.split(",")
count_kim = 0
count_lee = 0
count_ljm = 0
for i in n:
if i[0] == "김":
count_kim = count_kim + 1
elif i[0] == "이":
count_lee = count_lee + 1
print("김씨는 %d명입니다" %count_kim, "이씨는 %d명입니다" %count_lee)
for i in n:
if i=="이재영":
count_ljm =+ 1
print("이재영은 %d번 반복됩니다" %count_ljm)
print(",".join(set(n)))
print(",".join(sorted(set(n))))
a="이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌"
b = a.split(",")
kim = 0
lee = 0
lee_CNT = 0
#김씨와 이씨는 각각 몇 명 인가요?
for i in range(len(b)):
if b[i].startswith("이") :
lee +=1
elif b[i].startswith("김") :
kim +=1
print(kim)
print(lee)
#"이재영"이란 이름이 몇 번 반복되나요?
for i in range(len(b)):
if b[i] == "이재영" :
lee_CNT += 1
print(lee_CNT)
# 중복을 제거한 이름을 출력하세요.
c = set(b)
print(c)
# 중복을 제거한 이름을 오름차순으로 정렬하여 출력하세요.
d = sorted(c)
print(d)
names = '이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌'
#김씨와 이씨는 각각 몇 명 인가요?
count_k = 0
count_l = 0
name_list = names.split(',')
for i in name_list:
if i[0] == '김':
count_k += 1
elif i[0] == '이':
count_l += 1
print(f"김씨는 {count_k}명 입니다")
print(f"이씨는 {count_l}명 입니다")
#"이재영"이란 이름이 몇 번 반복되나요?
count_JY = 0
for i in name_list:
if i == '이재영':
count_JY += 1
print(f"이재영은 {count_JY}명 입니다.")
#중복을 제거한 이름을 출력하세요.
new_name = set(name_list)
print(new_name)
#중복을 제거한 이름을 오름차순으로 정렬하여 출력하세요.
new_name_sort = sorted(new_name)
print(new_name_sort)
import re
input_str = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌"
input_str = input_str.split(',')
p = re.compile("[김]..")
print( "1. 김: ",len(list( filter(p.match,input_str))) )
p = re.compile("[이]..")
print( "1. 이: ",len(list( filter(p.match,input_str))) )
p = re.compile("이재영")
print( "2. ",len(list( filter(p.match,input_str))) )
input_str = list( set(input_str) )
print( "3. ",input_str)
input_str.sort()
print("4. ",input_str)
a = '이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌'
b = a.split(',')
print('1. 김씨는',len([x for x in b if x[0] == '김']),'명 입니다.', '이씨는',len([x for x in b if x[0] == '이']),'명 입니다.')
print('2. 이재영이란 이름은',len([x for x in b if x == '이재영']),'번 반복 됩니다.')
print('3.',','.join(set(b)))
print('4.', ','.join(sorted(set(b))))
name_list = '이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌'
name_list = name_list.split(',')
# 김씨와 이씨는 각각 몇 명 인가요?
count_kim = 0
count_lee = 0
for i in name_list:
if i[0] == '김':
count_kim += 1
elif i[0] == '이':
count_lee += 1
print('김씨:',count_kim,'\n이씨:',count_lee)
# "이재영"이란 이름이 몇 번 반복되나요?
count_jyl = 0
for i in name_list:
if i == '이재영':
count_jyl += 1
print('이재영:',count_jyl)
#중복을 제거한 이름을 출력하세요.
print(set(name_list))
#중복을 제거한 이름을 오름차순으로 정렬하여 출력하세요.
print(sorted(set(name_list)))
names = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌"
names=names.split(',')
#1
last_name=[name[0] for name in names]
print("김씨: %d" %last_name.count("김"))
print("이씨: %d" %last_name.count("이"))
#2
print("이재영: %d" %names.count("이재영"))
#3
names2=list(set(names))
print(names2)
#4
name3=sorted(names2)
print(name3)
파이썬
koreans = ['이유덕','이재영','권종표','이재영','박민호','강상희','이재영','김지완','최승혁','이성연','박영서','박민호','전경헌','송정환','김재성','이유덕','전경헌']
kim = []
lee = []
for i in koreans: #김씨와 이씨의 반복을 for문을 통해 찾아내서
if '김' in i: #리스트로 저장후 길이로 몇 번 반복되었는지 확인
kim.append(i)
elif '이' in i:
lee.append(i)
print('김씨는',len(kim),'명', '이씨는',len(lee),'명')
a = koreans.count('이재영')
print('2번문제 : 이재영은 '+str(a)+'번 반복됨')
b = list(set(koreans))
print('3번문제 :',b)
b.sort() # d=sorted(c)
print('4번문제 :',b) # print(d)도 동일하다
names = ['이유덕','이재영','권종표','이재영','박민호','강상희','이재영','김지완','최승혁','이성연','박영서','박민호','전경헌','송정환','김재성','이유덕','전경헌']
lee = 0 kim = 0 leejy = 0 names_mod = []
for name in names: if name[0] == '이': lee += 1
if name[0] == '김':
kim += 1
if name == '이재영':
leejy += 1
if name not in names_mod:
names_mod.append(name)
print("이씨 성은 %d명 입니다." % lee) print("김씨 성은 %d명 입니다." % kim) print("이재영은 %d번 반복됩니다." % leejy) print(names_mod) print(sorted(names_mod))
names = ['이유덕','이재영','권종표','이재영','박민호','강상희','이재영','김지완','최승혁','이성연','박영서','박민호','전경헌','송정환','김재성','이유덕','전경헌']
lee = 0
kim = 0
leejy = 0
names_mod = []
for name in names:
if name[0] == '이':
lee += 1
if name[0] == '김':
kim += 1
if name == '이재영':
leejy += 1
if name not in names_mod:
names_mod.append(name)
print("이씨 성은 %d명 입니다." % lee)
print("김씨 성은 %d명 입니다." % kim)
print("이재영은 %d번 반복됩니다." % leejy)
print(names_mod)
print(sorted(names_mod))
# 복붙해서 리스트로 만듦
names = '이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌'
name_list = names.split(',')
# 김씨와 이씨는 각각 몇 명?
kims = []
lees = []
for name in name_list:
if name[0] == '김':
kims.append(name)
elif name[0] == '이':
lees.append(name)
print(f'김씨는 {len(kims)}명')
print(f'이씨는 {len(lees)}명')
# "이재영"은 몇 번 반복?
count_ljy = 0
for name in name_list:
if name == '이재영':
count_ljy += 1
print(f'이재영은 {count_ljy}번 반복')
# 중복을 제거한 이름을 출력
new_names = []
for name in name_list:
if name not in new_names:
new_names.append(name)
print('중복 제거:', new_names)
# 중복 제거한 이름을 오름차순으로
print('오름차순:', sorted(new_names))
names = ['이유덕','이재영','권종표','이재영','박민호','강상희', '이재영','김지완','최승혁','이성연','박영서','박민호', '정경헌','송정환','김재성','이유덕','정경헌'] lee = 0 kim = 0 ljy = 0
my_set = list(set(names)) print(my_set) my_set.sort() print(my_set)
for i in names: if i[0] == "이": lee += 1 if i == "이재영": ljy += 1 elif i[0] == "김": kim += 1
print("성씨가 이씨인 사람들 -> {}".format(lee)) print("성씨가 김씨인 사람들 -> {}".format(kim)) print("이름이 이재영인 사람 -> {}".format(ljy))
names='이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌'
names_list=names.split(",")
Kim=[]
Lee=[]
for name in names_list:
if name[0]=='김':
Kim.append(name)
if name[0]=='이':
Lee.append(name)
print("1. 김씨와 이씨는 각각 몇 명인가요?\n","김씨 : %d"%len(Kim), "이씨 : %d"%len(Lee))
LJY=names_list.count('이재영')
print('''2. "이재영"이란 이름이 몇 번 반복되나요?\n''',LJY)
del_list=list(set(names_list))
print("3. 중복을 제거한 이름을 출력하세요.\n", del_list)
del_list.sort()
print("4. 오름차순으로 정렬\n",del_list)
using System;
using System.Collections.Generic;
namespace FirstProgram
{
class Program
{
static void Main(string[] args)
{
string[] names = new string[] {"이유덕","이재영","권종표","이재영","박민호","강상희","이재영","김지완","최승혁","이성연","박영서","박민호","전경헌","송정환","김재성","이유덕","전경헌"};
List<string> newnames = new List<string>();
int k = 0;
int l = 0;
for (int i = 0; i < names.Length; i++)
{
if (names[i].StartsWith("김"))
k++;
if (names[i].StartsWith("이"))
l++;
}
foreach (string name in names)
{
if (newnames.Contains(name))
continue;
newnames.Add(name);
}
Console.WriteLine("김씨는 " + k);
Console.WriteLine("이씨는 " + l);
Console.WriteLine("중복 제거 :");
for(int i=0; i<newnames.Count; i++)
{
Console.Write(newnames[i] + " ");
}
newnames.Sort();
Console.WriteLine("");
Console.WriteLine("중복 제거 후 오름차순 :");
for (int i = 0; i < newnames.Count; i++)
{
Console.Write(newnames[i] + " ");
}
}
}
}
C#
names=['이유덕','이재영','권종표','박민호','강상희','이재영','김지완',
'최승혁','이성연','박영서', '박민호' ,'전경헌' ,'송정환' ,'김재성' ,'이유덕' ,'전경헌']
#김씨와 이씨는 각각 몇명 ?
a=0
b=0
for i in names:
if i[0]=='이' :
a+=1
elif i[0]=='김':
b+=1
print(a,b)
#이재영이란 이름은 몇번 반복 ?
a1=0
for i in names :
if i =='이재영' :
a1+=1
print(a1)
#중복된 이름 제거
print(set(names))
#중복된 이름 제거후 오름차순
b1=list(set(names))
b1.sort()
print(b1)
quiz = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌"
quiz = quiz.split(",")
count1 = 0
count2 = 0
count3 = 0
for i in range(len(quiz)):
if quiz[i][0] == "김":
count1 += 1
elif quiz[i][0] == "이":
count2 += 1
if quiz[i] == "이재영":
count3 += 1
print(f'1번 : 김씨 {count1}명, 이씨 {count2}명')
print(f'2번 : {count3}번')
quiz = set(quiz)
print(f'3번 : {quiz}')
quiz = sorted(quiz)
print(f'4번 : {quiz}')
재밌게 풀고 있습니다~~
lst = ['이유덕','이재영','권종표','이재영','박민호','강상희','이재영','김지완','최승혁','이성연','박영서','박민호','전경헌','송정환','김재성','이유덕','전경헌']
kim = 0
lee = 0
for i in lst:
if i[0] == '이':
kim += 1
elif i[0] == '김':
lee += 1
print("이씨는 %d명, 김씨는 %d명이다" % (lee, kim))
leejy = 0
for jy in lst:
if jy == '이재영':
leejy += 1
print("이재영은 %d 명이다" % (leejy))
personlst = []
for person in lst:
if person not in personlst:
personlst.insert(0, person)
print(personlst)
personlst.sort()
print(personlst)
import java.util.HashSet;
import java.util.TreeSet;
public class DupulicateName {
public static void main(String[] args) {
String input = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌";
String[] name = input.split(",");
int countKim = 0;
int countLee = 0;
int countLjy = 0;
HashSet<String> hash = new HashSet<>(); // 중복허용은 안하지만 순서는 뒤죽박죽
TreeSet<String> tree = new TreeSet<>(); // 중복허용도 안하고 순서 자동정렬
for (int i = 0; i < name.length; i++) {
hash.add(name[i]);
tree.add(name[i]);
if (name[i].startsWith("김"))
countKim++;
if (name[i].startsWith("이"))
countLee++;
if (name[i].equals("이재영"))
countLjy++;
}
System.out.println("김씨는 " + countKim + "명이고 이씨는 "+ countLee + "명 입니다.");
System.out.println("이재영씨는 " + countLjy + "명 입니다.");
System.out.println(hash);
System.out.println(tree);
}
}
# 주어진 문자열(공백 없이 쉼표로 구분되어 있음)을 가지고 아래 문제에 대한 프로그램을 작성하세요.
# 이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌
# 김씨와 이씨는 각각 몇 명 인가요?
# "이재영"이란 이름이 몇 번 반복되나요?
# 중복을 제거한 이름을 출력하세요.
# 중복을 제거한 이름을 오름차순으로 정렬하여 출력하세요.
input_name = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌"
list_name = input_name.split(",")
# 김씨와 이씨는 각각 몇 명 인가요?
num_kim = 0
num_lee = 0
for i in list_name:
if i[0] == "김":
num_kim += 1
elif i[0] == "이":
num_lee += 1
else:
pass
print(f"김씨는 {num_kim}명입니다.")
print(f"이씨는 {num_lee}명입니다.")
# "이재영"이란 이름이 몇 번 반복되나요?
print()
num_iter = input_name.count('이재영')
print(f"이재영은 {num_iter}명입니다.")
# 중복을 제거한 이름을 출력하세요.
print()
list_deduplication = []
for i in list_name:
if i not in list_deduplication:
list_deduplication.append(i)
print(f"중복을 제거한 결과: \n{', '.join(list_deduplication)}")
# 중복을 제거한 이름을 오름차순으로 정렬하여 출력하세요.
print()
list_deduplication.sort()
print(f"중복을 제거하고 오름차순으로 정렬한 결과: \n{', '.join(list_deduplication)}")
l1 = '이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌'.split(',')
l2=[]
l3=[]
for i in l1:
if '이' in i:
l2.append(i)
elif '김' in i:
l3.append(i)
print('김씨: {}명, 이씨: {}명' .format(len(l3),len(l2)))
l4=l2+l3
print('{}번' .format(l4.count('이재영')))
print(set(l4))
print(sorted(set(l4)))
S = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌"
S = S.split(',')
list_kim = 0
list_lee = 0
list_lsy = []
list_name_sort = []
list_name_sort_in = []
for i in S:
if i[0] == '김':
list_kim += 1
elif i[0] == '이':
list_lee += 1
elif i == '이재영':
list_lsy += 1
print('김', list_kim)
print('이', list_lee)
print('이재영', list_lsy)
print(set(S))
print(sorted(S))
nm=['이유덕','이재영','권종표','이재영','박민호','강상희','이재영','김지완',\
'최승혁','이성연','박영서','박민호','전경헌','송정환','김재성','이유덕','전경헌']
cnt1=0
cnt2=0
for j in range(len(nm)):
if nm[j][0]=='이':
cnt1+=1
if nm[j][0]=='김':
cnt2+=1
print(cnt1, cnt2)
n=nm.count('이재영')
print(n)
nms=set(nm)
print(nms)
nml=list(nms)
print(sorted(nml))
names = '이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌'
name = names.split(',')
countKim = 0
countLee = 0
for i in name:
if i[0] == '김':
countKim += 1
elif i[0] == '이':
countLee += 1
print(countKim,countLee)
print(name.count('이재영'))
print(list(set(name)))
print(sorted(list(set(name))))
a='이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌' b=a.split(",") print(b) count_kim=0 count_lee=0 count_same=0 for i in b: if i[0]=="이": count_lee+=1 elif i[0]=="김": count_kim+=1 if i=="이재영": count_same+=1 print(count_kim,count_lee,count_same-1) a=b[0] b.sort() c=[] for i in b[1::]: if a==i: pass else: c.append(i) a=i print(c)
package com.algorithm.algorithmpractice.dojang;
import java.util.*;
public class Names {
public static ArrayList getByLastName(ArrayList<String> nameList, String inputName) {
char lastname = inputName.charAt(0);
ArrayList<String> result = new ArrayList<>();
nameList.forEach(elem -> {
if (elem.charAt(0) == lastname) {
result.add(elem);
}
});
return result;
}
public static ArrayList getDuplicatedName(ArrayList<String> nameList, String inputName) {
ArrayList<String> result = new ArrayList<>();
nameList.forEach(elem -> {
if (elem.equals(inputName)) {
result.add(elem);
}
});
return result;
}
public static void main(String[] args) {
String nameStr = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌";
String[] nameArr = nameStr.split(",");
ArrayList nameList = new ArrayList<String>(Arrays.asList(nameArr));
//1번 문제: 김씨와 이씨는 각각 몇 명 인가요?
ArrayList leeList = getByLastName(nameList, "이");
System.out.println(leeList.size());
ArrayList kimList = getByLastName(nameList, "김");
System.out.println(kimList.size());
//2번 문제: 이재영이라는 이름이 몇번 반복 되나요?
System.out.println(getDuplicatedName(nameList, "이재영").size());
//3번 문제: 중복을 제거한 이름을 출력하세요.
System.out.println(nameList);
ArrayList newArray = new ArrayList<>();
int idx = 0;
String temp = "";
while (nameList.size() > 0){
temp = (String) nameList.get(0);
newArray.add(temp);
for(int j = 0; j < nameList.size(); j++){
if(nameList.get(j).equals(temp)){
nameList.remove(temp);
}
}
}
System.out.println(newArray);
//4번 문제: 중복을 제거한 이름을 오름차순으로 출력하세요.
Object[] objArr = newArray.toArray();
Arrays.sort(objArr);
System.out.println(Arrays.toString(objArr));
Iterator it = Arrays.stream(objArr).iterator();
ArrayList<String> strArr = new ArrayList();
while (it.hasNext()){
strArr.add((String)it.next());
}
System.out.println(strArr);
}
}
print(a.count("이재영"))
count=0
for i in a:
for j in i[0]:
if j=="이" or j=="김":
count+=1
print(count)
print(set(a))
print(sorted(list(set(a))))
이름들 = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌".split(",")
김씨 = 0
이씨 = 0
이재영 = 0
중복제거 = []
for 이름 in 이름들:
if 이름[0] == '김':
김씨 += 1
elif 이름[0] == '이':
이씨 += 1
if 이름 == '이재영':
이재영 += 1
if 이름 not in 중복제거:
중복제거.append(이름)
print(f"김씨와 이씨는 각각 {김씨}명, {이씨}명 입니다.")
print(f'"이재영"이란 이름이 {이재영} 번 반봅됩니다.')
print(f'중복을 제거한 이름 : {" ".join(중복제거)}')
중복제거.sort()
print(f'중복을 제거한 이름을 오름차순으로 정렬 : {" ".join(중복제거)}')
파이썬입니다.
names = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌"
name_list = names.split(",")
n_1 = 0
n_2 = 0
n_3 = 0
for i in name_list:
if i[0] == "김":
n_1 += 1
elif i[0] == "이":
n_2 += 1
for i in name_list:
if i == '이재영':
n_3 += 1
if n_3 > 1:
name_list.remove(i)
print("중복된 이름이 제거되었습니다.%s" %i)
print("김씨는 %d명, 이씨는 %d명" %(n_1,n_2))
print("이재영이란 이름은 %d 번 반복됩니다." %n_3)
print(name_list)
name_list.sort()
print(name_list)
JAVA입니다.
public static void main(String[] args) {
// *문제*
// 주어진 문자열(공백 없이 쉼표로 구분되어 있음)을 가지고 아래 문제에 대한 프로그램을 작성하세요.
String[] names = { "이유덕", "이재영", "권종표 ", "이재영", "박민호", "강상희", "이재영", "김지완", "최승혁",
"이성연", "박영서", "박민호", "전경헌", "송정환", "김재성", "이유덕", "전경헌" };
// 1.김씨와 이씨는 각각 몇 명 인가요?
int sum = 0;
for (int i = 0; i < names.length; i++) {
if (names[i].substring(0, 1).equals("김") || names[i].substring(0, 1).equals("이")) {
sum++;
} // if
} // for_i
System.out.println("김씨와 이씨는 각각 몇 명 인가요?");
System.out.println("정답 : " + sum + "명");
// 2."이재영"이란 이름이 몇 번 반복되나요?
int result = 0;
for (int i = 0; i < names.length; i++) {
if (names[i].equals("이재영")) {
result++;
} // if
} // for_i
System.out.println("'이재영'이란 이름이 몇 번 반복되나요?");
System.out.println("정답 : " + result + "번");
// 3.중복을 제거한 이름을 출력하세요.
ArrayList<String> arrList = new ArrayList<String>();
for (String item : names) {
if (!arrList.contains(item)) {
arrList.add(item);
} // if
} // for_i
System.out.println("중복을 제거한 이름을 출력하세요.");
System.out.println("정답 : " + arrList);
// 중복을 제거한 이름을 오름차순으로 정렬하여 출력하세요.
arrList.sort(Comparator.naturalOrder());
System.out.println("중복을 제거한 이름을 오름차순으로 정렬하여 출력하세요.");
System.out.print("정답 : " + arrList);
} // main
자바로 풀어봤습니다.
import java.util.HashSet;
import java.util.TreeSet;
import java.util.Arrays;
public class name {
public static void main(String[] args) {
String[] names = {"이유덕","이재영","권종표","이재영","박민호","강상희","이재영","김지완","최승혁","이성연","박영서","박민호","전경헌","송정환","김재성","이유덕","전경헌"};
int countKim=0, countLee=0;
int countLeeJaeyoung = 0;
for(int i=0; i<names.length; i++) {
String name = names[i];
String firstName = name.substring(0, 1);
if(firstName.equals("김")==true) {
countKim++;
}else if(firstName.equals("이")==true) {
countLee++;
if(name.equals("이재영")) {
countLeeJaeyoung++;
}
}
}
HashSet<String> filteredNames = new HashSet<>(Arrays.asList(names));
TreeSet<String> sortedNames = new TreeSet<>(Arrays.asList(names));
System.out.printf("김씨성을 가진 사람은 %d명입니다.\n", countKim);
System.out.printf("이씨성을 가진 사람은 %d명입니다.\n", countLee);
System.out.printf("\"이재영\"이란 이름은 %d번 반복합니다.\n", countLeeJaeyoung);
System.out.println("중복을 제거한 이름들 :"+filteredNames);
System.out.println("중복을 제거한 이름을 오름차순으로 정렬 :"+sortedNames);
}
}
names = '이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌'.split(",")
N2=names.count("이재영")
N3=list(set(names))
N4=sorted(N3) # N4=N3.sort() ==> None 값 출력 오류 발생
N1_kim=[]
N1_Lee=[]
for name in names :
if name[0] =="김":
N1_kim.append(name[0])
elif name[0] =="이":
N1_Lee.append(name[0])
print(f"1번-김씨:{len(N1_kim)}명, 이씨:{len(N1_Lee)}명",f"2번-이재명 {N2}번 반복",f"3번-중복제거 :{N3}",f"4번-오름차순 중복제거: {N4}", sep="\n")
names = '이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌'.split(',')
# 1)
a = [ i[0] for i in names ]
kims = a.count('김')
lees = a.count('이')
print("김씨와 이씨는 각각 %d, %d 명입니다." % (kims, lees))
# 2)
print("'이재영'은 %d번 반복됩니다." % names.count('이재영') )
# 3)
u_names = list(set(names))
print(u_names)
# 4)
u_names.sort()
print(u_names)
python
names = '이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌'
names_list = names.split(',')
#1
count_kim = 0
count_lee = 0
for x in names_list:
if x[:1] == '김':
count_kim += 1
if x[:1] == '이':
count_lee += 1
print("김씨는 ",count_kim,"명, 이씨는 ",count_lee,"명 입니다.")
#2
count_ljy = 0
for x in names_list:
if x == '이재영':
count_ljy += 1
print("\"이재영\"이란 이름은 ",count_ljy,"번 반복됩니다.")
#3
new_list = []
for x in names_list:
if x in new_list:
continue
else:
new_list.append(x)
print(new_list)
#4
print(sorted(new_list))
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class NameSplit {
public static void main(String[] args) {
String str = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌";
String[] array = str.split(",");
int Kcnt = 0;
int Lcnt = 0;
int Jcnt = 0;
for (int i = 0; i < array.length; i++) {
if ("김".equals(array[i].substring(0, 1))) {
Kcnt++;
} else if ("이".equals(array[i].substring(0, 1))) {
Lcnt++;
}
if ("이재영".equals(array[i])) {
Jcnt++;
}
}
List<String> namelist = Arrays.asList(array);
List<String> list = new ArrayList<>();
for (int i = 0; i < namelist.size(); i++) {
if (!list.contains(namelist.get(i))) {
list.add(namelist.get(i));
}
}
System.out.print("김씨 : " + Kcnt + " ");
System.out.print("이씨 : " + Lcnt);
System.out.println();
System.out.print("이재영은 : " + Jcnt + "명");
System.out.println();
System.out.print(list);
System.out.println();
Collections.sort(list);
System.out.print("오름차순 : " + list);
}
}
name = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌".split(",")
# 1번 문제
first = [i[0] for i in name]
print(first) # 성씨 출력
Kim = first.count('김') # 김씨가 몇명인지 세기
Lee = first.count("이") # 이씨가 몇명인지 세기
print(Kim)
print(Lee)
# 2번 문제
print(name.count('이재영'))
# 3번 문제
a = list(set(name)) # a는 name에서 중복 제거한 리스트
print(a)
# 4번 문제
a.sort() # 오름차순
print(a)
public class Interview {
public void solve(String str) {
Map<String, Integer> countFamilyName = this.countFamilyName(str, "김", "이");
System.out.println("김씨와 이씨는 각각 몇 명 인가요? : " + countFamilyName);
System.out.println("\"이재영\"이란 이름이 몇 번 반복되나요? : " + this.countFullName(str, "이재영"));
System.out.println("중복을 제거한 이름을 출력하세요. : " + this.getRemovedDuplicateName(str));
System.out.println("중복을 제거한 이름을 오름차순으로 정렬하여 출력하세요. : " + this.getAcsName(str));
}
// === private ===
private Map<String, Integer> countFamilyName(String origin, String param1, String param2) {
String[] strArr = origin.split(",");
Map<String, Integer> result = new HashMap<>();
for (String str : strArr) {
if (str.startsWith(param1)) {
int count = result.getOrDefault(param1, 0);
result.put(param1, ++count);
}
if (str.startsWith(param2)) {
int count = result.getOrDefault(param2, 0);
result.put(param2, ++count);
}
}
return result;
}
private int countFullName(String origin, String param) {
String[] strArr = origin.split(",");
return (int) Arrays.stream(strArr)
.filter(str -> str.equals(param))
.count();
}
private String getRemovedDuplicateName(String origin) {
String[] strArr = origin.split(",");
return Arrays.stream(strArr)
.distinct()
.collect(Collectors.joining(","));
}
private String getAcsName(String origin) {
String[] beforeArr = this.getRemovedDuplicateName(origin).split(",");
return Arrays.stream(beforeArr)
.sorted()
.collect(Collectors.joining(","));
}
}
namestr = '이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌'
namelist = namestr.split(',')
def df(x):
count_lee = 0
count_kim = 0
for a in x:
if a[0] == '김':
count_kim += 1
elif a[0] == '이':
count_lee +=1
print(f'이씨는 {count_lee}명, 김씨는 {count_kim}명')
# 1번답
df(namelist)
# # 2번답
namelist.count('이재영')
# # 3,4 번답
namelist_unique =list(set(namelist))
namelist_unique.sort()
str(namelist_unique)
# Codingdojang 24
a=['이유덕','이재영','권종표','이재영','박민호','강상희','이재영',
'김지완','최승혁','이성연','박영서','박민호','전경헌','송정환',
'김재성','이유덕','전경헌']
#q_1
a_len=len(a)
b=[]
for i in range(a_len):
if a[i][0]=='이':
b.append(a[i][0])
count_lee=len(b)
print("1.이씨 성의 이름 수 : %d"%count_lee)
#q_2
count_ljy=a.count('이재영')
print("2.이재영 이름 수 : %d"%count_ljy)
#q_3
duplicate=list(set(a))
print("3.중복재거 list :")
print(duplicate)
#q_4
duplicate.sort()
print("4.중복재거 및 오름차순 : ")
print(duplicate)
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
String str = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌";
String[] strArr = str.split(",");
String str_re = "";
int kimCount = 0;
int leeCount = 0;
int ljyCount = 0;
for (int s = 0; s < strArr.length; s++) {
if (strArr[s].indexOf("김") == 0) {
kimCount++;
}
if (strArr[s].indexOf("이") == 0) {
leeCount++;
}
if (strArr[s].equals("이재영")) {
ljyCount++;
}
if (str_re.indexOf(strArr[s]) < 0) {
if (str_re == "") {
str_re += strArr[s];
} else {
str_re += "," + strArr[s];
}
}
}
String[] strArr_re = str_re.split(",");
Arrays.sort(strArr_re);
System.out.println("김씨와 이씨는 각각 몇 명 인가요?");
System.out.println("김씨 : " + kimCount + "명\r이씨 : " + leeCount + "명\r");
System.out.println("\"이재영\"이란 이름이 몇 번 반복되나요?");
System.out.println(ljyCount + "번\r");
System.out.println("중복을 제거한 이름을 출력하세요.");
System.out.println(str_re + "\r");
System.out.println("중복을 제거한 이름을 오름차순으로 정렬하여 출력하세요.");
System.out.println(Arrays.toString(strArr_re));
}
}
import re
def solve(str):
firstLee=re.findall('이[가-힣]{1,3}',str)
firstKim=re.findall('김[가-힣]{1,3}',str)
print('1.',firstKim, '%d명'%len(firstKim))
print(firstLee, '%d명'%len(firstLee))
LJY=re.findall('이재영',str)
print('\n2.',LJY,'%d번'%len(LJY))
overlapped=list(set(re.findall('[가-힣]{1,4}',str)))
print('\n3.',overlapped)
sorted=overlapped
sorted.sort()
print('\n4.',sorted)
return (len(firstLee),len(firstKim)),len(LJY),overlapped,sorted
names = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌".split(',')
# 1번 문제
kim_count = 0
lee_count = 0
for i in range(len(names)):
if names[i][0] == '김':
kim_count += 1
if names[i][0] == '이':
lee_count += 1
print("김씨 : %d명, 이씨 : %d명" %(kim_count, lee_count))
# 2번 문제
jaeyoung_count = 0
for i in range(len(names)):
if names[i] == "이재영":
jaeyoung_count += 1
# 3번 문제
filters = []
for i in range(len(names)):
if names[i] not in filters:
filters.append(names[i])
print(filters)
# 4번 문제
print(sorted(filters))
완료~
names = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌"
name_list = names.split(',')
lee = 0
kim = 0
for i in name_list:
if str(i[0]) == '이':
lee += 1
elif str(i[0]) == '김':
kim += 1
else:
pass
print(f"이씨는 {lee}명 김씨는 {kim}명 입니다.")
print(f"이재영은 {names.count('이재영')}번 반복됩니다.")
name_one = list(set(name_list))
sorted(name_one)
"""
* 입력 파라메터
- names: 입력 데이터 , list 를 입력으로 받는다.
- get_key : callback 함수, key를 추출한다.
* return : dictionary
- key: get_key callback 함수로 생성된 키(성 또는 전체 이름)
- value : 회수
"""
def count_name(names, get_key ):
result = {}
for n in names:
key = get_key(n)
if key not in result:
result[key] =0
result[key] = result[key] + 1
return result
input ="이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌"
print("입력:",input)
input_names = input.split(",")
# 이름별 회수 계산
full_names = count_name(input_names,lambda x : x)
# 성별
last_names = count_name(input_names,lambda x : x[0])
print('출력')
print("김씨:",last_names['김'],",이씨:",last_names["이"])
print('이재영:',full_names["이재영"])
print("중복제거:",list(full_names.keys()))
print("중복제거 및 정렬:",sorted(full_names.keys()))
Python
names="이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌"
namelist=names.split(",") #쉼표 기준으로 나누어 리스트화
last_list=[] #성씨만 모아서 리스트화
for i in namelist:
if i[0]=='김' or '이':
last_list.append(i[0])
ljy=[] #이재영 동명이인 리스트화
for i in namelist:
if i == '이재영':
ljy.append(i)
print("김씨 성을 가진 사람의 수는 %s명, " %last_list.count('김')+"이씨 성을 가진 사람의 수는 %s명입니다." %last_list.count('이')) #과제 1 출력
print("'이재영'이라는 이름은 %d번 반복됩니다." %ljy.count('이재영')) #과제 2 출력
group_nonOverlap=set(namelist) #이름 리스트를 집합으로 바꾸어 중복 제거
namelist_nonOverlap=list(group_nonOverlap) #중복 제거한 이름 집합을 다시 리스트로
print(namelist_nonOverlap) #과제 3 출력
print(sorted(namelist_nonOverlap)) #과제 4 출력
names = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌".split(',')
count_lee = 0
count_kim = 0
count_ljy = 0
double_name = []
for name in names:
if name[0] == '김':
count_kim += 1
elif name[0] == '이':
count_lee += 1
print('김씨는 ' + str(count_kim) + '명입니다.')
print('이씨는 ' + str(count_lee) + '명입니다.')
for name in names:
if name == '이재영':
count_ljy +=1
print('이재영은 ' + str(count_ljy) + '명입니다.')
for name in names:
if name in double_name:
pass
else:
double_name.append(name)
print(double_name)
double_name.sort()
print(double_name)
name = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌"
name_list = name.split(",")
name_list2 = list(set(name_list))
# 김씨와 이씨는 각각 몇 명 인가요?
kim = 0
lee = 0
for a in name_list2:
if a[0] == "김":
kim += 1
elif a[0] == "이":
lee += 1
print("김씨는 {}명, 이씨는 {}명".format(kim,lee))
# "이재영"이란 이름이 몇 번 반복되나요?
LJY = 0
for b in name_list:
if b == "이재영":
LJY += 1
print("이재영은 {}번 반복됩니다.".format(LJY))
# 중복을 제거한 이름을 출력하세요.
print(name_list2)
# 중복을 제거한 이름을 오름차순으로 정렬하여 출력하세요.
name_list2.sort()
print(name_list2)
names = ["이유덕","이재영","권종표","이재영","박민호","강상희","이재영","김지완","최승혁","이성연","박영서","박민호","전경헌","송정환","김재성","이유덕","전경헌"]
# 1
a = [i[0] for i in names]
print(a.count("이"),a.count("김"))
# 2
print(names.count("이재영"))
# 3
print(list(set(names)))
# 4
list(set(names)).sort()
names = '이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌'.split(',')
#1
kimcount = 0
leecount = 0
for i in names:
if i[0] == '김':
kimcount += 1
elif i[0] == '이':
leecount += 1
print(f'김씨: {kimcount}명, 이씨: {leecount}명')
#2
ljy = names.count('이재영')
print(f'이재영: {ljy}명')
#3
a = list(set(names))
print(a)
#4
print(sorted(a))
namelist = '이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌'.split(",")
def namefun(namelist): a=0 for i in namelist: if i[0].find('김') >=0 or i[0].find('이') >= 0: a += 1 b = namelist.count("이재영") c = set(namelist) d = sorted(c)
return print(f"{a} 명",'\n',f"{b} 명",'\n',c,'\n',d)
namefun(namelist)
#문자열
mylist = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌"
mylist = mylist.split(",")
#1 이씨, 김씨 찾기
lee = 0
kim = 0
for i in range(len(mylist)-1):
kim += mylist[i].count("김",0)
lee += mylist[i].count("이",0)
print("김씨: ",kim,"명")
print("이씨: ",lee,"명")
#2 이재영 찾기
count_ljy = 0
for i in range(len(mylist)-1):
if mylist[i]=="이재영":
count_ljy += 1
print(count_ljy,"번")
#3 중복 제거
mylist = list(set(mylist))
print(mylist)
#4 오름차순
print(sorted(mylist))
i = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌"
arri = [n for n in i.split(',')]
kims = [o for o in arri if o.startswith('김')]
lees = [o for o in arri if o.startswith('이')]
removedupli = set(arri)
sorted = list(removedupli)
sorted.sort()
print("1.김씨와 이씨는 각각 몇 명 인가요?", len(kims), len(lees))
print('2."이재영"이란 이름이 몇 번 반복되나요?', arri.count('이재영'))
print("중복을 제거한 이름을 출력하세요.", set(arri))
print("중복을 제거한 이름을 오름차순으로 정렬하여 출력하세요.", sorted)
#1
a = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌"
b = a.split(",")
c= len(b)
p = 0
o = 0
for i in range(0,c):
if b[i][0] == "이":
p = p + 1
print(p)
#2
u = b.count("이재영")
print(u)
#3
h = list(set(b))
print(h)
#4
h.sort()
Python
name = '이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌'
nameList = name.split(',')
# 1) 김씨와 이씨는 각각 몇 명 인가요?
ck = 0
cl = 0
for i in range(len(nameList)):
if nameList[i][0] == '김':
ck += 1
elif nameList[i][0] == '이':
cl += 1
print('김씨: {}명, 이씨: {}명'.format(ck, cl))
# 2) "이재영"이란 이름이 몇 번 반복되나요?
cljy = 0
for i in range(len(nameList)):
if nameList[i] == '이재영':
cljy += 1
print('이재영: {}번'.format(cljy))
# 3) 중복을 제거한 이름을 출력하세요.
newList = []
for i in range(len(nameList)):
if nameList[i] in nameList[0:i]:
pass
else:
newList.append(nameList[i])
res = ''
for new in newList:
res += (new + ',')
print(res[:-1])
rres = ''
# 4)중복을 제거한 이름을 오름차순으로 정렬하여 출력하세요.
nnewList = sorted(newList)
for new in nnewList:
rres += (new + ',')
print(rres[:-1])
string='이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌'
L1=[];
a=-1
for i in range(len(string)):
if string[i]==',':
L1.append(string[a+1:i])
a=i
b=0; c=0
for i in range(len(L1)):
if L1[i][0]=='김':
b+=1
elif L1[i][0]=='이':
c+=1
print('1. 김씨와 이씨는 각각 몇 명 인가요?\n%d명, %d명' %(b, c))
b=0
for i in range(len(L1)):
if L1[i]=='이재영':
b+=1
print('2. "이재영"이란 이름이 몇 번 반복되나요?\n%d번' %b)
print('3. 중복을 제거한 이름을 출력하세요.')
S=set(L1)
L1=list(S)
for i in range(len(L1)):
print(L1[i], end=' ')
print('\n4. 중복을 제거한 이름을 오름차순으로 정렬하여 출력하세요.')
for i in range(len(L1)):
print(sorted(L1)[i], end=' ')
names = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌"
a = [ i[0] for in in names ] print("김씨 : %d\n이씨 : %d\n"%(a.count("김"), a.count("이")))
print(names.count("이재영"))
uniq_names = list(set(names)) print(uniq_names)
uniq_names.sort() print(uniq_names)
name=['이유덕','이재영','권종표','이재영',
'박민호','강상희','이재영','김지완','최승혁','이성연','박영서',
'박민호','전경헌','송정환','김재성','이유덕','전경헌']
#김씨와 이씨 몇 명인지 출력하기. 이재영 몇 번 반복출력?
count=0
leecount=0
kimcount=0
for i in range(0,len(name)):
if name[i][0]=="이":
leecount+=1
elif name[i][0]=="김":
kimcount+=1
print("이씨는 {}명이고 김씨는 {}명 입니다.".format(leecount,kimcount))
for i in range(0,len(name)):
if name[i]=="이재영":
count+=1
print("이재영 이름은 %d 번 반복됩니다."%count)
#중복을 제거한 이름을 출력하세요.
result=list(set(name))
print(result)
#오름차순으로 정렬하시오
print(sorted(result))
1
name_list=list(input().split(',')) count_first_name=0 for i in name_list: if i[0]=='김' or i[0]=='이': count_first_name+=1
print(count_first_name)
2
name_list=list(input().split(',')) count_name=0 for i in name_list: if i=="이재영": count_name+=1
print(count_name)
3
name_list=list(input().split(',')) count_name=0 for i in name_list: if i=="이재영": count_name+=1 for i in range(count_name-1): name_list.remove("이재영")
print(name_list)
4
name_list=list(input().split(',')) count_name=0 for i in name_list: if i=="이재영": count_name+=1 for i in range(count_name-1): name_list.remove("이재영") name_list.sort() print(name_list)
names = ['이유덕','이재영','권종표','이재영','박민호','강상희','이재영','김지완','최승혁','이성연','박영서','박민호','전경헌','송정환','김재성','이유덕','전경헌']
kim = 0
Lee = 0
LJY = 0
for i in range(len(names)):
if names[i][0] == '김':
kim +=1
elif names[i][0] == '이':
Lee +=1
if names[i] == "이재영":
LJY +=1
print(f"kim{kim} Lee{Lee}")
print(f"LJY{LJY}")
names_set = list(set(names))
print(names_set)
names_set.sort()
print(names_set)
str_name = '이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌'
list_name = str_name.split(',')
#1. 김씨와 이씨는 각각 몇 명 인가요?
count_le = 0
count_kim = 0
for i in list_name :
if i[0] == '이':
count_le += 1
if i[0] == '김':
count_kim += 1
print('이씨 : {}'.format(count_le))
print('김씨 : {}'.format(count_kim))
#2. "이재영"이란 이름이 몇 번 반복되나요?
count = 0
count = list_name.count('이재영')
print('이재영 : {}'.format(count))
#3. 중복을 제거한 이름을 출력하세요.
non_dup_list = []
for i in list_name:
if i not in non_dup_list:
non_dup_list.append(i)
print('중복제거 : {}'.format(non_dup_list))
#4. 중복을 제거한 이름을 오름차순으로 정렬하여 출력하세요.
non_dup_list.sort()
print('오름차순 정렬 : {}'.format(non_dup_list))
b = ("이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌").split(",")
count_kim, count_lee, count_LJY = 0, 0, 0
new_list = []
for idx in b:
if idx[0] == "김":
count_kim += 1
elif idx[0] == "이":
count_lee += 1
#1
print("김씨는 {}명, 이씨는 {}명".format(count_kim, count_lee))
for idx in b:
if idx == "이재영":
count_LJY += 1
#2
print("이재영은 {}번 반복".format(count_LJY))
#3
for idx in b:
if idx not in new_list:
new_list.append(idx)
print(new_list)
#4
new_list.sort()
print(new_list)
s="이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌"
llist=s.split(',')
print("1. 김씨와 이씨는 각각 몇 명 인가요? ")
kim=0
lee=0
for i in llist:
if i[0]=='김':
kim+=1
if i[0]=='이':
lee+=1
print("%d명, %d명" %(kim,lee))
print("2.\"이재영\"이란 이름이 몇 번 반복되나요? ")
j=0
for i in llist:
if i=='이재영':
j+=1
print('%d번'%j)
print("3. 중복을 제거한 이름을 출력하세요 ")
name=list(set(llist))
print(name)
print("4. 중복을 제거한 이름을 오름차순으로 정렬하여 출력하세요. ")
name.sort()
print(name)
import java.lang.*;
import java.util.*;
public class SelfTest_4 {
public static void main(String[] args) {
int check=0, check2=0;
int count=0;
String name="이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌";
String[] ArrayStr = name.split(",");
for(String s : ArrayStr){
// System.out.println(s);
if(s.charAt(0)=='김'){
check += 1;
};
if(s.charAt(0)=='이'){
check2 +=1;
}
if(s.compareTo("이재영")==0){
count += 1;
}
}
String[] resultArr = Arrays.stream(ArrayStr).distinct().toArray(String[]::new);
System.out.println("김씨는 " + check + "명 입니다.");
System.out.println("이씨는 " + check2 + "명 입니다.");
System.out.println("'이재영' 이라는 이름은 " + count + "번 반복 됩니다.");
System.out.println(Arrays.toString(resultArr));
Arrays.sort(resultArr);
System.out.println(Arrays.toString(resultArr));
}
}
s = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌" arr = list(s.split(","))
print(len([s for s in arr if s[0] == '이' or s[0] =='김']))
print(len([s for s in arr if s == "이재영"]))
print(set(arr))
print(sorted(set(arr)))
package codingstamp.ex024_Lv1_cantSolve;
import java.util.ArrayList;
import java.util.Arrays;
public class trialAndError {
public static void main(String[] args) {
String names = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌";
String[] nameList = names.split(",");
ArrayList<String> nameArrayList = new ArrayList<>();
int IjyCounts = 0, Kim = 0, Lee = 0;
for(String s : nameList) {
if(s.equals("이재영")) {
IjyCounts++;
}
if(! nameArrayList.contains(s)) {
nameArrayList.add(s);
}
}
for(String f : nameArrayList) {
if(f.startsWith("김")) {
Kim++;
}
if(f.startsWith("이")) {
Lee++;
}
}
String[] finalNameList = nameArrayList.toArray(new String[0]);
System.out.printf("1. 김 씨는 %d명이고, 이 씨는 %d명이다.\n", Kim, Lee);
System.out.printf("2. 이재영은 총 %d번 반복된다.\n", IjyCounts);
System.out.print("3. ");
for(int k = 0; k < nameArrayList.size(); k++) {
System.out.print(finalNameList[k] + ((finalNameList.length == k + 1) ? "\n":","));
}
System.out.print("4. ");
Arrays.sort(finalNameList);
for(int k = 0; k < nameArrayList.size(); k++) {
System.out.print(finalNameList[k] + ((finalNameList.length == k + 1) ? "\n":","));
}
}
}
다른 분 코드를 많이 참고하였고, 4번만에 성공했습니다. 참고로 저는 김 씨와 이 씨가 몇 명인지를 미리 중복 제거 처리한 후 구했습니다.
public class Test12 {
public static void main(String[] args) {
//주어진 문자열(공백 없이 쉼표로 구분되어 있음)을 가지고 아래 문제에 대한 프로그램을 작성하세요.
//이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌
//김씨와 이씨는 각각 몇 명 인가요?
//"이재영"이란 이름이 몇 번 반복되나요?
//중복을 제거한 이름을 출력하세요.
//중복을 제거한 이름을 오름차순으로 정렬하여 출력하세요.
String names = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,"
+ "최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌";
int kimCount = 0;
int leeCount = 0;
int leeJaeYoung = 0;
String[] nameArray = names.split(",");
List<String> uniqueNames = new ArrayList<>();
Set<String> uniqueNamesSet = new HashSet<>();
for (String name : nameArray) {
if(name.startsWith("김")) {
kimCount++;
}
else if(name.startsWith("이")) {
leeCount++;
if(name.equals("이재영")) {
leeJaeYoung++;
}
}
uniqueNamesSet.add(name);
}
uniqueNames.addAll(uniqueNamesSet);
System.out.println("김씨는 " + kimCount +"명 입니다");
System.out.println("이씨는 " + leeCount +"명 입니다");
System.out.println("이재영은 " + leeJaeYoung +"번 반복됩니다");
uniqueNames.sort(null);
System.out.println("중복을 제거한 이름을 오름차순으로 정렬: " + uniqueNames);
}}
a='이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌'
a=list(a.split(','))
#Q1
result=0
for i in a:
if i[0]=='김' or i[0]=='이':
result+=1
print(result)
#Q2.
print(a.count('이재영'))
#Q3,4
a_set=list(set(a))
a_set_sorted=sorted(a_set)
print(a_set)
print(a_set_sorted)
### names = ['이유덕','이재영','권종표','이재영','박민호','강상희','이재영','김지완','최승혁','이성연','박영서','박민호','전경헌','송정환','김재성','이유덕','전경헌']
names = list(input().split(','))
kims, lees, ljy = 0, 0, 0
for name in names:
if name.startswith('김'):
kims += 1
elif name.startswith('이'):
lees += 1
if name == '이재영':
ljy += 1
print('Kims: ', kims, 'Lees: ', lees)
print('이재영 수: ', ljy)
nameSet = set(names)
print(list(nameSet))
nameSetSorted = sorted(list(nameSet))
print(nameSetSorted)
data = ['leeud','leejy',kwonjp','leejm','barkmh','kangsh','leejm','kimjw','choish','leesy','barksy','barkmh','junkh','songjh','kimjs','leeud','junkh']
kim = 0;bark = 0
for i in data:
if i[:3] == 'kim':
kim += 1
elif i[:3] == 'bak':
bark += 1
print('kim:',kim,'bark',bar)
print('Leejy:',data.count('leejy')
data2 = list(set(data))
print(data2)
data2.sort()
print(data2)
datas = ['이유덕','이재영','권종표','이재영','박민호','강상희','이재영','김지완','최승혁','이성연','박영서','박민호','전경헌','송정환','김재성','이유덕','전경헌']
last_names = [data[0] for data in datas]
print('김: ', last_names.count('김'))
print('이: ', last_names.count('이'))
print('이재영: ',datas.count('이재영'))
print(set(datas))
print(sorted(list(set(datas))))
name_list = [
'Lee Yu-deok', 'Lee Jae-young', 'Kwon Jong-pyo', 'Lee Jae-young',
'Park Min-ho', 'Kang Sang-hee', 'Lee Jae-young', 'Kim Ji-wan',
'Choi Seung-hyuk', 'Lee Seong-yeon', 'Park Young-seo', 'Park Min-ho',
'Jeon Kyeong-heon', 'Song Jeong-hwan', 'Kim Jae-seong', 'Lee Yu-deok',
'Jeon Kyeong-heon'
]
def kimlee():
count = 0
for name in name_list:
if 'Kim' in name or 'Lee' in name:
count += 1
return count
def jyl():
count = 0
for jyl in name_list:
if 'Lee Jae-young' in jyl:
count += 1
return count
def name_rem():
v2 = list(set(name_list))
#new_v
#for name in name_list
#if name not in name_list
#new_v.append(name)
return v2
def final():
v2 = sorted(list(set(name_list)))
return v2
print(kimlee())
print(jyl())
print(name_rem())
print(final())
names = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,\
최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌".split(",")
김_cnt, 이_cnt = 0, 0
이재영_cnt = 0
set_names = []
for n in names:
if n[0]=='김': 김_cnt += 1
if n[0]=='이': 이_cnt += 1
if n =='이재영': 이재영_cnt += 1
if n not in set_names: set_names.append(n)
print('김씨 %d 명 ' %김_cnt)
print('\n이씨 %d 명' %이_cnt)
print('\n"이재영"이란 이름 %d 번 반복' %이재영_cnt)
print('\n중복을 제거한 이름\n', set_names)
print('\n중복을 제거한 이름을 오름차순으로 정렬\n', sorted(set_names))
namelist = '이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌'
namelist = namelist.split(',')
kimnum = 0
leenum = 0
leejaeyoung = 0
import re
p = re.compile('^김')
m = re.compile('^이')
a = re.compile('이재영')
for name in namelist:
if p.match(name):
kimnum += 1
if m.match(name):
leenum += 1
if a.match(name):
leejaeyoung += 1
print(kimnum)
print(leenum)
print(leejaeyoung)
s1 = set(namelist)
namelist = list(s1)
print(namelist)
namelist.sort()
print(namelist)
package codingdojang;
import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap;
public class Synapsoft {
public static void main(String[] args) {
String names = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌";
String[] nameList = names.split(",");
ArrayList
for (int i = 0; i < nameList.length; i++) {
// 1. 김 씨와 이 씨는 각각 몇 명인가요?
String firstName = nameList[i].substring(0, 1);
if (hm.containsKey(firstName)) {
hm.put(firstName, hm.get(firstName) + 1);
} else {
hm.put(firstName, 1);
}
// 2. 이재영이란 이름이 몇 번 반복되나요?
if (nameList[i].equals("이재영")) {
count_ljy += 1;
}
// ArrayList에 중복을 제거하고 이름을 추가
if (!nameListArray.contains(nameList[i])) {
nameListArray.add(nameList[i]);
}
}
System.out.println(hm.get("이")); // 이 씨 성을 가진 인원 수
System.out.println(hm.get("김")); // 박 씨 성을 가진 인원 수
System.out.println(count_ljy); // 이재영이란 이름이 몇 번 반복되는가?
String[] nameArr = nameListArray.toArray(new String[nameListArray.size()]);
// 3. 중복을 제거한 이름을 출력하세요.
for (String s : nameArr) {
System.out.print(s + " ");
}
System.out.println();
Arrays.sort(nameArr);
// 4. 중복을 제거한 이름을 오름차순으로 정렬하여 출력하세요
for (String s : nameArr) {
System.out.print(s + " ");
}
}
}
package codingdojang;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
public class Synapsoft {
public static void main(String[] args) {
String names = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌";
String[] nameList = names.split(",");
ArrayList<String> nameListArray = new ArrayList<String>();
HashMap<String, Integer> hm = new HashMap<>();
int count_ljy = 0;
for (int i = 0; i < nameList.length; i++) {
// 1. 김 씨와 이 씨는 각각 몇 명인가요?
String firstName = nameList[i].substring(0, 1);
if (hm.containsKey(firstName)) {
hm.put(firstName, hm.get(firstName) + 1);
} else {
hm.put(firstName, 1);
}
// 2. 이재영이란 이름이 몇 번 반복되나요?
if (nameList[i].equals("이재영")) {
count_ljy += 1;
}
// ArrayList에 중복을 제거하고 이름을 추가
if (!nameListArray.contains(nameList[i])) {
nameListArray.add(nameList[i]);
}
}
System.out.println(hm.get("이")); // 이 씨 성을 가진 인원 수
System.out.println(hm.get("김")); // 박 씨 성을 가진 인원 수
System.out.println(count_ljy); // 이재영이란 이름이 몇 번 반복되는가?
String[] nameArr = nameListArray.toArray(new String[nameListArray.size()]);
// 3. 중복을 제거한 이름을 출력하세요.
for (String s : nameArr) {
System.out.print(s + " ");
}
System.out.println();
Arrays.sort(nameArr);
// 4. 중복을 제거한 이름을 오름차순으로 정렬하여 출력하세요
for (String s : nameArr) {
System.out.print(s + " ");
}
}
}
name="이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌"
num1,num2,i=0,0,0
while i <= len(name):
if name[i] == "이":
num2 = num2 + 1
i = i + 4
elif name[i] == "김":
num1 = num1 + 1
i = i + 4
else:
i = i + 4
print("1번. 김씨:",num1,",이씨:",num2)
print("2번.",name.count("이재영"))
name=name.split(",")
name=set(name)
print("3번.",list(name))
name=list(name)
name.sort()
print("4번.",name)
names = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌"
names_split = names.split(',')
count_kim = 0
count_lee = 0
for i in names_split:
if i.startswith('김'):
count_kim += 1
elif i.startswith('이'):
count_lee += 1
else:
pass
print(f"김씨 : {count_kim}",f"이씨 : {count_lee}",sep = "\n")
print(f"이재영 : {names_split.count('이재영')}")
names_set = set(names_split)
print(names_set)
names_modified_list = list(names_set)
names_modified_list.sort()
print(names_modified_list)
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
public class synapsoftInterview {
public static void main(String[] args) {
String[] arr = new String[]{"이유덕", "이재영", "권종표", "이재영", "박민호", "강상희", "이재영", "김지완", "최승혁",
"이성연", "박영서", "박민호", "전경헌", "송정환", "김재성", "이유덕", "전경헌"}; // String 배열 초기화
// set으로 중복제거 하는 방법//
Set<String> set = new HashSet<>(Arrays.asList(arr));
String[] uniqueArray = set.toArray((new String[0]));
int countKim =0;
int countLee = 0;
int countNum = 0;
for (int i = 0; i < arr.length ; i++){
if(arr[i].contains("김")){
countKim++;
}
else if(arr[i].contains(("이"))){
countLee++;
}
}
for (int i = 0; i < arr.length; i++) {
if(arr[i].contains("이재영")){
countNum++;
}
}
System.out.println("김씨는 " + countKim + "명이고 " + "이씨는" + countLee + "명입니다.");
System.out.println("이재영이란 이름은 총 " + countNum + "번 반복됩니다.");
System.out.println("중복을 제거한 배열: " +Arrays.toString(uniqueArray));
Arrays.sort(uniqueArray);
System.out.println("중복을 제거한 오름 차순 배열:" +Arrays.toString(uniqueArray));
}
}
names = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌"
names_list = names.split(",")
# 김씨와 이씨는 각각 몇 명 인가요?
Kim_count = 0
Lee_count = 0
for name in names_list:
if name.startswith("김"):
Kim_count += 1
elif name.startswith("이"):
Lee_count += 1
print(f"김씨 {Kim_count}명, 이씨는 {Lee_count}명")
# "이재영"이란 이름이 몇 번 반복되나요?
print(f"이재영은 {names_list.count("이재영")}번 반복")
# 중복을 제거한 이름을 출력하세요.
set_names_list = set(names_list)
print (set_names_list)
#중복을 제거한 이름을 오름차순으로 정렬하여 출력하세요.
set_names_list = list(set_names_list)
set_names_list.sort()
print(set_names_list)
name = '이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌'
cntStartswith = lambda x: sum([n.startswith(x) for n in name.split(',')])
print(f"1. 김씨: {cntStartswith('김')}명, 이씨: {cntStartswith('이')}명")
print(f"2. 이재영: {cntStartswith('이재영')}명")
print(f"3. 중복제거이름: {list(set(name.split(',')))}")
print(f"4. 중복제거이름 오름차순 정렬: {sorted(list(set(name.split(','))))}")
> 1. 김씨: 2명, 이씨: 6명
> 2. 이재영: 3명
> 3. 중복제거이름: ['강상희', '이재영', '박민호', '이유덕', '김재성', '최승혁', '김지완', '이성연', '송정환', '권종표', '전경헌', '박영서']
> 4. 중복제거이름 오름차순 정렬: ['강상희', '권종표', '김재성', '김지완', '박민호', '박영서', '송정환', '이성연', '이유덕', '이재영', '전경헌', '최승혁']
import re
q_1 = len(re.findall('김',names)) + len(re.findall('이',names))
q_2 = len(re.findall('이재영',names))
q_3 = set(names.split(','))
q_4 = sorted(q_3)
print(q_1)
print(q_2)
print(q_3)
print(q_4)
JAVA입니다.
package question2.사이냅소프트_면접문제;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
String input =
"이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌";
Set<String> nameSet = new HashSet<String>();
String[] names = input.split(",");
int kim = 0, lee = 0;
int leeJaeYoung = 0;
for (String name : names) {
nameSet.add(name);
if(name.substring(0, 1).equals("김")) {
kim++;
}
if(name.substring(0, 1).equals("이")) {
lee++;
}
if(name.equals("이재영")) {
leeJaeYoung++;
}
}
List<String> singleNames = new ArrayList<String>();
for (String string : nameSet) {
singleNames.add(string);
}
Collections.sort(singleNames);
System.out.println("김씨: " + kim + "명");
System.out.println("이씨: " + lee + "명");
System.out.println("이재영: " + leeJaeYoung + "명");
for (int i = 0; i < nameSet.toArray().length; i++) {
System.out.print(nameSet.toArray()[i]);
if(i != nameSet.toArray().length - 1) {
System.out.print(",");
}
}
System.out.println("");
for (int i = 0; i < singleNames.size(); i++) {
System.out.print(singleNames.get(i));
if(i != singleNames.size() - 1) {
System.out.print(",");
}
}
}
}
#list 함수:
def LName_Count(name_List, last_Name):
counter = 0
for name in name_List:
if name[0] == last_Name:
counter += 1
return counter
def name_Count(name_List, name):
cnt = 0
for n in name_List:
if n == name:
cnt += 1
return cnt
def dup_Name(name_List):
name = []
for n in name_List:
if name_List.count(n) > 1:
name.append(n)
return name
def delete_Dup(name_List):
for name in name_List:
if name_List.count(name) > 1:
name_List.remove(name)
return name_List
def lst_str(a):
resultStr = ""
for i in a:
resultStr += (i + " ")
return resultStr
names = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌"
list_name = names.split(',')
kim_Count = LName_Count(list_name, '김')
lee_Count = LName_Count(list_name, '이')
print(f"1. 김씨는 {kim_Count}명 입니다. 이씨는 {lee_Count}명 입니다.")
ljy_cnt = name_Count(list_name, '이재영')
print(f"2. 이재영은 {ljy_cnt}번 반복 됩니다.")
dupl_Name = dup_Name(list_name)
uniqDup_Name = set(dupl_Name)
duppedNames = lst_str(uniqDup_Name)
print(f"3. 중복된 이름들은 {duppedNames}입니다.")
uniq_Name = delete_Dup(list_name)
uniqName_str = lst_str(uniq_Name)
print(f"3. 중복된 이름 없는 리스트는 {uniqName_str}입니다.")
uniq_Name.sort()
sortedStr = lst_str(uniq_Name)
print(f"4. 오름차순으로 정렬된 리스트 출력 {sortedStr}")
함수 사용 그리고 깔끔한 포맷팅을 초점으로 두고 만들었습니다.
file=open("이름 리스트.txt","r")
list_name=file.readline().split(',')
file.close()
print(list_name)
kim_count=0
for a in range(len(list_name)):
if '김'==list_name[a][0:1]:
kim_count+=1
print('1:김씨:',kim_count)
lee_count=0
for a in range(len(list_name)):
if '이'==list_name[a][0:1]:
lee_count+=1
print('1:이씨:',lee_count)
lee_jae_young_count=0
for a in range(len(list_name)):
if '이재영'==list_name[a]:
lee_jae_young_count+=1
print('2:이재영:',lee_jae_young_count)
set_name=set(list_name)
print('3:',set_name)
list_set_ascending_order_name=list(set_name)
list_set_ascending_order_name.sort()
print('4:',list_set_ascending_order_name)
name = """이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌"""
#1
name.count("김")
#2
name.count("이재영")
#3
nameList = list(name.split(","))
nameR=list(set(nameList))
print(nameR)
#4
nameR.sort()
print(nameR)
interviewee = "이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌"
def find_name(a):
surnames = list(map(lambda x : x[0],a.split(",")))
f_surnames = (input("찾으려는 사람의 성은?:")).split(",")
counts = list(map(lambda x : surnames.count(x),f_surnames))
result = { f"{n} : {c}" for n, c in zip(f_surnames, counts)}
unique_name = set(a.split(","))
unique_name_sorted = sorted(unique_name)
final_output = (
f"[성별 카운트]\n{result}\n\n"
f"[중복 제거]\n{unique_name}\n\n"
f"[정렬]\n{unique_name_sorted}"
)
return final_output
print(find_name(interviewee))
data = '이유덕,이재영,권종표,이재영,박민호,강상희,이재영,김지완,최승혁,이성연,박영서,박민호,전경헌,송정환,김재성,이유덕,전경헌'.split(',')
# 1
kim = [name for name in data if name.startswith('김')]
lee = [name for name in data if name.startswith('이')]
print(f'Kim: {len(kim)}, Lee: {len(lee)}')
# 2
print(f'Count: {data.count('이재영')}')
# 3
print(', '.join(set(data)))
# 4
print(', '.join(sorted(set(data))))