Problem:


  MathJax.Hub.Config({ tex2jax: { inlineMath: [["$","$"], ["\\(","\\)"]], processEscapes: true }});

Distance II

  Your task is to calculate the distance between two $n$ dimensional vectors $x = \{x_1, x_2, ..., x_n\}$ and $y = \{y_1, y_2, ..., y_n\}$.

  The Minkowski's distance defined below is a metric which is a generalization of both the Manhattan distance and the Euclidean distance.

\[
D_{xy} = (\sum_{i=1}^n |x_i - y_i|^p)^{\frac{1}{p}}
\]

It can be the Manhattan distance 

\[
D_{xy} = |x_1 - y_1| + |x_2 - y_2| + ... + |x_n - y_n|
\]

where $p = 1 $.

It can be the Euclidean distance

\[
D_{xy} = \sqrt{(|x_1 - y_1|)^{2} + (|x_2 - y_2|)^{2} + ... + (|x_n - y_n|)^{2}}
\]

where $p = 2 $.

Also, it can be the Chebyshev distance

\[
D_{xy} = max_{i=1}^n (|x_i - y_i|)
\]

where $p = \infty$

Write a program which reads two $n$ dimensional vectors $x$ and $y$, and calculates Minkowski's distance where $p = 1, 2, 3, \infty$ respectively.

Input

  In the first line, an integer $n$ is given. In the second and third line, $x = \{x_1, x_2, ... x_n\}$ and $y = \{y_1, y_2, ... y_n\}$ are given respectively. The elements in $x$ and $y$ are given in integers.

Output

  Print the distance where $p = 1, 2, 3$ and $\infty$ in a line respectively.
The output should not contain an absolute error greater than 10-5.

Constraints

$1 \leq n \leq 100$

$0 \leq x_i, y_i \leq 1000$

Sample Input

3
1 2 3
2 0 4

Sample Output

4.000000
2.449490
2.154435
2.000000



Sample input:
3
1 2 3
2 0 4


Sample output:
4.000000
2.449490
2.154435
2.000000

Submission status: Runtime Error

Solution code:
# coding: utf-8
# Here your code !

def calculate_minkowski_distances():
    _ = input()
    data = []
    for i in range(2):
        data.append([float(value) for value in input().rstrip().split()])
    for exponent in (1, 2, 3, float("inf")):
        print("{0:.6f}".format(minkowski_distance(*data, exponent)))

def minkowski_distance(vector_x, vector_y, exponent):
    abs_xy = [ abs(pair[0] - pair[1]) for pair in zip(vector_x, vector_y) ]

    m_dis = 0
    if exponent == float("inf") :
        m_dis = max(abs_xy)
    elif exponent == 0 :
        m_dis = nan
    else :
        m_dis = ( sum([ elem**exponent for elem in abs_xy ])**(1/exponent) )
    
    return m_dis

if __name__ == "__main__" :
    calculate_minkowski_distances()

Submission status: Runtime Error

Solution code:
# coding: utf-8
# Here your code !
import sys
import collections
#import math
import unittest

def calculate_minkowski_distances():
    _ = input()
    data = []
    for i in range(2):
        data.append([float(value) for value in input().rstrip().split()])
#    lines = sys.stdin.readlines()[1:]
#    for line in lines:
#        data.append([ float(value) for value in line.rstrip().split() ])

    for exponent in (1, 2, 3, float("inf")):
        print("{0:.8f}".format(minkowski_distance(*data, exponent)))

def minkowski_distance(vector_x, vector_y, exponent):
    abs_xy = [ abs(pair[0] - pair[1]) for pair in zip(vector_x, vector_y) ]

    m_dis = 0
    if exponent == float("inf") :
        m_dis = max(abs_xy)
    elif exponent == 0 :
        m_dis = nan
    else :
        m_dis = ( sum([ elem**exponent for elem in abs_xy ])**(1/exponent) )
    
    return m_dis
'''
def __input_error():
    print("input error")
    return -1

class __TestValueClass(unittest.TestCase):
    def testEqual(self, func, tuples, eff_digit = math.nan, print_success = False):
        self.testFunction(self.assertEqual,func,tuples,eff_digit,print_success)
    
    def testFunction(self,assertfunc,func,tuples,eff_digit,print_success):
        #tuples[index] = ([*arguments of func], compared value)
        for item in tuples:
            try:
                if isinstance(item[0], collections.Iterable):
                    value = func(*item[0])
                else:
                    value = func(item[0])
                
                if math.isnan(eff_digit) :
                    assertfunc(value,item[1])
                else :
                    format_str = "{0:."+str(eff_digit)+"g}"
                    assertfunc(format_str.format(value),format_str.format(item[1]))
                    
            except Exception as msg:
                swidth = 15
                print("="*50)
                print("-- Assertion Error in '" + func.__name__ + "' --")
                print("arguments".ljust(swidth)+":",item[0])
                print("compared value".ljust(swidth)+":",item[1])
                print("message".ljust(swidth)+":")
                print(msg)
                sys.exit()
        if print_success :
            print(func.__name__,": succeeded")
'''
#test
if __name__ == "__main__" :

#    test = __TestValueClass()
#    vec_x = [1, 2, 3]
#    vec_y = [2, 0, 4]
#    test.testEqual(minkowski_distance, [([vec_x, vec_y, 1], 4),         ([vec_x, vec_y, 2], 2.449490)], eff_digit = 5)
#    test.testEqual(minkowski_distance, [([vec_x, vec_y, 3], 2.154435),  ([vec_x, vec_y, math.inf], 2)], eff_digit = 5)#, print_success = True)

    
    calculate_minkowski_distances()

Submission status: Runtime Error

Solution code:
# coding: utf-8
# Here your code !

def calculate_minkowski_distances():
    _ = input()
    data = []
    for i in range(2):
        data.append([float(value) for value in input().rstrip().split()])

    for exponent in (1, 2, 3, float("inf")):
        print("{0:.8f}".format(minkowski_distance(*data, exponent)))

def minkowski_distance(vector_x, vector_y, exponent):
    abs_xy = [ abs(pair[0] - pair[1]) for pair in zip(vector_x, vector_y) ]

    m_dis = 0
    if exponent == float("inf") :
        m_dis = max(abs_xy)
    elif exponent == 0 :
        m_dis = nan
    else :
        m_dis = ( sum([ elem**exponent for elem in abs_xy ])**(1/exponent) )
    
    return m_dis

if __name__ == "__main__" :
    calculate_minkowski_distances()

Submission status: Runtime Error

Solution code:
# coding: utf-8
# Here your code !

def calculate_minkowski_distances():
    _ = input()
    data = []
    for i in range(2):
        data.append([float(value) for value in input().rstrip().split()])

    for exponent in (1, 2, 3, float("inf")):
        print("{0:.8f}".format(minkowski_distance(*data, exponent)))

def minkowski_distance(vector_x, vector_y, exponent):
#    abs_xy = [ abs(pair[0] - pair[1]) for pair in zip(vector_x, vector_y) ]
    abs_xy = [abs(vector_x[i] - vector_y[i]) for i in range(len(vector_x))]
    
    m_dis = 0
    if exponent == float("inf") :
        m_dis = max(abs_xy)
    elif exponent == 0 :
        m_dis = nan
    else :
        m_dis = ( sum([ elem**exponent for elem in abs_xy ])**(1/exponent) )
    
    return m_dis

if __name__ == "__main__" :
    calculate_minkowski_distances()

Submission status: Runtime Error

Solution code:
# coding: utf-8
# Here your code !

def calculate_minkowski_distances():
    _ = input()
    data = []
    for i in range(2):
        data.append([float(value) for value in input().rstrip().split()])

    for exponent in (1, 2, 3, float("inf")):
        print(minkowski_distance(*data, exponent))
#        print("{0:.8f}".format(minkowski_distance(*data, exponent)))

def minkowski_distance(vector_x, vector_y, exponent):
#    abs_xy = [ abs(pair[0] - pair[1]) for pair in zip(vector_x, vector_y) ]
    abs_xy = [abs(vector_x[i] - vector_y[i]) for i in range(len(vector_x))]
    
    m_dis = 0
    if exponent == float("inf") :
        m_dis = max(abs_xy)
    elif exponent == 0 :
        m_dis = nan
    else :
        m_dis = ( sum([ elem**exponent for elem in abs_xy ])**(1/exponent) )
    
    return m_dis

if __name__ == "__main__" :
    calculate_minkowski_distances()

Submission status: Runtime Error

Solution code:
# coding: utf-8
# Here your code !

def calculate_minkowski_distances():
    _ = input()
    data = []
    for i in range(2):
        data.append([int(value) for value in input().rstrip().split()])

    for exponent in (1, 2, 3, float("inf")):
        print(minkowski_distance(*data, exponent))
#        print("{0:.8f}".format(minkowski_distance(*data, exponent)))

def minkowski_distance(vector_x, vector_y, exponent):
#    abs_xy = [ abs(pair[0] - pair[1]) for pair in zip(vector_x, vector_y) ]
    abs_xy = [abs(vector_x[i] - vector_y[i]) for i in range(len(vector_x))]
    
    m_dis = 0
    if exponent == float("inf") :
        m_dis = max(abs_xy)
    elif exponent == 0 :
        m_dis = nan
    else :
        m_dis = sum([ elem**exponent for elem in abs_xy ])**(1/exponent)
    
    return m_dis

if __name__ == "__main__" :
    calculate_minkowski_distances()

Submission status: Runtime Error

Solution code:


def dis_func(n, x, y):
    dis = [round(0, 6) for i in range(n+1)]
    for x, y in zip(x, y):
        tmp = abs(x - y)
        dis[0] += tmp
        dis[1] += (tmp ** 2)
        dis[2] += (tmp ** 3)
        dis[3] = max(dis[3], tmp)

    dis[1] = dis[1] ** (1/2)
    dis[2] = dis[2] ** (1/3)
    print('\n'.join(list(map(str, dis))))


if __name__ == '__main__':
    n = int(input())
    x = list(map(int, input().split()))
    y = list(map(int, input().split()))

    dis_func(n, x, y)

Submission status: Runtime Error

Solution code:
n = int(input())
X = [int(i) for i in input().split(" ")]
Y = [int(i) for i in input().split(" ")]

#p = 1,2,3
for p in range(1, 4):
   print("{:.6f}".format(sum( [abs(a - b) ** p) for a, b in zip(X,Y) ] ) ** (1 / p) ) )

#p = infinity
print("{:.6f}".format(max( [ abs(a - b) for a, b in zip(X, Y) ] ) ) )

Submission status: Runtime Error

Solution code:
n = int(input())
X = [int(i) for i in input().split(" ")]
Y = [int(i) for i in input().split(" ")]

for p in range(1, 4):
   print("{:.6f}".format(sum( [abs(a - b) ** p) for a, b in zip(X,Y) ] ) ** (1 / p) ) )

print("{:.6f}".format(max( [ abs(a - b) for a, b in zip(X, Y) ] ) ) )

Submission status: Runtime Error

Solution code:
n = int(input())
X = [int(i) for i in input().split(" ")]
Y = [int(i) for i in input().split(" ")]

for p in range(1, 4):
    print("{:.6f}".format(sum( [abs(a - b) ** p) for a, b in zip(X,Y) ] ) ** (1 / p) ) )

print("{:.6f}".format(max( [ abs(a - b) for a, b in zip(X, Y) ] ) ) )

Submission status: Runtime Error

Solution code:
#!/usr/bin/env python
import math

chebyshev = []

n = int(input())

x = input().split()
y = input().split()

for i in range(n):
    x[i] = int(x[i])
for i in range(n):
    y[i] = int(y[i])

for p in range(3):
    total = 0
    for i in range(n):
        total += (math.fabs(x[i]-y[i]))**(p+1)
    distance = total**(1/(p+1))
    print("%.5f" % distance)

for i in range(n):
    chebyshev.append(math.abs(x[i]-y[i]))
print("%.5f" % max(chebyshev))

Submission status: Runtime Error

Solution code:
#ITP1_10-D Distance2
n = int(input())
x = float().split(" ")
y = float().split(" ")

d1=0.0
for i in range(n):
    d1 += abs(x[i]-y[i])
print(d1)

d2=0.0
for i in range(n):
    d2 += (x[i]-y[i])**2
print(d2**0.5)

d3=0.0
for i in range(n):
    d3 += (x[i]-y[i])**3
print(d3**(1.0/3.0))

d_inf=0.0
for i in range(n):
    if abs(x[i]-y[i])>d_inf:
        d_inf = x[i]-y[i]
print(d_inf)

Submission status: Runtime Error

Solution code:
def distance(x,y,n):
    return sum(abs(x[i]-y[i])**n for i in range(len(n))) **(1/n)

n = int(input())
x = list(map(float,input().split()))
y = list(map(float,input().split()))
for i in range(1,4):
    print(distance(x,y,i))
print(max(abs(x[i]-y[i]) for i in range(n)))

Submission status: Runtime Error

Solution code:
import math
n = int(input())
x = list(map(int, input().split()))
y = list(map(int, input().split()))
tmp = [[0 for i in range(6)] for j in range(n+1)]
absDiff = abs(x[0]-y[0])
tmp[0][3] = tmp[0][0] = absDiff
tmp[0][4] = tmp[0][1] = absDiff ** 2
tmp[0][5] = tmp[0][2] = absDiff ** 3
max = absDiff
for i in range(1, n, 1):
    absDiff = abs(x[i]-y[i])
    tmp[i][0] = absDiff
    tmp[i][1] = absDiff ** 2
    tmp[i][2] = absDiff ** 3
    tmp[i][3] = tmp[i-1][3] + tmp[i][0]
    tmp[i][4] = tmp[i-1][4] + tmp[i][1]
    tmp[i][5] = tmp[i-1][5] + tmp[i][2]
    if absDiff > max:
        max = absDiff
print(tmp[i][3])
print(math.sqrt(tmp[i][4]))
print(tmp[i][5] ** (1/3))
print(max)

Submission status: Runtime Error

Solution code:
def min_dist(x_b,y_b):
    s=0
    for x,y in zip(x_b,y_b):
        s+=abs(x-y)
    return s

def man_dist(x_b,y_b):
    s=0
    for x, y in zip(x_b,y_b):
        s+=(abs(x-y))**2
    return s**0.5

def che_dist(x_b,y_b):
    s=0
    for x,y in zip(x_b,y_b):
        s+=(abs(x-y))**3
    return s**(1/3)

def anf_dist(x_b,y_b):
    s=[abs(x-y) for x,y in zip(x_b,y_b)]
    return max(s)

n=int(input())
y_b=list(map(int,input().split()))

print(min_dist(x_b,y_b))
print(man_dist(x_b,y_b))
print(che_dist(x_b,y_b))
print(anf_dist(x_b,y_b))

Submission status: Runtime Error

Solution code:
import math
n=int(input())
xli=list(map(int,input().split())
yli=list(map(int,input().split())
a=0
b=0
c=0
d=0

for x,y in zip(xli,yli):
    base = math.fabs(x,y)
    a += base
    b += base**2
    c += base**3
    if d < base : d = base

print(a)
print(b**(1/2))
print(c**(1/3))
print(d)

Submission status: Runtime Error

Solution code:
import math
n=int(input())
xli=list(map(int,input().split()))
yli=list(map(int,input().split()))
a=0
b=0
c=0
d=0

for x,y in zip(xli,yli):
    base = math.fabs(x,y)
    a += base
    b += base**2
    c += base**3
    if d < base : d = base

print(a)
print(b**(1/2))
print(c**(1/3))
print(d)

Submission status: Runtime Error

Solution code:
import math
n=int(input())
xli=list(map(float,input().split())
yli=list(map(float,input().split())
a=0
b=0
c=0
d=0
 
for x,y in zip(xli,yli):
    base = math.fabs(x-y)
    a += base
    b += base**2
    c += base**3
    if d < base : d = base
 
print(a)
print(b**(1/2))
print(c**(1/3))
print(d)

Submission status: Runtime Error

Solution code:
import math
ni = int(input())
xi = map(int, raw_input().split())
yi = map(int, raw_input().split())

p1 = []
p2 = []
p3 = []
p4 = []
for x, y in zip(xi, yi):
    p1.append(abs(x - y))
    p2.append(abs(x - y)**2)
    p3.append(abs(x - y)**3)
    p4.append(abs(x - y))

print '%.6f' % reduce(lambda x, y: x + y,
print '%.6f' % reduce(lambda x, y: x + y,
print '%.6f' % reduce(lambda x, y: x + y,
print '%.6f' % max(p4)

Submission status: Runtime Error

Solution code:
import math
ni = int(input())
xi = map(int, raw_input().split(
yi = map(int, raw_input().split(

p1 = []
p2 = []
p3 = []
p4 = []
for x, y in zip(xi, yi):
    p1.append(abs(x - y))
    p2.append(abs(x - y)**2)
    p3.append(abs(x - y)**3)
    p4.append(abs(x - y))

print '%.8f' % reduce(lambda x, 
print '%.8f' % reduce(lambda x, 
print '%.8f' % reduce(lambda x, 
print '%.8f' % max(p4)

Submission status: Runtime Error

Solution code:
while True:
    n = int( input() )
    if n==0:
        break
    a=list(map(int, input().split()))
    m=sum(a)/n
    s=0
    for i in a:
        s+=(i-m)**2
    print( ( s/n)**0.5 )

Submission status: Runtime Error

Solution code:
import math

def str2list(str):
	result = []
	for value in str.split(' '):
		result.append(int(value))
	return result

def distance1(n, x, y):
	result = 0
	for i in range(n):
		result += abs(x[i] - y[i])
		
	return result
	
def distance2(n, x, y):
	result = 0
	for i in range(n):
		result += (x[i] - y[i]) * (x[i] - y[i])
		
	return math.sqrt(result)
	
def distance3(n, x, y):
	result = 0
	for i in range(n):
		result += math.pow(abs(x[i] - y[i]), 3)
		
	return math.exp(math.log(result)/3)
	
def distanceInf(n, x, y):
	result = 0
	for i in range(n):
		new_result = abs(x[i] - y[i])
		result = new_result if new_result > result else result
		
	return result

n = int(input());
x = str2list(input())
y = str2list(input())

print('%.6f'%distance1(n, x, y))
print('%.6f'%distance2(n, x, y))
print('%.6f'%distance3(n, x, y))
print('%.6f'%distanceInf(n, x, y))

Submission status: Runtime Error

Solution code:
import math

def str2list(str):
	result = []
	for value in str.split(' '):
		result.append(int(value))
	return result

def distance1(n, x, y):
	result = 0
	for i in range(n):
		result += abs(x[i] - y[i])
		
	return result
	
def distance2(n, x, y):
	result = 0
	for i in range(n):
		result += (x[i] - y[i]) * (x[i] - y[i])
		
	return math.sqrt(result)
	
def distance3(n, x, y):
	result = 0
	for i in range(n):
		result += math.pow(abs(x[i] - y[i]), 3)
		
	return math.exp(math.log(result)/3)
	
def distanceInf(n, x, y):
	result = 0
	for i in range(n):
		new_result = abs(x[i] - y[i])
		result = new_result if new_result > result else result
		
	return result

n = int(input());
x = str2list(input())
y = str2list(input())

print('%.6f'%distance1(n, x, y))
print('%.6f'%distance2(n, x, y))
print('%.6f'%distance3(n, x, y))
print('%.6f'%distanceInf(n, x, y))
import math

def str2list(str):
	result = []
	for value in str.split(' '):
		result.append(int(value))
	return result

def distance1(n, x, y):
	result = 0
	for i in range(n):
		result += abs(x[i] - y[i])
		
	return result
	
def distance2(n, x, y):
	result = 0
	for i in range(n):
		result += (x[i] - y[i]) * (x[i] - y[i])
		
	return math.sqrt(result)
	
def distance3(n, x, y):
	result = 0
	for i in range(n):
		result += math.pow(abs(x[i] - y[i]), 3)
		
	return math.exp(math.log(result)/3)
	
def distanceInf(n, x, y):
	result = 0
	for i in range(n):
		new_result = abs(x[i] - y[i])
		result = new_result if new_result > result else result
		
	return result

n = int(input());
x = str2list(input())
y = str2list(input())

print('%.6f'%distance1(n, x, y))
print('%.6f'%distance2(n, x, y))
print('%.6f'%distance3(n, x, y))
print('%.6f'%distanceInf(n, x, y))

Submission status: Runtime Error

Solution code:
from math import *
import numpy as np
input()
P1 = []
P2 = []
P3 = []
for a, b in zip(map(int, input().split()), map(int, input().split())):
    t = abs(a - b)
    P1.append(t)
    P2.append(t ** 2)
    P3.append(t ** 3)
print("{:f}".format(sum(P1)))
print(sqrt(sum(P2)))
print(np.cbrt(sum(P3)))
print("{:f}".format(max(P1)))

Submission status: Runtime Error

Solution code:
n=int(input())
x,y=[list(map(int,input().split()))for in range(2)]
d=[abs(s-t)for s,t in zip(x,y)]
f=lambda n:sum([s**n for s in d])**(1/n)
print(f(1),f(2),f(3),max(d),sep='\n')

Submission status: Runtime Error

Solution code:
import math
import numpy as np

s = int(input())

all_list = []

for _ in range(2):
    all_list.append(list(map(float, input().split())))

p1 = sum([math.fabs(x - y) for x, y in zip(all_list[0], all_list[1])])
p2 = math.sqrt(sum([(math.fabs(x - y))**2 for x, y in zip(all_list[0], all_list[1])]))
p3 = np.cbrt(sum([(math.fabs(x - y))**3 for x, y in zip(all_list[0], all_list[1])]))
pi = max([math.fabs(x - y) for x, y in zip(all_list[0], all_list[1])])

print("{:.6f}".format(p1))
print("{:.6f}".format(p2))
print("{:.6f}".format(p3))
print("{:.6f}".format(pi))

Submission status: Runtime Error

Solution code:
# -*- coding: utf-8 -*-

import math

n = int(input())
x = list(map(float, input().split()))
y = list(map(float, input().split()))
abs_xy = []

for i in range(n):
    abs_xy.append(abs(x[i] - y[i]))

d1 = sum(abs_xy)

d2 = 0
for i in range(n):
    d2 += abs_xy * abs_xy
d2 = math.sqrt(d2)

d3 = 0
for i in range(n):
    d3 += abs_xy * abs_xy * abs_xy
d3 = math.pow(d3, 1/3)

d = max(abs_xy)

print(d1)
print(d2)
print(d3)
print(d)

Submission status: Runtime Error

Solution code:
n=map(int,raw_input().split())
x1, y1, x2, y2 = map(float, raw_input().split())
print ((x1-x2)**2 + (y1-y2)**2)**0.5

Submission status: Runtime Error

Solution code:
import math
def mink(x,y,p):
    return (sum([math.fabs(_x - _y)**p for _x, _y in zip(x,y)]))**(1/p)
n = int(input())
x = [int(i) for i in input().split()]
y = [int(i) for i in input().split()]
print(mink(x,y,1))
print(mink(x,y,2))
print(mink(x,y,3))
print(mink(x,y,10**9))