리스트에 있는 숫자들의 중앙값을 구하는 프로그램을 만들어라.
[7, 9, 14] = 9
[24, 31, 35, 49] = 33
[17, 37, 37, 47, 57] = 37
중앙값 : 자료를 작은 값에서부터 크기순으로 나열할 때 중앙에 위치한 값
① 자료의 개수가 홀수이면 가운데 위치한 값이 중앙값이다.
② 자료의 개수가 짝수이면 가운데 위치한 두 값의 평균이 중앙값이다.
131개의 풀이가 있습니다.
import statistics
test =[[7,9,14],[24, 31, 35, 49],[17,37,37,47,57]]
for i in range(len(test)):
print(test[i],'=',statistics.median(test[i]))
public class Main {
public static void print(int a[])
{
if(a.length %2==0)
{
int idx=(a.length/2)-1;
System.out.printf("%d\n",(a[idx]+a[idx+1])/2);
}else
{
int idx=(a.length/2);
System.out.printf("%d\n",a[idx]);
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
int arr[] = {7, 9, 14};
int arr2[]={24, 31, 35, 49};
int arr3[]={17, 37, 37, 47, 57};
int arr4[]={17, 37, 37, 47, 57,22};
print(arr);
print(arr2);
print(arr3);
print(arr4);
}
}
파이썬으로 풀이했음
원소 개수가 홀수인 경우,
원소 개수를 2로 나누었을때의 정수값이 중간값이 되고,
(예: 원소갯수가 5라면, 5/2=2.5이고, 반올림한 정수는 3이됨. 즉, 리스트상 3번째 원소가 중간값임)
원소 개수가 홀수인 경우,
원소 개수를 2로 나누었을때의 정수값과 그 다음 정수의 평균값이 되는 것으로 계산함
(얘: 원소갯수가 4라면, 4/2=2, 즉, 리스트상 2번째 원소와 3번째 원소의 평균값이 중간값임)
(예)list = [17, 37, 37, 47, 57]
if int(len(list)) % 2 == 0:
i = int(len(list)/2)
j = i + 1
print(int((list[i] + list[j])/2))
else:
i = int((len(list))/2)
print(list[i])
print("리스트 원소 원하는 만큼 입력")
n=[]
while True:
a=input("원소입력: ")
if a=="종료":
break
n.append(int(a))
while len(n) !=1:
n.remove(max(n))
n.remove(min(n))
print(n[0])
def pg(n):return sum(n)/len(n)
def jung_Ang(n):
n=sorted(n)
if len(n)%2==0:return pg([n[(len(n)//2)-1],n[len(n)//2]])
else:return n[len(n)//2]
print(jung_Ang([1,2,3,4]))
def median(n):
n.sort()
print(n[int(len(n)/2)] if len(n) %2 == 1 else (n[int(len(n)/2)] + n[int(len(n)/2)-1])/2)
def median(lst):
lst.sort()
m = len(lst) // 2
return lst[m] if len(lst) % 2 == 1 else (lst[m] + lst[m - 1]) / 2
a = [[7, 9, 14],[24, 31, 35, 49],[17, 37, 37, 47,57]]
for i in range(len(a)):
a[i].sort()
if len(a[i])%2 ==0 :
print(a[i],(a[i][(len(a[i]) // 2) -1] +a[i][(len(a[i]) // 2)])//2)
elif len(a[i])%2 ==1 :
print(a[i],a[i][(len(a[i])// 2)])
c#
class Program
{
static void Main(string[] args)
{
/*
중앙값: 자료를 작은 값에서부터 크기순으로 나열할 때 중앙에 위치한 값
① 자료의 개수가 홀수이면 가운데 위치한 값이 중앙값이다.
② 자료의 개수가 짝수이면 가운데 위치한 두 값의 평균이 중앙값이다.
*/
int[] ary1 = { 7, 9, 14 }; // 9
int[] ary2 = { 24, 31, 35, 49 }; // 33
int[] ary3 = { 17, 37, 37, 47, 57 }; // 37
int[] ary = ary3; //할당
//짝수
if (ary.Length % 2 == 0)
{
int number = (ary[ary.Length / 2 - 1] + ary[ary.Length / 2])/2;
Console.WriteLine(number);
}
else //홀수
{
Console.WriteLine(ary[ary.Length/2]);
}
}
}
list1 = [[7, 9, 14], [24, 31, 35, 49], [17, 37, 37, 47, 57]]
def mean(l1):
return l1[(len(l1)-1)//2] if len(l1)%2 else (l1[(len(l1)-1)//2] + l1[(len(l1)-1)//2 + 1])/2
for l1 in list1:
print(l1, "=", mean(l1))
출력
[7, 9, 14] = 9
[24, 31, 35, 49] = 33.0
[17, 37, 37, 47, 57] = 37
class Program
{
static void Main(string[] args)
{
int[] nList1 = { 7, 9, 14 };
int[] nList2 = { 24, 31, 35, 49 };
int[] nList3 = { 17, 37, 37, 47, 57 };
Console.WriteLine(GetMedian(nList1).ToString());
Console.WriteLine(GetMedian(nList2).ToString());
Console.WriteLine(GetMedian(nList3).ToString());
}
public static int GetMedian(int[] Value)
{
decimal Median = 0;
int size = Value.Length;
int mid = size / 2;
Median = (size % 2 != 0) ? (decimal)Value[mid] : ((decimal)Value[mid] + (decimal)Value[mid - 1]) / 2;
return Convert.ToInt32(Math.Round(Median));
}
}
using System;
using System.Collections.Generic;
namespace CD186
{
class Program
{
static void Main(string[] args)
{
List<int> alist;
alist = new List<int>() { 7, 9, 14 };
Console.WriteLine(GetMedian(alist));
alist = new List<int>() { 24, 31, 35, 49 };
Console.WriteLine(GetMedian(alist));
alist = new List<int>() { 17, 37, 37, 47, 57 };
Console.WriteLine(GetMedian(alist));
}
static double GetMedian(List<int> aList)
{
aList.Sort();
double median;
int listLength = aList.Count;
if (listLength % 2 == 0)
{
median = (aList[listLength / 2 - 1] + aList[listLength / 2]) / 2;
}
else
{
median = aList[(int)(listLength / 2)];
}
return median;
}
}
}
public class TEST08 {
public static void main(String[] args) {
int[] data1 = {7, 9, 14};
int[] data2 = {24, 31, 35, 49};
int[] data3 = {17, 37, 37, 47, 57};
int[] mid = midIndex(data1);
if (mid.length == 1) {
System.out.println(data1[mid[0]]);
}
else {
int avg = (data1[mid[0]] + data1[mid[1]]) / 2;
System.out.println(avg);
}
mid = midIndex(data2);
if (mid.length == 1) {
System.out.println(data2[mid[0]]);
}
else {
int avg = (data2[mid[0]] + data2[mid[1]]) / 2;
System.out.println(avg);
}
mid = midIndex(data3);
if (mid.length == 1) {
System.out.println(data3[mid[0]]);
}
else {
int avg = (data3[mid[0]] + data3[mid[1]]) / 2;
System.out.println(avg);
}
}
public static int[] midIndex(int[] data) {
int odd = data.length % 2;
int[] mid = null;
if (odd == 1) {
mid = new int[1];
mid[0] = data.length / 2;
}
else {
mid = new int[2];
mid[0] = (data.length / 2) - 1;
mid[1] = data.length / 2;
}
return mid;
}
}
lst = [17, 37, 37, 47, 57]
lst.sort()
med_1 = lst[int((len(lst)-1)/2)]
med_2 = lst[int((len(lst))/2)]
med = (med_1+med_2)/2
print(med)
저는 python을 사용하였습니다. 자료의 개수가 홀수든 짝수든 상관없이 가우스를 씌워주어 중앙값을 출력하게끔 하였습니다.
Ruby
a = gets.chomp.split
a.sort!
if a.length.odd?
puts a[a.length/2]
else
puts (a[a.length/2-1] + a[a.length/2]) / 2
end
Kotlin 연습
fun main(args : Array<String>){
val list: List<Int> = args.toList().map { s->s.toInt()}.sorted()
if(list.size % 2 == 0)
println((list[list.size / 2 - 1] + list[list.size / 2]) / 2)
else
println(list[list.size / 2])
}
package test;
public class test {
public static void main(String[] args) {
int[][] num = { { 7, 9, 14 }, { 24, 31, 35, 49 }, { 17, 37, 37, 47, 57 } };
for (int i = 0; i < num.length; i++)
System.out.println(num[i].length % 2 == 0 ? (num[i][num[i].length / 2 - 1] + num[i][num[i].length / 2]) / 2 : num[i][num[i].length / 2]);
}
}
Ruby
mid_val = ->arr { arr.size.odd? ? arr[arr.size/2] : arr[arr.size/2-1, 2].sum / 2 }
Test
expect( mid_val[[7, 9, 14]] ).to eq 9
expect( mid_val[[24, 31, 35, 49]] ).to eq 33
expect( mid_val[[17, 37, 37, 47, 57]] ).to eq 37
def median(xs):
xs = sorted(xs)
l = len(xs)
if l % 2 is 0:
return sum(xs[l//2-1:l//2+1]) / 2
return xs[l//2]
//[7, 9, 14] = 9
//[24, 31, 35, 49] = 33
//[17, 37, 37, 47, 57] = 37
//
//중앙값 : 자료를 작은 값에서부터 크기순으로 나열할 때 중앙에 위치한 값
//① 자료의 개수가 홀수이면 가운데 위치한 값이 중앙값이다.
//② 자료의 개수가 짝수이면 가운데 위치한 두 값의 평균이 중앙값이다.
#include <iostream>
#include <algorithm>
#include <assert.h>
using namespace std;
double GetMedium(int input[], int inputSize)
{
sort(input, input+inputSize);
if (inputSize % 2 == 1)
return(input[inputSize/2]);
else
return((input[inputSize/2 - 1] + input[inputSize/2])/2.0);
}
void test() {
int input1[3] = {7, 9, 14};
assert(GetMedium(input1, 3) == 9);
int input2[4] = {24, 31, 35, 49};
assert(GetMedium(input2, 4) == 33.0);
int input3[5] = {17, 37, 37, 47, 57};
assert(GetMedium(input3, 5) == 37);
int input4[7] = {17, 37, 37, 47, 57, 0, 0};
assert(GetMedium(input4, 5) == 37);
}
int main() {
test();
//return 0;
int input[6] = {9, 8, 7, 6, 5, 4};
for (int i = 0; i<6; i++) {
cout << "input[i] : " << input[i] << endl;
}
double medium = GetMedium(input, 6);
cout << "Medium = " << medium;
return 0;
}
int[] arr1 = { 14, 7, 9 };
int[] arr2 = { 24, 31, 35, 49 };
int[] arr3 = { 17, 37, 37, 47, 57 };
Arrays.sort(arr1);
Arrays.sort(arr2);
Arrays.sort(arr3);
int centera = arr1.length / 2;
int centerb = arr2.length / 2;
int centerc = arr3.length / 2;
if (arr1.length % 2 != 0) {
System.out.println(arr1[centera]);
} else {
int center1 = arr1.length / 2 - 1;
System.out.println((arr1[centera] + arr1[center1]) / 2);
}
if (arr2.length % 2 != 0) {
System.out.println(arr2[centerb]);
} else {
int center1 = arr2.length / 2 - 1;
System.out.println((arr2[centerb] + arr2[center1]) / 2);
}
if (arr3.length % 2 != 0) {
System.out.println(arr3[centerc]);
} else {
int center1 = arr3.length / 2 - 1;
System.out.println((arr3[centerc] + arr3[center1]) / 2);
}
var myArra = [17, 37, 37, 47, 57];
var myNum = myArra.length/2;
if(myArra.length%2 > 0)
{
var Result = myArra[Math.ceil (myNum-1)];
}
else
{
var Result = (myArra[myNum-1]+myArra[myNum])/2;
}
alert(Result);
def mid(lst):
lst.sort()
a=len(lst)//2
if len(lst)%2==0:
return (lst[a-1]+lst[a])/2
else:
return lst[a]
``````{.python}
def mid(lst):
lst.sort()
a=len(lst)//2
if len(lst)%2==0:
return (lst[a-1]+lst[a])/2
else:
return lst[a]
public class Middlenum {
public static void main(String[] args) {
int []arr= {17, 37, 97, 47, 57};
for (int i = 1; i<arr.length; i++) {
int temp = 0;
for (int j = 0; j<i;j++ ) {
if (arr[i]>arr[j]) {
temp = arr[i];
arr[i]=arr[j];
arr[j]=temp;
}
}
}
//오름차순으로 순서를 정리한 후에 출력처리하였습니다.
if ((arr.length%2) == 1){
System.out.println(arr[arr.length/2]);
} else {
System.out.println((double)(arr[arr.length/2-1]+arr[arr.length/2])/2);
}
}
}
def Median(A) :
size = len(A)
result = 0.0
temp=[]
for i in A :
temp.append(i)
temp.sort()
if size%2!=0 :
#홀수
result = temp[size//2]
else :
#짝수
result = (temp[(size//2)-1]+temp[(size//2)])/2
return print(str(A)+" = "+ str(result))
m=[1,2,3,4]#여기에 리스트 넣기
n=sorted( m )
l=len(n)
o=l//2
if l%2==0:
print((n[o]+n[o-1])/2)
else:
print(n[o])
public class Solution {
public static void main(String[] args) {
int[][] arr = {{7, 9, 14}, {24, 31, 35, 49}, {17, 37, 37, 47, 57}};
for(int i = 0; i < arr.length; i++) {
if(arr[i].length % 2 == 0) {
int idx = arr[i].length/2-1;
System.out.println((arr[i][idx]+arr[i][++idx])/2);
}else {
int idx = arr[i].length/2;
System.out.println(arr[i][idx]);
}
}
}
}
# l : python list
def output_median(l):
mid_div = len(l) % 2
mid = len(l) // 2
if mid_div != 0:
return l[mid]
else:
return (l[mid-1] + l[mid]) / 2
def middle(lista):
if len(lista)%2 != 0:
return lista[len(lista)//2]
else:
return (lista[len(lista)//2]+lista[(len(lista)//2)-1])/2
namespace codingdojang__
{
class Program
{
static void Main(string[] args)
{
string[] input_array = Console.ReadLine().Split(',');
double temp = 0;
if (input_array.Length % 2 == 1)
{
temp = double.Parse(input_array[input_array.Length / 2]);
}
else if(input_array.Length % 2 == 0)
{
temp = (double.Parse(input_array[input_array.Length / 2 - 1]) + double.Parse(input_array[input_array.Length / 2])) / 2;
}
Console.WriteLine(temp);
}
}
}
list_ = list(sorted(map(float,input("변수 입력 : ").split())))
print(list_[int((len(list_) - 1) / 2)] if len(list_) % 2 == 1
else (list_[int(((len(list_) - 2) / 2))] + list_[int(len(list_) / 2)]) / 2)
#include<stdio.h>
int main(void)
{
int a[5] = { 10,20,30,40,50};
int i,pos,mid;
int cnt = 0;
for (i = 0; i<sizeof(a)/sizeof(a[1]); i++)
{
cnt++;
}
if (cnt % 2 == 0)
{
pos = (cnt / 2)-1;
mid = (a[pos] + a[pos + 1]) / 2;
printf("%d", mid);
}
else if (cnt % 2 != 0)
{
pos = (cnt / 2)-1;
printf("%d", a[pos + 1]);
}
return;
}
def median(lst):
lst.sort()
ret = (lst[len(lst) // 2] + lst[(len(lst) - 1) // 2]) / 2
return ret
test = [[7, 9, 14],
[24, 31, 35, 49],
[17, 37, 37, 47, 57]]
for t in test:
print(t, median(t), sep=" = ")
def findig(x):
n=len(x)
if n%2 == 1:
result = x[int((n-1)/2)]
else:
result = (x[int(n/2)-1]+x[int(n/2)])/2
return result
x = [1,3,4,5]
print(findig(x))
num=input("숫자들을 입력하시오:")
num_list=num.split()
for x in range(0,len(num_list)):
num_list[x]=int(num_list[x])
if len(num_list)%2!=0:
print("중앙값은{}입니다.".format(num_list[int(len(num_list)/2)]))
else:
print("중앙값은{}입니다.".format((num_list[int(len(num_list)/2)]+num_list[int(len(num_list)/2+1)])/2))
numlist = list(map(int,input().split()))
def center(numlist):
l = len(numlist)
numlist.sort()
if l % 2 == 0:
return (numlist[int(l/2-1)] + numlist[int(l/2)]) / 2
else:
return numlist[int(l//2)]
print(center(numlist))
def centre(n) :
if len(n) % 2 != 0 :
return n[(len(n)//2)]
else :
return (n[(len(n)//2) - 1] + n[(len(n)//2)]) / 2
print(round(centre([24, 31, 35, 49])))
output : 33
파이썬입니다. 식이 많이 더럽네요.. ㅠ
static void Main(string[] args)
{
Console.WriteLine("*** 코딩도장 Q186 ***");
int[] q1 = { 7, 9, 14 };
int[] q2 = { 24, 31, 35, 49 };
int[] q3 = { 17, 37, 37, 47, 57 };
CenterValue(q1);
CenterValue(q2);
CenterValue(q3);
}
static void CenterValue(int[] q)
{
int gili = q.Length;
int centerValue = 0;
if (gili%2==0)
{
centerValue = (q[gili / 2] + q[(gili / 2) - 1]) / 2;
Console.WriteLine("중앙값은 {0} 입니다.", centerValue);
}
else
{
centerValue = q[gili / 2];
Console.WriteLine("중앙값은 {0} 입니다.", centerValue);
}
}
public static double searchMedium(int[] numbers) {
return (numbers[(numbers.length-1)/2] + numbers[(numbers.length)/2]) / 2.0;
}
#include <iostream>
using namespace std;
float middleValue(int *arr, int len)
{
return (len%2 == 1) ? arr[len/2] : (float)(arr[len/2] + arr[len/2-1])/2;
}
int main(int argc, const char * argv[]) {
// insert code here...
int a[3] = {1,2,3};
int b[4] = {1,2,3,4};
cout<< middleValue(a, 3)<<" "<<middleValue(b, 4)<<endl;
return 0;
}
public class practice {
public static void main(String[] args) {
int list1[] = {7, 9, 14};
int list2[]={24, 31, 35, 49};
int list3[]={17, 37, 37, 47, 57};
center(list1);
center(list2);
center(list3);
}
public static void center(int array[])
{
if(array.length %2==0)
{
System.out.printf("%d\n", (array[array.length / 2 -1] + array[array.length / 2]) / 2);
}
else
{
System.out.printf("%d\n", array[array.length / 2]);
}
}
}
function solution(n) {
var input = n;
var result;
var division = Math.floor(input.length / 2)
if (input.length % 2 == 0) {
result = Math.floor((input[division] + input[division - 1]) / 2);
} else {
result = input[division];
}
return result;
}
console.log(solution([7, 9, 14]));
console.log(solution([24, 31, 35, 49]));
console.log(solution([17, 37, 37, 47, 57]));
import java.util.Scanner;
public class Test3 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("테스트할 원소의 개수: ");
int TestCase = in.nextInt();
int[] listNum = new int[TestCase];
int sum = 0;
if(TestCase % 2 == 0) {
for(int i = 0; i < listNum.length; i++) {
listNum[i] = in.nextInt();
}
int index = (listNum.length/2)-1;
System.out.println((listNum[index]+listNum[index+1])/2);
}
else if(TestCase % 2 == 1) {
for(int i = 0; i < listNum.length; i++) {
listNum[i] = in.nextInt();
}
int index = (listNum.length/2);
System.out.println(listNum[index]);
}
}
}
int getArray(int arr, int size){ for (int i = 0; i < size-1; i++){ scanf("%d\n", &arr[i]); } return arr; } void main(){ int size = 0; scanf("%d\n", &size); int arr= (int)malloc(sizeof(int)*size); getArray(arr, size); ((size) % 2) ? printf("%d\n", arr[(size)/ 2]) : printf("%f\n", (float)((arr[(size) / 2 -1] + arr[(size) / 2]) / 2));
}
subj=list(map(int,input().split()))
if len(subj)%2==1:
print(subj[int(len(subj)/2)])
else:
print((subj[int(len(subj)/2)-1]+subj[int(len(subj)/2)])/2)
length = 리스트의 길이 if (length % 2 == 0) result = 리스트의 length/2 위치 아이템 else result = (리스트의 length/2 - 1 + 리스트의 length/2)/2
파이썬 3.7.2
nlist = []
while True:
if len(nlist) == 0:
Ans = int(input("숫자를 입력하세요.\n> "))
nlist.append(Ans)
Ans = input("숫자를 추가하시겠습니까? ( Y / N ) \n> ")
if Ans in ["Y", "y"]:
Ans = int(input("숫자를 입력하세요.\n> "))
nlist.append(Ans)
elif Ans in ["N", "n"]:
break
nlist.sort()
if len(nlist)%2 == 1:
print("\n\n중간 수 : "+str(nlist[int(len(nlist)/2)])+"\n\n")
if len(nlist)%2 == 0:
print("\n\n중간 수 : "+str((nlist[int(len(nlist)/2)]+nlist[int(len(nlist)/2)+1])/2)+"\n\n")
lis = list(map(int, input('>>>').split(',')))
l = len(lis)
lis.sort()
print(lis, '=', lis[l//2] if l%2==1 else (lis[(l//2)-1]+lis[l//2])//2)
lis = [17, 37, 37, 47, 57]
a = len(lis)//2
b = a-1
if len(lis) %2 == 1:
print(lis[a])
else:
print((lis[a]+lis[b])/2)
def medium(lst):
if len(lst)%2 == 1:
print(lst[len(lst)//2])
else:
me = (lst[len(lst)//2] + lst[(len(lst)//2)-1])/2
print(me)
lst = list(map(int, input('값을 입력하세요:').split(' ')))
medium(lst)
list1 = [17, 37, 37, 47, 57]
if len(list1)%2 == 0: avg= int((list1[int((len(list1)/2)-1)]+list1[int((len(list1)/2))])/2)
elif len(list1)%2 == 1: avg= list1[(len(list1)//2)]
print(avg)
L = [int(x) for x in input('Enter numbers = ').split()]; L.sort()
if len(L) % 2 == 0 :
avg = (L[int(len(L)/2)]+L[int(len(L)/2-1)])/2
else :
avg = L[int((len(L)-1)/2)]
print(L, '=', avg)
def solution(mylist):
if len(mylist) % 2 == 1:
return mylist[len(mylist)//2]
else:
t = mylist[len(mylist)//2-1] + mylist[len(mylist)//2]
return t/2
print(solution([7,9,14]))
print(solution([24,31,35,49]))
print(solution([17,37,37,47,57]))
MEDIAN.PY
====================
---------------------
a = [7, 9, 14]
b = [24, 31, 35, 49]
c = [17, 37, 37, 47, 57]
H1
print(a[1])
print(b[1]+b[2]/2)
print(c[2])
def find_mid(x):
if len(x) // 2 == 1:
return x[int(len(x)/2)]
else:
return (x[int(len(x)/2)-1]+x[int(len(x)/2)])/2
# Algorithm
def Odd(list_1):
a = len(list_1)//2
return list_1[a]
def Even(list_1):
a = len(list_1)//2
print(a)
return int((list_1[a-1]+list_1[a]))/2
# Input list of argument
a = list(map(int, input().split(' ')))
if len(a)%2 == 1:
print(Odd(a))
elif len(a)%2 == 0:
print(Even(a))
def mid(li):
li.sort()
len_li = len(li)
if len_li % 2 == 0:
print((li[len_li // 2] + li[len_li // 2 + 1]) / 2)
else:
print(li[(len_li // 2)])
inp = eval(input("input :"))
if len(inp)%2 == 0 :
print((inp[int(len(inp)/2)-1]+ inp[int(len(inp)/2)])/2)
print()
else :
print(inp[int((len(inp)-1)/2)])
결과
input :[1, 2, 3, 4, 5, 6] 3.5
def Mid_value(data):
Count = len(data)
if Count % 2 == 1:
result = data[Count//2]
else :
result = (data[Count//2-1]+data[Count//2])/2
print(result)
Mid_value([7,9,14])
Mid_value([24,31,35,49])
Mid_value([17,37,37,47,57])
def num(a,b,c):
return int(a/3+b/3+c/3-1)
print(num(1,2,3))
위의 예시들을 보면 전부다 중앙값이 평균값 - 1 이라는 걸 알 수 있다. 그래서 -1을 해줬건만 내가 쓴 코드에선 중앙값=평균값이라 모순이 발생한다.
public class 중앙값구하기 {
public static void Middle(int[] a) {
if(a.length%2==0) {
System.out.println((a[1]+a[2])/2);
}
else {
System.out.println(a[a.length/2]);
}
}
public static void main(String[] args) {
int[] list1 = {7, 9, 14};
int[] list2 = {24, 31, 35, 49};
int[] list3 = {17, 37, 37, 47, 57};
Middle(list1);
Middle(list2);
Middle(list3);
}
}
def median():
list=[]
while True:
data=input("자료 입력(end 입력 시 입력 종료)")
list.append(data)
if data=='end':
list.remove('end')
break
list.sort()
if len(list)%2==1:
print(list[int((int(len(list))+1)/2-1)])
else:
print((int(list[int(len(list)/2)])+int(list[int((len(list))/2-1)]))/2)
median()
파이썬
def median(n):
m=sorted(n)
if len(m)%2==1:
answer=m[int(len(m)/2)]
elif len(m)%2==0:
answer=(m[int(len(m)/2)-1]+m[int(len(m)/2)])/2
return answer
print(median([7, 9, 14])) #9
print(median([24, 31, 35, 49])) #33
print(median([17, 37, 37, 47, 57])) #37
파이썬3입니다.
def midvalue(*x):
a = list(x)
a.sort()
print(a[int(len(a)/2)] if len(a) % 2 == 1 else (a[int(len(a)/2-1)]+a[int(len(a)/2)])/2)
midvalue(7, 9, 14) #9
midvalue(24, 31, 35, 49) #33.0
midvalue(17, 37, 37, 47, 57) #37
int Midium_num(int a[]) { int result = 0; int Mrx_Size_Ctr = 0; Mrx_Size_Ctr = sizeof(a)/sizeof(int); Mrx_Size_Ctr%2 ==0? result = even(a,Mrx_Size_Ctr) : result = odd(a,Mrx_Size_Ctr) ; return result; }
int even(int a[],int a_size) { int result = 0; result = (a[a_size-1]+a[a_size])/2 return result; } int odd(int a[],int a_size) { int result = 0; result = a[a_size/2]; return result; }
def rookie(n):
if len(n) % 2 ==0:
d=(n[(int(len(n)/2)-1)]+n[(int(len(n)/2))])/2
else:
d=n[round(int(len(n)/2))]
return d
print(rookie([7, 9, 14]))
print(rookie([24, 31, 35, 49]))
print(rookie([17, 37, 37, 47, 57]))
output: 9 , 33 , 37 초보스럽게 한번 풀어봣습니다..
lst=list(map(int,input("리스트를 만듭니다. 콤마(",")를 포함한 연속된 숫자를 입력하십시오: ").split(",")))
def med(lst):
lst.sort()
if len(lst)%2!=0:
return lst[int((len(lst)-1)/2)]
else:
return (lst[int(len(lst)/2)]+lst[int((len(lst)/2))-1])/2
print(med(lst))
a = list(input("list를 입력하시오."))
if len(a)%2 == 1:
a.sort()
print(a)
print(a[len(a)//2])
else:
b = int(a[len(a)//2 - 1]) + int(a[len(a)//2])
print(b)
a = [2, 34, 7, 5, 78, 123, 45]
def median(a):
if len(a) %% 2 == 0:
num1 = a[len(a) / 2]
num2 = a[len(a) / 2 + 1]
result = (num1 + num2) / 2
return result
else:
result = a[round(len(a) / 2)]
return result
a = list(input("숫자를 입력: ").split(","))
b = list(map(int, a))
c = sorted(b)
if len(b) % 2 == 0:
print((c[int(len(b)/2) - 1]+c[int(len(b)/2)])/2)
elif len(b) % 2 == 1:
print(c[int(len(b)/2)])
a= (input("numbers:"))
b = a.split(',')
if len(b)%2 == 1:
c = int(len(b)//2)
print(b[c])
else:
c = int((len(b)//2))
print((int(b[c])+int(b[c-1]))/2)
nums = sorted(list(map(int, input('숫자를 공백으로 분리해 입력하세요:').split())))
target = len(nums)//2
print([(nums[target-1]+nums[target])/2 if len(nums) % 2 == 0 else nums[target]][0])
import statistics
A = [7, 9, 14] B = [24, 31, 35, 49] C = [17, 37, 37, 47, 57]
print(statistics.median(A)) print(statistics.median(B)) print(statistics.median(C))
def mid(l):
l1 = sorted(l)
if len(l)%2==0:
return (l1[len(l)//2-1]+l1[len(l)//2])/2
else:
return l1[len(l)//2]
test=[[7, 9, 14], [24, 31, 35, 49], [17, 37, 37, 47, 57]]
for data in test:
data.sort()
print(data[int(len(data)/2-0.5)]if len(data)%2==1 else (data[int(len(data)/2-1)]+data[int(len(data)/2)])/2)
def cal_middle_value(li):
result = sorted(li, reverse=True)
num = len(result)
if num % 2 == 1:
return result[num // 2]
else:
return (result[num // 2 - 1] + result[num // 2]) // 2
if __name__ == "__main__":
print(cal_middle_value([7, 9, 14]))
print(cal_middle_value([24, 31, 35, 49]))
print(cal_middle_value([17, 37, 37, 47, 57]))
li1=input('리스트 입력 : ').split()
li2=list(map(int,li1))
li3=sorted(li2)
n=len(li2)
print(li2)
print(li3)
print(n)
if n%2==0:
print('중앙값은 ',(li3[int((n-1)/2)]+li3[int((n-1)/2+1)])/2)
else:
print('중앙값은 ',li3[int((n-1)/2+0.5)])
a = [int(x) for x in input().strip().split()]
if len(a)%2 ==0:
result = (a[len(a)//2-1]+a[len(a)//2])/2
else:
result = (a[(len(a)-1)//2])
print(result)
직접 숫자 입력후 리스트의 중앙값을 뽑아내줍니다.
A=input()
A1=list(map(int,A.split(",")))
A1.sort()
if len(A1)%2!=0:
center=A1[len(A1)//2]
print(str(A1)+" = "+str(center))
else:
center=(A1[(len(A1)//2)-1]+A1[len(A1)//2])/2
print(str(A1) + " = " + str(center))
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;
import java.util.TreeSet;
public class Q184 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String[] input = scan.nextLine().split(",");
TreeSet<String> ts = new TreeSet<String>(Arrays.asList(input));
ArrayList<String> temp = new ArrayList<String>(ts);
if (ts.size() % 2 == 0) {
System.out.println(
(Integer.parseInt(temp.get(temp.size() / 2 - 1))
+ Integer.parseInt(temp.get(temp.size() / 2)))
/ 2);
} else {
System.out.println(temp.get(temp.size() / 2));
}
}
}
def center(x):
print (x,'\n--> ',end='')
x.sort()
if len(x)%2==0:
print((x[int((len(x))/2)]+x[int((len(x)-1)/2)])/2)
else:
print(x[int((len(x)-1)/2)])
center([7, 9, 14])
center([24, 31, 35, 49])
center([17, 37, 37, 47, 57])
lst=list(map(int, input().split()))
if len(lst)%2==0:
print((lst[int(len(lst))//2]+lst[int(len(lst))//2-1])/2)
else:
print(lst[int(len(lst))//2])
N = list(map(int,input().split()))
N.sort()
if len(N) % 2 == 0:
print(int((N[int(len(N)/2)-1] + N[int(len(N)/2)])/2))
elif len(N) % 2 == 1:
print(N[int(len(N)/2)])
#184 중앙값구하기
list1 = [7, 9, 14]
list2 = [24, 31, 35, 49]
list3 = [17, 37, 37, 47, 57]
list1.sort()
list2.sort()
list3.sort()
if len(list1) % 2 == 1:
cal_odd = int((len(list1)-1)/2)
print("첫 번째 리스트의 중앙값은",list1[cal_odd])
else:
middle_even = (list1[int(len(list1)/2)]+list1[int((len(list1)/2)-1)])/2
print("첫 번째 리스트의 중앙값은",middle_even)
if len(list2) % 2 == 1:
cal_odd = int((len(list2)-1)/2)
print("두 번째 리스트의 중앙값은",list2[cal_odd])
else:
middle_even = (list2[int(len(list2)/2)]+list2[int((len(list2)/2)-1)])/2
print("두 번째 리스트의 중앙값은",middle_even)
if len(list3) % 2 == 1:
cal_odd = int((len(list3)-1)/2)
print("세 번째 리스트의 중앙값은",list3[cal_odd])
else:
middle_even = (list3[int(len(list3)/2)]+list3[int((len(list3)/2)-1)])/2
print("세 번째 리스트의 중앙값은",middle_even)
public class a {
public static void Median(int[] num){
if(num.length%2==1){
System.out.println(num[num.length/2]);
} else{
System.out.println((num[num.length/2-1]+num[num.length/2])/2);
}
}
public static void main(String[] args){
int[] list1 = {7,9,14};
int[] list2 = {24,31,35,49};
int[] list3 = {17,37,37,47,57};
Median(list1);
Median(list2);
Median(list3);
}
}
#include <stdio.h>
#include <stdlib.h>
int main(){
int arr1[4]={4,6,12,19};
int mid, size;
size=sizeof(arr1)/4;
if(size%2==0)
mid=(arr1[size/2]+arr1[size/2-1])/2;
else
mid=arr1[size/2];
printf("%d",mid);
}
namespace _60일차_9월30일
{
class MainApp
{
static void Main(string[] args)
{
//배열 입력란
Console.Write("Input Numbers (Split Setting : ',') : ");
string Input_Data = Console.ReadLine();
string[] string_Array = Input_Data.Split(',');
int[] Int_Array_Data = System.Array.ConvertAll<string,int>(string_Array,int.Parse);
//배열 정렬
Array.Sort(Int_Array_Data);
//배열 출력[배열의 개수가 짝수 / 홀수일때]
if (Int_Array_Data.Length % 2 == 0)
{
Console.Write("[");
foreach (var Result in Int_Array_Data)
Console.Write($" {Result} ");
Console.Write($"] = {(Int_Array_Data[1]+Int_Array_Data[2])/2}");
}
else if (Int_Array_Data.Length % 2 != 0)
{
Console.Write("[");
foreach (var Result in Int_Array_Data)
Console.Write($" {Result} ");
Console.Write($"] = {Int_Array_Data[Int_Array_Data.Length/2]}");
}
}
}
}
def Middle(k):
if len(k)%2==0:
return (k[len(k)//2-1]+k[(len(k)//2)])//2
else:
return k[len(k)//2]
print(Middle([7,9,14]))
print(Middle([24,31,35,49]))
print(Middle([17,37,37,47,57]))
class GetBalance:
def __init__(self):
self.mid = 0
def getMid(self,list):
l = len(list)
if l%2==1:
self.mid = list[int((l-1)/2)]
else:
self.mid = 0.5*(list[int(l/2)]+list[int(l/2-1)])
print (self.mid)
a = GetBalance()
a.getMid([7,9,14])
a.getMid([24,31,35,49])
a.getMid([17,37,37,47,57])
result = [int(i) for i in input().split(",")]
result.sort()
print(result[len(result)//2] if len(result)%2==1 else (result[len(result)//2]+result[(len(result)//2)-1])/2)
def middle(lis):
if len(lis) % 2 == 1 :
return lis[len(lis)%2]
else:
return (lis[(len(lis)//2)-1] + lis[(len(lis)//2)]) / 2
print(middle([17,37,37,47,57]))
def list_middle(list):
list.sort()
if len(list)%2==1:
print(list[len(list)//2])
else:
print((list[int(len(list)/2)]+list[int(len(list)/2)-1])/2)
a=[7,9,14]
b=[24,31,35,49]
list_middle(a)
list_middle(b)
def midian(x):
x.sort()
result =x[len(x)//2] if len(x)%2==1 else (x[len(x)//2-1]+x[len(x)//2])/2
return result
python 3.8.7입니다.
>>> import statistics
>>> list = [449590, 1836049, 1224]
>>> statistics.median(list)
449590
>>> list = [149875, 13468394, 438, 24, 2459456, 4667]
>>> statistics.median(list)
77271.0
a = [17, 37, 37, 47, 57]
temp = int(len(a)/2)
if len(a) % 2 == 0:
print((a[temp-1] + a[temp]) / 2)
else:
print(a[len(a) // 2])
test = [8, 2, 3, 5, 6, 9]
test.sort()
print((test[(int((len(test) - 1) / 2))] + test[(int(len(test) / 2))]) / 2)
python 3.9.1
왕초보입니다
def find_median(list1):
list1.sort()
n = len(list1)
if n % 2 == 0:
median = (list1[int(n/2)] + list1[int(n/2 - 1)]) / 2
if n % 2 != 0:
median = list1[int((n-1) / 2)]
return median
def median(lst):
lst.sort()
temp = int(len(lst)/2)
if len(lst) % 2 == 0 :
output = (lst[temp] + lst[temp-1])/2
else:
output = lst[temp]
return output
ll = [7,9,14,45]
ll = sorted(ll)
m = len(ll) // 2
print(ll[m] if len(ll) % 2 == 1 else (ll[m] + ll[m - 1]) / 2)
li =[[7, 9, 14], [24, 31, 35, 49],[17, 39, 37, 47, 57]]
for i in li:
i = sorted(i)
if len(i)%2 == 0:
print((i[len(i)//2]+i[(len(i)//2) - 1])//2)
else:
print(i[len(i)//2])
listx=[7,9,14]
listy=[24,31,35,49]
listz=[17,37,37,47,57]
def middle(e):
e.sort()
if len(e) % 2 == 1:
return e[int((len(e)-1)/2)]
if len(e) % 2 == 0:
return int((e[int(len(e)/2)]+e[int((len(e)/2)-1)])/2)
print(middle(listx),middle(listy),middle(listz))
a = [24, 31, 35, 49]
if len(a)%2 == 1:
print(a[int(((len(a)-1))/2)])
elif len(a)%2 == 0:
print((a[int(len(a)/2-1)]+a[int(len(a)/2)])/2)
import statistics
a = [7, 9, 14]
print(statistics.median(a))
def where_mid(list1):
point = len(list1)//2
if len(list1)//2 != 0: return list1[point]
else: return list1[point]/2+list1[point-1]/2
a = [7, 9, 14]
b = [24, 31, 35, 49]
c = [17, 37, 37, 47, 57]
print(where_mid(a), where_mid(b), where_mid(c))
def cent_numb(x):
x.sort()
if len(x) % 2 == 1:
print(x[len(x) // 2])
else:
print(((x[(len(x) // 2) -1]) + (x[len(x) // 2])) / 2)
#codingdojing_medianList
a = [17, 37, 37 ,47, 57]
b = [7, 9, 14]
c = [24, 31, 35, 49]
a.sort()
b.sort()
c.sort()
K = c
print(K[len(K)//2]) if len(K)%2 == 1 else print(sum(K[len(K)//2 - 1 : len(K)//2 +1])/2)
파이썬 3.8.10으로 작성되었습니다.
from math import floor
def get_middle(arr):
arr_s = sorted(arr)
l = len(arr)
if l % 2 == 0:
half = floor(l/2)
return (arr_s[half] + arr_s[half - 1]) / 2
else:
return arr_s[floor(l/2)]
print(get_middle([24, 31, 35, 49]))
def func(list):
sorted_list = sorted(list)
if len(sorted_list) % 2 != 0:
print(sorted_list[len(sorted_list) // 2])
else:
mid = len(sorted_list) // 2
print(int((sorted_list[mid - 1] + sorted_list[mid]) / 2))
func([7, 9 ,14])
func([24, 31, 35, 49])
func([17, 37, 37, 47, 57])
even = [2, 4, 6, 8]
odd = [5, 7, 9, 11,13]
a = odd
mok = len(a) // 2
if len(a) % 2 == 1: # 홀수이면
print(a[mok])
else: # 짝수이면
print((a[mok] + a[mok-1])/2)
def median(n):
if len(n)%2==0: print((n[len(n)//2]+n[len(n)//2 -1])/2)
else: print(n[(len(n)-1)//2])
median([7,9,14])
static void middle(int...x) {
if(x.length%2 == 0) {
System.out.println((x[x.length/2-1] + x[x.length/2]) /(double)2);
}else {
System.out.println(x[x.length%2]);
}
}
public static void main(String[] args) {
middle(7,9,14);
middle(24,31,35,49);
middle(17,37,37,47,57);
}
def median (arr) :
leng = len(arr)
m = int(leng/2)
if leng %2 != 0 :
return arr[m]
if leng %2 == 0 :
return (arr[m-1]+arr[m])/2
a = [24, 31, 35, 49]
b = median(a)
print(b)
// Rust
fn main() {
let v1: Vec<u32> = vec![7, 9, 14];
let v2: Vec<u32> = vec![24, 31, 35, 49];
let v3: Vec<u32> = vec![17, 37, 37, 47, 57];
let mut vecs = vec![v1, v2, v3]; // Vec<Vec<u32>>
for vec in &mut vecs {
vec.sort();
let l = vec.len();
if l % 2 != 0 {
println!("{:?} = {}", vec, vec[l/2]);
} else {
println!("{:?} = {}", vec, ((vec[l/2-1]+vec[l/2]) as f64)/2.);
}
}
}
a = [[7, 9, 14],[24, 31, 35, 49],[17, 37, 37, 47,57]]
for li in a:
li.sort()
n = len(li)
if n % 2 == 1:
middle = li[int((n-1)/2)]
print("{} 홀수 값 {}".format(li, middle))
else:
middle = (li[int(n/2)] + li[int(n/2)-1])/2
print("{} 짝수 값 {}".format(li, middle))
a = [7, 9, 14]
b = [24, 31, 35, 49]
c = [17, 37, 37, 47, 57]
print(f"{a} = {(a[len(a)//2] + a[-(len(a)//2) - 1])//2}")
print(f"{b} = {(b[len(b)//2] + b[-(len(b)//2) - 1])//2}")
print(f"{c} = {(c[len(c)//2] + c[-(len(c)//2) - 1])//2}")
# numpy median를 이용한 방법
import numpy as np
print(f"{a} = {int(np.median(a))}")
print(f"{b} = {int(np.median(b))}")
print(f"{c} = {int(np.median(c))}")
package com.algorithm.algorithmpractice.dojang;
public class MiddleNumber {
public static double getMiddleNumber(int[] arrInput){
int[] arr = {17, 37, 47, 57};
for(int i = 0; i < arr.length; i++){
for(int j = i+1; j < arr.length; j++){
if(arr[i] <= arr[j]){
continue;
}
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
if(arr.length % 2 != 0){
return arr[arr.length/2];
}
return (arr[arr.length/2-1] + arr[arr.length/2])/2;
}
public static void main(String[] args) {
getMiddleNumber(null);
System.out.println(getMiddleNumber(null));
}
}
def center(a):
a.sort()
l = len(a)
if l % 2 == 0:
return sum(a[l//2-1:l//2+1])/2
else:
return a[l//2]
ui = list(map(int, input("리스트의 중앙값을 구합니다.\n리스트의 요소가 될 숫자들 입력(공백으로 구분)>> ").split()))
ui.sort()
if len(ui) % 2 != 0:
i = (1+len(ui))/2 - 1
print(ui, "=", ui[int(i)])
else:
f = round((1+len(ui))/2) - 1
b = f + 1
i = (ui[f]+ui[b])/2
print(ui, "=", int(i))
파이썬 3.8.5
test_1 = [7, 9, 14]
test_2 = [24, 31, 35, 49]
test_3 = [17, 37, 37, 47, 57]
def median(list_input):
list_input.sort()
n = len(list_input)
if n % 2 == 0 :
print( ( list_input[ n//2 ] + list_input[n//2 - 1] )/2 )
else :
print( list_input[(n-1)//2 ] )
python
import numpy as np
list1 = [7, 9, 14]
list2 = [24, 31, 35, 49]
list3 = [17, 37, 37, 47, 57]
for x in [list1, list2, list3]:
print(np.median(x))
num_list = [17, 37, 37, 47, 57]
num_list.sort()
length = len(num_list)
half = int(length / 2)
if length % 2 == 0 :
median = (num_list[half] + num_list[half - 1]) / 2
else :
median = num_list[half]
print(median)
def median(list):
return (list[len(list)//2 -1] + list[len(list)//2]) / 2 if len(list) % 2 == 0 else list[len(list)//2]
print(median([7, 9, 14]))
print(median([24, 31, 35, 49]))
print(median([17, 37, 37, 47, 57]))
Python
# math 모듈을 임포트
import math
lst = [17, 37, 37, 47, 57] # 검증을 위한 임의값
def median(list):
# 먼저 크기순으로 정렬해 줍니다
list.sort()
# 인덱스 가운데값을 구합니다
med = (len(list) - 1 ) / 2
# 올림, 내림을 이용해 가운데값을 변형합니다
a = math.floor(med)
b = math.ceil(med)
# 중간값을 구합니다
# 요소 개수가 홀수일 경우 a, b가 달라지므로 두 요소의 평균값을 구할 수 있음
# 요소 개수가 짝수일 경우 a, b가 같아지므로 같은 값을 2 곱해 2 나눠도 그대로
return (list[a] + list[b]) / 2
print(median(lst))
>>>37.0
import math
nums = list(map(int,input(">").split())))
if len(nums) % 2 != 0:
middle = nums[math.floor(len(nums)/2)]
else:
middle = (nums[math.floor(len(nums)/2-1] + nums[math.ceil(len(nums)/2)]) / 2
print(middle)
test =[[7,9,14],[24, 31, 35, 49],[17,37,37,47,57]]
for i in range(len(test)):
l, r = 0, len(test[i]) - 1
while not(l == r or l+1 == r):
l, r = l+1, r-1
print(test[i], ' = ', (test[i][l] + test[i][r])/2)