리스트에 있는 숫자들의 최빈값을 구하는 프로그램을 만들어라.
[12, 17, 19, 17, 23] = 17
[26, 37, 26, 37, 91] = 26, 37
[28, 30, 32, 34, 144] = 없다
최빈값 : 자료의 값 중에서 가장 많이 나타난 값
① 자료의 값이 모두 같거나 모두 다르면 최빈값은 없다.
② 자료의 값이 모두 다를 때, 도수가 가장 큰 값이 1개 이상 있으면 그 값은 모두 최빈값이다.
36개의 풀이가 있습니다.
def mode(lst):
freq = {x:lst.count(x) for x in set(lst)}
if len(freq) == 1 or len(freq) == len(lst):
return None
else:
return [x for x in freq.keys() if freq[x] == max(freq.values())]
for lst in [[12, 17, 19, 17, 23], [26, 37, 26, 37, 91], [28, 30, 32, 34, 144]]:
print(lst, mode(lst))
import collections
def cb(list):
o = collections.Counter(list).most_common()
max,m = o[0][1],[]
for num in o:
if num[1] == max:m.append(num[0])
if len(m)==len(list):return '없음'
return m
print(cb([1,2,3,4,5,5]))
print(cb([1,2,3,4,4,5,5]))
print(cb([1,2,3,4,5]))
def mode(n):
Max = 0
for x in list(set(n)):
if n.count(x) > Max:
Max = n.count(x)
print(Max if Max <= 1 else 'None')
def mode(v):
tmp = set(v)
if len(tmp) in (1, len(v)): return None
cnt = {}
for i in tmp:
getcnt = v.count(i)
try : cnt[getcnt].append(i)
except: cnt[getcnt] = [i]
return cnt[max(cnt)]
public class Main {
public static void print(int a[])
{
int check[] =new int[a.length];
for(int i=0;i<a.length;i++)
{
check[i]=0;
}
int maxidx=0;
for(int i=0; i<a.length ;i++)
{
for(int j=i+1;j<a.length;j++)
{
if( a[i] == a[j])
{
check[i]++;
if(check[maxidx]<check[i])
{
maxidx=i;
}
}
}
}
if(check[maxidx] ==0)
{
System.out.println("없다.");
return;
}
for(int i=0;i<check.length;i++)
{
if(check[maxidx]==check[i])
{
System.out.printf("%d ",a[i]);
}
}
System.out.printf("\n");
}
public static void main(String[] args) {
// TODO Auto-generated method stub
int arr[] = {12, 17, 19, 17, 23};
int arr2[]={26, 37, 26, 37, 91};
int arr3[]={28, 30, 32, 34, 144};
print(arr);
print(arr2);
print(arr3);
}
}
C# Linq
class Program
{
static void Main(string[] args)
{
int[] ary1 = { 12, 17, 19, 17, 23, 23 }; // 17
int[] ary2 = { 26, 37, 26, 37, 91 }; // 26, 37
int[] ary3 = { 28, 30, 32, 34, 144 }; // 없다
int[] ary = ary3;
var hash = new HashSet<int>(ary);
//모두 다른 값 or 동일한 값인 경우 체크
if (hash.Count == ary.Length || hash.Count == 1)
{
Console.WriteLine("최빈 값이 없습니다.");
return;
}
var cntLists = from x in hash
join y in ary on x equals y
group x by x into gp
select new
{
Key = gp.Key,
Count = gp.Count()
};
int max = cntLists.Max(x => x.Count);
var resultList = from x in cntLists
where x.Count == max
select x;
foreach (var v in resultList)
{
Console.WriteLine($"{v.Key}: {v.Count}개" );
}
}
}
list1 = [[12, 17, 19, 17, 23],
[26, 37, 26, 37, 91],
[28, 30, 32, 34, 144]]
def mode(l1):
a1 = {x:l1.count(x) for x in set(l1)}
a2 = [a for a in a1.keys() if a1[a] == max(a1.values())]
return "없다" if len(a1) == len(a2) else a2
for l1 in list1:
print(l1, "=", mode(l1))
출력
[12, 17, 19, 17, 23] = [17]
[26, 37, 26, 37, 91] = [26, 37]
[28, 30, 32, 34, 144] = 없다
const arr = [12, 12, 12, 11];
const getMode = (arr) => {
let mostFrequentCnt = 1;
const mode = [];
const _map = new Map();
for (const item of arr) {
const hasValue = _map.get(item);
const cnt = hasValue === undefined ? 1: hasValue + 1;
_map.set(item, cnt);
}
for (const [key, value] of _map) {
if (value > mostFrequentCnt) {
mostFrequentCnt = value;
}
}
if (mostFrequentCnt === 1) return null;
for (const [key, value] of _map) {
if (value === mostFrequentCnt) {
mode.push(key);
}
}
if (mostFrequentCnt === arr.length) return null;
return mode;
};
if (getMode(arr)) {
console.log('최빈값:', getMode(arr).join(','));
} else {
console.log('없다');
}
import java.util.Arrays;
public class TEST07 {
public static void main(String[] args) {
int[] data1 = {12, 17, 19, 17, 23,23};
int[] data2 = {26, 37, 26, 37, 91};
int[] data3 = {28, 30, 32, 34, 144};
int[] max = maxShow(data1);
for (int i = 0; i < max.length; i++) {
if (max[i] != 0) {
System.out.print(max[i] + " ");
}
}
System.out.println(" ");
max = maxShow(data2);
for (int i = 0; i < max.length; i++) {
if (max[i] != 0) {
System.out.print(max[i] + " ");
}
}
System.out.println(" ");
max = maxShow(data3);
for (int i = 0; i < max.length; i++) {
if (max[i] != 0) {
System.out.print(max[i] + " ");
}
}
}
public static int[] maxShow(int[] data) {
Arrays.sort(data);
int[] value = new int[data.length];
int[] showCnt = new int[data.length];
int[] max = new int[data.length];
int cnt = 1;
int init = data[0];
int idx = 0;
for (int i = 1; i < data.length; i++) {
if (init == data[i]) {
cnt = cnt + 1;
}
else {
value[idx] = init;
showCnt[idx++] = cnt;
init = data[i];
cnt = 1;
}
if (i == (data.length - 1)) {
value[idx] = init;
showCnt[idx] = cnt;
}
}
idx = 0;
int max_value = searchMax(showCnt);
if (max_value == 1) {
return max;
}
for (int i = 0; i < showCnt.length; i++) {
if (max_value == showCnt[i]) {
max[idx++] = value[i];
}
}
return max;
}
public static int searchMax(int[] data) {
int max = 0;
for (int i = 0; i < data.length; i++) {
if (data[i] > max) {
max = data[i];
}
}
return max;
}
}
Ruby
def most_freq(arr)
hash = arr.reduce(Hash.new(0)) {|h,freq| h[freq] += 1; h}
mfreq = hash.select {|_,freq| freq == hash.values.max }
mfreq.rassoc(1) ? "not exist" : mfreq.one? ? mfreq.keys[0] : mfreq.map(&:first)
end
Test
expect( most_freq([12, 17, 19, 17, 23]) ).to eq 17
expect( most_freq([26, 37, 26, 37, 91]) ).to eq [26, 37]
expect( most_freq([28, 30, 32, 34, 144]) ).to eq "not exist"
from collections import Counter
def most_common(xs):
c = Counter(xs)
return [x for x, y in c.items() if y == c.most_common()[0][1]]
def freq(lista):
freqdic = {}
for i in lista:
total = 0
for j in lista:
if(i==j):
total += 1
freqdic[i] = total
return max(freqdic,key=freqdic.get)
clear
clc
%최빈값구하기(해당 함수 미사용)
n=input('벡터 입력:');
sortn=sort(n);%정렬
count=1;
c=1;
k=1;
for i=2:length(sortn)
if sortn(i)~=sortn(i-1)
if count>c
c=count;
freq=sortn(i-1);
count=1;
elseif count==c && count~=1
c=count;
freq(k)=freq;
freq(k+1)=sortn(i-1);
k=k+1;
count=1;
end
else
count=count+1;
end
end
if c==1 || count==length(n)
fprintf('최빈값은 없다\n');
elseif length(freq)>=2
fprintf('최빈값:\n');
disp(freq);
else
fprintf('최빈값: %d\n',freq);
end
def mode(lst):
cnt = {n:lst.count(n) for n in lst}
ret = [n for n in cnt.keys()
if cnt[n] == max(cnt.values()) and cnt[n] > 1]
return ret
for lst in [[12, 17, 19, 17, 23],
[26, 37, 26, 37, 91],
[28, 30, 32, 34, 144]]:
print(lst, mode(lst), sep=':')
sample = list(map(int, input().split()))
count_result = []
temp = []
tempresult = []
for i in sample:
count = 0
for j in sample:
if i == j:
count += 1
count_result.append(count)
compare = count_result[0]
for i in range(len(count_result) - 1):
if compare < count_result[i + 1]:
compare = count_result[i + 1]
for i in range(len(count_result)):
if compare == 1:
break
elif compare == count_result[i]:
tempresult.append(sample[i])
result = list(set(tempresult))
result.sort()
if result == []:
print('없다')
else:
print(result)
def max_freq(lst):
if len(set(lst)) != len(lst):
freq_dict = {}
for num in lst:
freq_dict[num] = 0
for num in lst:
freq_dict[num] += 1
reverse_tuple = sorted([(j, i) for i, j in freq_dict.items()], key = lambda x: x[0], reverse=True)
dup = 0
for i in range(1, len(reverse_tuple)):
if reverse_tuple[0][0] == reverse_tuple[i][0]:
dup += 1
freq_tuple = [reverse_tuple[i][1] for i in range(dup+1)]
return freq_tuple
else:
return '최빈값이 없습니다.'
C#
using System;
using System.Collections.Generic;
using System.Linq;
namespace CD187
{
internal class Program
{
private static void Main(string[] args)
{
List<int> testCase;
testCase = new List<int>() { 12, 17, 19, 17, 23 };
Console.WriteLine(Mode(testCase));
testCase = new List<int>() { 26, 37, 26, 37, 91 };
Console.WriteLine(Mode(testCase));
testCase = new List<int>() { 28, 30, 32, 34, 144 };
Console.WriteLine(Mode(testCase));
}
private static string Mode(List<int> list)
{
// 딕셔너리 구성(key = 숫자, value = 리스트 내의 개수)
var countDic = list.GroupBy(e => e).ToDictionary(g => g.Key, g => g.Count());
// 딕셔너리 아이템의 중복 개수가 중복 개수의 최대값과 동일한 아이템 개수 계산
int maxVal = countDic.Values.Max();
int criteria = countDic.Where(g => g.Value == maxVal).Select(g => g.Key).Count();
// 동일한 아이템 개수 == 리스트의 항목 개수인 경우(즉, 모두 같거나, 모두 다르거나) 최빈값 없음
string result = criteria == list.Count() ? "없다" :
// 그렇지 않은 경우 딕셔너리 키(리스트 항목)(들을) 반환
string.Join(", ", countDic.Where(g => g.Value == maxVal).Select(g => g.Key));
return result;
}
}
}
mylist = [40, 40, 26, 26, 4]
eval_list= [mylist.count(item) for item in mylist]
res = []
if max(eval_list) == 1:
print("No mode exists")
else:
for val in range(0,len(eval_list)):
if eval_list[val] == max(eval_list):
res.append(mylist[val])
for item in set(res):
print(item, end = " ")
def freq(a):
freqlist = []
freqset = set([])
result = {}
result2 = []
for i in a:
freqlist.append(i)
freqset.add(i)
if len(freqset) == len(freqlist):
return "없다"
else:
for j in freqlist:
c = freqlist.count(j)
result[j] = c
for k , l in result.items():
count = max(result.values())
if l == count:
result2.append(k)
print(result2)
def mode(n): Max = 0 for x in list(set(n)): if n.count(x) > Max: Max = n.count(x) print(Max if Max <= 1 else 'None')
java 입력받는 숫자의 개수는 10개이고, 입력값이 10000을 넘지않는 가정하에 품
import java.util.*;
public class q4 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
ArrayList<Integer> array = new ArrayList<>();
int[][] count = new int[10000][2];
for (int i = 0; i < 10; i++) {
array.add(sc.nextInt());
}
for (int i = 0; i < 10; i++) {
count[array.get(0)][1]++;
array.remove(0);
}
int max_count = 0;
for (int i = 0; i < 10000; i++) {
if (max_count < count[i][1]) {
max_count = count[i][1];
}
}
if (max_count == 1) {
System.out.println("없다");
System.exit(0);
} else {
for (int i = 0; i < 10000; i++) {
if (count[i][1] == max_count) {
System.out.print(i + " ");
}
}
}
}
}
public class 최빈값구하기 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String str = scan.nextLine();
ArrayList<Integer> list = new ArrayList<Integer>();
ArrayList<Integer> list2 = new ArrayList<Integer>();
String[] arr = str.split(", ");
for(int i=0; i<5; i++) {
list.add(Integer.parseInt(arr[i]));
}
int mode = 0;
for(int i=0; i<list.size(); i++) {
int count = 0;
for(int j=0; j<list.size(); j++) {
if(list.get(i)==list.get(j)) {
count++;
}
}
if(count>=mode&&count>1) {
mode = count;
list2.add(list.get(i));
list2.add(mode);
for(int k=0; k<list.size(); k++) {
if(list.get(i)==list.get(k)&&i!=k) {
list.remove(k);
k--;
}
}
}
}
if(list2.size()>1) {
int 빈도 = 0;
for(int i=1; i<list2.size(); i=i+2) {
if(list2.get(i)>=빈도) {
빈도=list2.get(i);
}
}
for(int i=1; i<list2.size(); i++) {
if(list2.get(i)==빈도) {
System.out.print(list2.get(i-1)+" ");
}
}
}
else if(list2.size()==0) {
System.out.println("없다");
}
}
}
lst1=[26, 37, 26, 37, 91]
def mode(lst):
frq={}
nlst=[]
for n in lst:
frq[n]=frq.get(n,0)+1
vlst=list(frq.values())
if len(frq)==1 or len(lst)==len(frq) or len(set(vlst))==1: #최빈값이 없을 조건: 1. 모든 자료값이 같음, 2. 모든 자료값이 다름, 3.자료값의 도수가 전부 같을 경우
return None
else:
for n in list(frq.keys()):
if frq[n]==max(vlst):
nlst.append(n)
return nlst
print("최빈값은",mode(lst1),"입니다.") #26,37
a = [28, 30, 32, 34, 144]
if max(a)== min(a):
print("없다.")
else:
a.sort()
b = 0
for i in range(len(a)):
if a[i-1] == a[i] :
print(a[i])
else:
b += 1
if b == int(len(a)):
print("없다.")
N = list(map(int,input().split()))
M = {}
test = list()
for i in N:
check = 0
go = 0
for j in range(len(test)):
if test[j] == i:
check = 1
go = j
if check == 0:
M[i] = 1
test.append(i)
elif check == 1:
M[test[go]] = M[test[go]] + 1
finalcheck = 0
usecheck = 0
for i in sorted(M.items(), key=lambda x: x[1], reverse=True):
if usecheck != 0:
if usecheck != list(i)[1]:
break
elif usecheck == 0:
if list(i)[1] == 1:
finalcheck = 1
break
usecheck = list(i)[1]
print(str(list(i)[0]) + ' ', end='')
if finalcheck == 1:
print("없다")
'''더 쉽게 하는 방법이 있을것 같긴 한데
참 어렵게 문제를 풀었습니다.
동작은 잘 하지만,
별로 시원한 느낌이 들지 않는 코드입니다'''
import random
num=[]
numnum=random.randint(1,10)
for i in range (0,numnum):
num.append(random.randint(1,10))
numdic={}
most=[]
max=0
for i in range (0,len(num)):
if not num[i] in numdic:
numdic[num[i]]=1
else:
numdic[num[i]]+=1
print()
for k,v in numdic.items():
if v>max:
max=v
print()
for k,v in numdic.items():
if v==max:
most.append(k)
print(num,' = ',end='')
if max==1 or max==len(num):
print ('None')
else:
for i in range (0,len(most)):
print(most[i],' ',end='')
from collections import Counter
def mode(m):
c = Counter(m)
return '최빈값은 없다.' if len({v: k for k, v in c.items()}) == 1 \
else [k for k, v in c.items() if max(c.values()) == v]
if __name__ == '__main__':
m = [26, 37, 26, 37, 91]
print(*mode(m))
import java.util.*;
public class a {
public static void Mode(int[] num){
Set<Integer> set1 = new HashSet<Integer>();
for(int i=0;i<num.length;i++){
set1.add(num[i]);
}
int[] set2 = new int[set1.size()];
int b = 0;
for(Integer x : set1) set2[b++] = x;
ArrayList<Integer> d = new ArrayList<Integer>();
for(int i=0;i<set2.length;i++){
int c = 0;
for(int j=0;j<num.length;j++){
if(set2[i]==num[j]){
c = c + 1;
}
}
d.add(i, c);
}
Integer e = Collections.max(d);
ArrayList<Integer> set3 = new ArrayList<Integer>();
for(int i=0;i<set2.length;i++){
int c1 = 0;
for(int j=0;j<num.length;j++){
if(set2[i]==num[j]){
c1 = c1 + 1;
}
}
if(c1==e){
set3.add(set2[i]);
}
}
System.out.println(set3);
}
public static void main(String[] args){
int[] list1 = {12, 17, 19, 17, 23};
int[] list2 = {26, 37, 26, 37, 91};
int[] list3 = {28, 30, 32, 34, 144};
Mode(list1);
Mode(list2);
Mode(list3);
}
}
def print_mode(c):
a = {i:c.count(i) for i in c}
b = [n for n in a.keys()
if a[n] == max(a.values()) and a[n] > 1]
if b == []:
b = ['없다']
return "{0}".format(b)
c = [[12, 17, 19, 17, 23],[26, 37, 26, 37, 91],[28, 30, 32, 34, 144]]
for i in c:
print(print_mode(i))
def Max_Count(data):
d = {}
key_value = set(data)
for k in key_value:
cnt = data.count(k)
d[k]=cnt
Max = 0
result = []
for i in d:
if Max < d[i] :
Max = d[i]
keys = i
elif d[keys] == 1:
return None
for j in d:
if d[keys] == d[j]:
result.append(j)
print(result)
Max_Count([12, 17, 19, 17, 23])
Max_Count([26, 37, 26, 37, 91])
Max_Count([28, 30, 32, 34, 144])
n = int(input("배열 크기"))
arr = []
for i in range(n):
print(i+1,"번쨰")
arr.append(int(input("원소 입력")))
set_arr = list(set(arr))
cnt_arr = []
for k in set_arr:
cnt_arr.append([arr.count(k),k])
max_cnt = max(cnt_arr)[0]
if len(set(arr))==len(arr):
print("최빈값 없음")
else:
for j in cnt_arr:
if j[0] == max_cnt :
print(j[1],end=", ")
집합을 이용해서 원소를 분리했습니다 [원소개소,원소] 를 2차배열에 담았고, 2차배열의 max값은 0번쨰 인덱스를 비교하는것을 이용했어요.
// Rust
// 자료형 변환 없이 HashMap으로 그냥 찾았습니다
use std::collections::HashMap; fn mode() {
let input = [[12, 17, 19, 17, 23],
[26, 37, 26, 37, 91],
[28, 30, 32, 34, 144],];
for list in input {
let mut map: HashMap<u32, u32> = HashMap::new();
for v in list {
let count = map.entry(v).or_default();
*count += 1;
}
// value max인 key 찾기
let max_count = map.values().max().unwrap();
let mut result = vec![];
if *max_count != 1 {
result = map.iter().filter(|&(_,v)| *v==*max_count).collect();
}
println!("{:?}", result);
}
}
a = [28, 30, 32, 34, 144]
b = sorted(list(set(a)))
md = my_dict = {}
for i in b:
md[i]=a.count(i)
max_count = max(md.values())
if max_count == 1 or max_count == len(a):
print('없다.')
else:
for value, count in md.items():
if count == max(md.values()):
print(value)
미숙한 코드입니다. 조언 부탁드려요
package org.javaturotials.ex;
import java.util.*;
import java.util.stream.Collectors;
public class test {
public static void main(String[] args) {
int max=-1;
int chm = 0;
int[] arr = {26, 37, 26, 37, 91};
int[] chc = new int[arr.length];
int[] siz = new int[arr.length];
for(int i=0; i<arr.length; i++) {
int count=0;
for(int j=0; j<arr.length; j++) {
if(i!=j) {
if(arr[i]==arr[j]) {
count++;
}
}
}
if(max<=count) {
max=count;
chc[i]=arr[i];
}
}
System.out.print("최빈값은: ");
for(int i=0; i<chc.length; i++) {
if(chc[i]!=0) {
System.out.print(chc[i] + " ");}
}
}
}
자바로 풀어봤습니다.
import java.util.Scanner;
import java.util.ArrayList;
public class test {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
ArrayList<Integer> numbers = new ArrayList<>();
// 입력 받기
while(true) {
System.out.print("숫자를 입력하시오: (그만 입력하고 싶으면 !을 입력하시오.)");
String inputData = scan.next();
if(inputData.equals("!")) {
break;
}else {
numbers.add(Integer.parseInt(inputData));
}
}
// 내림차순 정리
int max, maxidx;
for(int i=0; i<numbers.size(); i++) {
max = numbers.get(i);
maxidx=i;
for(int j=i+1; j<numbers.size(); j++) {
if(numbers.get(j)>max) {
maxidx=j;
max=numbers.get(j);
}
}
numbers.set(maxidx, numbers.get(i));
numbers.set(i, max);
}
// 최빈값 구하기
ArrayList<Integer> result = new ArrayList<>();
result.add(numbers.get(0));
int count=1, maxCount=1;
for(int i=1; i<numbers.size(); i++) {
if(numbers.get(i-1)!= numbers.get(i)) {
if(count>maxCount) {
maxCount=count;
result.clear();
result.add(numbers.get(i-1));
}else if(count==maxCount) {
result.add(numbers.get(i-1));
}
count = 1;
}else {
count++;
}
}
if(count==maxCount) {
result.add(numbers.get(numbers.size()-1));
}
// 빈도수에 따라 결과값 출력
if(maxCount!=1) {
System.out.println("최빈값:"+result+"\n");
System.out.printf("빈도수는 %d입니다.", maxCount);
}else {
System.out.println("최빈값 없다.");
}
}
}
def findMostFrequentValue(lst):
dicValue = {}
n = 0
mfv = []
for v in lst:
if v not in dicValue.keys():
dicValue[v] = 0
dicValue[v] += 1
if n < dicValue[v]:
n = dicValue[v]
mfv.clear()
mfv.append(v)
elif n == dicValue[v]:
mfv.append(v)
if len(mfv) == len(lst):
print('없다')
else:
print(mfv)
findMostFrequentValue([12, 17, 19, 17, 23])
findMostFrequentValue([26, 37, 26, 37, 91])
findMostFrequentValue([28, 30, 32, 34, 144])