ronantakizawa/codereview-bench huggingface dataset:
Repository: samber/lo
File: map.go (Go)

Code before:
package lo

// Keys creates an array of the map keys.
// Play: https://go.dev/play/p/Uu11fHASqrU
func Keys[K comparable, V any](in map[K]V) []K {
	result := make([]K, 0, len(in))

	for k := range in {
		result = append(result, k)
	}

	return result
}

// HasKey returns whether the given key exists.
// Play: https://go.dev/play/p/aVwubIvECqS
func HasKey[K comparable, V any](in map[K]V, key K) bool {
	_, ok := in[key]
	return ok
}

// Values creates an array of the map values.
// Play: https://go.dev/play/p/nnRTQkzQfF6
func Values[K comparable, V any](in map[K]V) []V {
	result := make([]V, 0, len(in))

	for k := range in {
		result = append(result, in[k])
	}

	return result
}

// ValueOr returns the value of the given key or the fallback value if the key is not present.
// Play: https://go.dev/play/p/bAq9mHErB4V
func ValueOr[K comparable, V any](in map[K]V, key K, fallback V) V {
	if v, ok := in[key]; ok {
		return v
	}
	return fallback
}

// PickBy returns same map type filtered by given predicate.
// Play: https://go.dev/play/p/kdg8GR_QMmf

Review comment (suggestion):
may be more effective

```go
seen := make(map[K]struct{})
	
for i := range in {
  for k := range in[i] {
	seen[k] = struct{}{}
  }
}

result := make([]K, 0, len(seen))

for k := range seen {
	result = append(result, k)
}
```

Code after:
package lo

// Keys creates an array of the map keys.
// Play: https://go.dev/play/p/Uu11fHASqrU
func Keys[K comparable, V any](in ...map[K]V) []K {
	result := make([]K, 0)

	for i := range in {
		for k := range in[i] {
			result = append(result, k)
		}
	}

	return result
}

// UniqKeys creates an array of unique keys in the map.
// Play: https://go.dev/play/p/TPKAb6ILdHk
func UniqKeys[K comparable, V any](in ...map[K]V) []K {
	seen := make(map[K]struct{})
	result := make([]K, 0)

	for i := range in {
		for k := range in[i] {
			if _, exists := seen[k]; exists {
				continue
			}
			seen[k] = struct{}{}
			result = append(result, k)
		}
	}

	return result
}

// HasKey returns whether the given key exists.
// Play: https://go.dev/play/p/aVwubIvECqS
func HasKey[K comparable, V any](in map[K]V, key K) bool {
	_, ok := in[key]
	return ok
}

// Values creates an array of the map values.
// Play: https://go.dev/play/p/nnRTQkzQfF6
Repository: samber/lo
File: intersect.go (Go)

Code before:
	seen := make(map[T]struct{}, capLen)

	for i := range lists {
		for j := range lists[i] {
			if _, ok := seen[lists[i][j]]; !ok {
				seen[lists[i][j]] = struct{}{}
				result = append(result, lists[i][j])
			}
		}
	}

	return result
}

// Without returns slice excluding all given values.
func Without[T comparable, Slice ~[]T](collection Slice, exclude ...T) Slice {
	result := make(Slice, 0, len(collection))
	for i := range collection {
		if !Contains(exclude, collection[i]) {
			result = append(result, collection[i])
		}
	}
	return result
}

// WithoutBy returns a slice excluding values whose extracted key is in the exclude list.
func WithoutBy[T any, K comparable](collection []T, extract func(item T) K, exclude ...K) []T {
	result := make([]T, 0, len(collection))
	for _, item := range collection {
		if !Contains(exclude, extract(item)) {
			result = append(result, item)
		}
	}
	return result
}

// WithoutEmpty returns slice excluding empty values.
//
// Deprecated: Use lo.Compact instead.
func WithoutEmpty[T comparable, Slice ~[]T](collection Slice) Slice {
	return Compact(collection)
}


Review comment (refactor):
This is can be a much better comment I think:

// WithoutBy filters a slice by excluding elements whose extracted keys match any in the exclude list.
// It returns a new slice containing only the elements whose keys are not in the exclude list.

Code after:
	seen := make(map[T]struct{}, capLen)

	for i := range lists {
		for j := range lists[i] {
			if _, ok := seen[lists[i][j]]; !ok {
				seen[lists[i][j]] = struct{}{}
				result = append(result, lists[i][j])
			}
		}
	}

	return result
}

// Without returns slice excluding all given values.
func Without[T comparable, Slice ~[]T](collection Slice, exclude ...T) Slice {
	excludeMap := make(map[T]struct{}, len(exclude))
	for i := range exclude {
		excludeMap[exclude[i]] = struct{}{}
	}

	result := make(Slice, 0, len(collection))
	for i := range collection {
		if _, ok := excludeMap[collection[i]]; !ok {
			result = append(result, collection[i])
		}
	}
	return result
}

// WithoutBy filters a slice by excluding elements whose extracted keys match any in the exclude list.
// It returns a new slice containing only the elements whose keys are not in the exclude list.
func WithoutBy[T any, K comparable](collection []T, iteratee func(item T) K, exclude ...K) []T {
	excludeMap := make(map[K]struct{}, len(exclude))
	for _, e := range exclude {
		excludeMap[e] = struct{}{}
	}

	result := make([]T, 0, len(collection))
	for _, item := range collection {
		if _, ok := excludeMap[iteratee(item)]; !ok {
			result = append(result, item)
		}
	}
	return result
}

// WithoutEmpty returns slice excluding zero values.
//
// Deprecated: Use lo.Compact instead.
func WithoutEmpty[T comparable, Slice ~[]T](collection Slice) Slice {
Repository: samber/lo
File: find.go (Go)

Code before:
	return collection[l+n], nil
}

// Sample returns a random item from collection.
func Sample[T any](collection []T) T {
	result := SampleBy(collection, rand.IntN)
	return result
}

// SampleBy returns a random item from collection, using intFunc as the random index generator.
func SampleBy[T any](collection []T, intFunc func(int) int) T {
	size := len(collection)
	if size == 0 {
		return Empty[T]()
	}
	return collection[intFunc(size)]
}

// Samples returns N random unique items from collection.
func Samples[T any, Slice ~[]T](collection Slice, count int) Slice {
	results := SamplesBy(collection, count, rand.IntN)
	return results
}

// SamplesBy returns N random unique items from collection, using intFunc as the random index generator.
func SamplesBy[T any, Slice ~[]T](collection Slice, count int, intFunc func(int) int) Slice {
	size := len(collection)

	copy := append(Slice{}, collection...)

	results := Slice{}

	for i := 0; i < size && i < count; i++ {
		copyLength := size - i

		index := intFunc(size - i)
		results = append(results, copy[index])

		// Removes element.
		// It is faster to swap with last element and remove it.
		copy[index] = copy[copyLength-1]
		copy = copy[:copyLength-1]
	}

	return results
}


Review comment (suggestion):
```suggestion
func SamplesBy[T any, Slice ~[]T](collection Slice, count int, intFunc randomSeedFunc) Slice {
```


Code after:
	return collection[l+n], nil
}

// randomIntGenerator is a function that should return a random integer in the range [0, n)
// where n is the parameter passed to the randomIntGenerator.
type randomIntGenerator func(n int) int

// Sample returns a random item from collection.
func Sample[T any](collection []T) T {
	result := SampleBy(collection, rand.IntN)
	return result
}

// SampleBy returns a random item from collection, using randomIntGenerator as the random index generator.
func SampleBy[T any](collection []T, randomIntGenerator randomIntGenerator) T {
	size := len(collection)
	if size == 0 {
		return Empty[T]()
	}
	return collection[randomIntGenerator(size)]
}

// Samples returns N random unique items from collection.
func Samples[T any, Slice ~[]T](collection Slice, count int) Slice {
	results := SamplesBy(collection, count, rand.IntN)
	return results
}

// SamplesBy returns N random unique items from collection, using randomIntGenerator as the random index generator.
func SamplesBy[T any, Slice ~[]T](collection Slice, count int, randomIntGenerator randomIntGenerator) Slice {
	size := len(collection)

	copy := append(Slice{}, collection...)

	results := Slice{}

	for i := 0; i < size && i < count; i++ {
		copyLength := size - i

		index := randomIntGenerator(size - i)
		results = append(results, copy[index])

		// Removes element.
		// It is faster to swap with last element and remove it.
		copy[index] = copy[copyLength-1]
		copy = copy[:copyLength-1]
	}

	return results
}
Repository: samber/lo
File: string.go (Go)

Code before:
			cache, remain = rand2.Int64(), letterIdMax
		}
		if idx := int(cache & letterIdMask); idx < len(charset) {
			sb.WriteRune(charset[idx])
			i--
		}
		cache >>= letterIdBits
		remain--
	}
	return sb.String()
}

// nearestPowerOfTwo returns the nearest power of two.
func nearestPowerOfTwo(cap int) int {
	n := cap - 1
	n |= n >> 1
	n |= n >> 2
	n |= n >> 4
	n |= n >> 8
	n |= n >> 16
	if n < 0 {
		return 1
	} else if n >= MaximumCapacity {
		return MaximumCapacity
	}
	return n + 1
}

// Substring return part of a string.
// Play: https://go.dev/play/p/TQlxQi82Lu1
func Substring[T ~string](str T, offset int, length uint) T {
	rs := []rune(str)
	size := len(rs)

	if offset < 0 {
		offset = size + offset
		if offset < 0 {
			offset = 0
		}
	}

	if offset >= size {
		return Empty[T]()
	}

	if length > uint(size)-uint(offset) {
		length = uint(size - offset)
	}

	return T(strings.Replace(string(rs[offset:offset+int(length)]), "\x00", "", -1))
}

Review comment (suggestion):
```suggestion
	if n < 0 {
		return 1
	}
	if n >= MaximumCapacity {
		return MaximumCapacity
	}
	return n + 1
```


Code after:
	// e.g., for 62 characters, the bitmask would be 111111.
	var letterIdMask int64 = 1<<letterIdBits - 1
	// Available count, since rand.Int64() returns a non-negative number, the first bit is fixed, so there are 63 random bits
	// e.g., for 62 characters, this value is 10 (63 / 6).
	letterIdMax := 63 / letterIdBits
	// Generate the random string in a loop.
	for i, cache, remain := size-1, rand.Int64(), letterIdMax; i >= 0; {
		// Regenerate the random number if all available bits have been used
		if remain == 0 {
			cache, remain = rand.Int64(), letterIdMax
		}
		// Select a character from the charset
		if idx := int(cache & letterIdMask); idx < len(charset) {
			sb.WriteRune(charset[idx])
			i--
		}
		// Shift the bits to the right to prepare for the next character selection,
		// e.g., for 62 characters, shift by 6 bits.
		cache >>= letterIdBits
		// Decrease the remaining number of uses for the current random number.
		remain--
	}
	return sb.String()
}

// nearestPowerOfTwo returns the nearest power of two.
func nearestPowerOfTwo(cap int) int {
	n := cap - 1
	n |= n >> 1
	n |= n >> 2
	n |= n >> 4
	n |= n >> 8
	n |= n >> 16
	if n < 0 {
		return 1
	}
	if n >= maximumCapacity {
		return maximumCapacity
	}
	return n + 1
}

// Substring return part of a string.
// Play: https://go.dev/play/p/TQlxQi82Lu1
func Substring[T ~string](str T, offset int, length uint) T {
	rs := []rune(str)
	size := len(rs)

	if offset < 0 {
		offset = size + offset
		if offset < 0 {
Repository: samber/lo
File: slice_test.go (Go)

Code before:
		return len(item)
	})
	is.IsType(nonempty[0], allStrings, "type preserved")
}

func TestFlatten(t *testing.T) {
	t.Parallel()
	is := assert.New(t)

	result1 := Flatten([][]int{{0, 1}, {2, 3, 4, 5}})

	is.Equal([]int{0, 1, 2, 3, 4, 5}, result1)

	type myStrings []string
	allStrings := myStrings{"", "foo", "bar"}
	nonempty := Flatten([]myStrings{allStrings})
	is.IsType(nonempty, allStrings, "type preserved")
}

func TestConcat(t *testing.T) {
	t.Parallel()
	is := assert.New(t)

	result1 := Concat([][]int{{0, 1}, {2, 3, 4, 5}}...)

	is.Equal(result1, []int{0, 1, 2, 3, 4, 5})

	type myStrings []string
	allStrings := myStrings{"", "foo", "bar"}
	nonempty := Concat([]myStrings{allStrings}...)
	is.IsType(nonempty, allStrings, "type preserved")
}

func TestInterleave(t *testing.T) {
	t.Parallel()
	is := assert.New(t)

	testCases := []struct {
		name string
		in   [][]int
		want []int
	}{
		{
			"nil",
			[][]int{nil},
			[]int{},
		},
		{
			"empty",
			[][]int{},
			[]int{},

Review comment (suggestion):
```suggestion
	is.Equal([]int{0, 1, 2, 3, 4, 5}, result1)
```

Code after:
		return len(item)
	})
	is.IsType(nonempty[0], allStrings, "type preserved")
}

func TestFlatten(t *testing.T) {
	t.Parallel()
	is := assert.New(t)

	result1 := Flatten([][]int{{0, 1}, {2, 3, 4, 5}})

	is.Equal([]int{0, 1, 2, 3, 4, 5}, result1)

	type myStrings []string
	allStrings := myStrings{"", "foo", "bar"}
	nonempty := Flatten([]myStrings{allStrings})
	is.IsType(nonempty, allStrings, "type preserved")
}

func TestConcat(t *testing.T) {
	t.Parallel()
	is := assert.New(t)

	result1 := Concat([][]int{{0, 1}, {2, 3, 4, 5}}...)

	is.Equal([]int{0, 1, 2, 3, 4, 5}, result1)

	type myStrings []string
	allStrings := myStrings{"", "foo", "bar"}
	nonempty := Concat([]myStrings{allStrings}...)
	is.IsType(nonempty, allStrings, "type preserved")
}

func TestInterleave(t *testing.T) {
	t.Parallel()
	is := assert.New(t)

	testCases := []struct {
		name string
		in   [][]int
		want []int
	}{
		{
			"nil",
			[][]int{nil},
			[]int{},
		},
		{
			"empty",
			[][]int{},
			[]int{},
Repository: samber/lo
File: lo_example_test.go (Go)

Code before:
	fmt.Printf("%v\n", result)

	result = Replace(list, -1, 42, 1)
	fmt.Printf("%v\n", result)

	result = Replace(list, 0, 42, 2)
	fmt.Printf("%v\n", result)

	result = Replace(list, 0, 42, -1)
	fmt.Printf("%v\n", result)

	// Output:
	// [42 1 0 1 2 3 0]
	// [0 1 0 1 2 3 0]
	// [42 1 42 1 2 3 0]
	// [42 1 42 1 2 3 42]
}

func ExampleClone() {
	list := []int{1, 2, 3, 4, 5}

	result := Clone(list)

	fmt.Printf("%v", result)
	// Output: [1 2 3 4 5]
}

func ExampleCompact() {
	list := []string{"", "foo", "", "bar", ""}

	result := Compact(list)

	fmt.Printf("%v", result)

	// Output: [foo bar]
}

func ExampleIsSorted() {
	list := []int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}

	result := IsSorted(list)

	fmt.Printf("%v", result)

	// Output: true
}

func ExampleIsSortedByKey() {
	list := []string{"a", "bb", "ccc"}

	result := IsSortedByKey(list, func(s string) int {

Review comment (suggestion):
```suggestion
	input := []int{1, 2, 3, 4, 5}

	output := Clone(input)
	input[0] = 42

	fmt.Printf("%v", output)
	// Output: [1 2 3 4 5]
}
```

Code after:
	fmt.Printf("%v\n", result)

	result = Replace(list, -1, 42, 1)
	fmt.Printf("%v\n", result)

	result = Replace(list, 0, 42, 2)
	fmt.Printf("%v\n", result)

	result = Replace(list, 0, 42, -1)
	fmt.Printf("%v\n", result)

	// Output:
	// [42 1 0 1 2 3 0]
	// [0 1 0 1 2 3 0]
	// [42 1 42 1 2 3 0]
	// [42 1 42 1 2 3 42]
}

func ExampleClone() {
	input := []int{1, 2, 3, 4, 5}

	output := Clone(input)
	input[0] = 42

	fmt.Printf("%v", output)
	// Output: [1 2 3 4 5]
}

func ExampleCompact() {
	list := []string{"", "foo", "", "bar", ""}

	result := Compact(list)

	fmt.Printf("%v", result)

	// Output: [foo bar]
}

func ExampleIsSorted() {
	list := []int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}

	result := IsSorted(list)

	fmt.Printf("%v", result)

	// Output: true
}

func ExampleIsSortedByKey() {
	list := []string{"a", "bb", "ccc"}
Repository: scikit-learn/scikit-learn
File: sklearn/metrics/pairwise.py (Python)

Code before:
    MissingValues,
    Options,
    StrOptions,
    validate_params,
)
from sklearn.utils.deprecation import _deprecate_force_all_finite
from sklearn.utils.extmath import row_norms, safe_sparse_dot
from sklearn.utils.fixes import parse_version, sp_base_version
from sklearn.utils.parallel import Parallel, delayed
from sklearn.utils.validation import _num_samples, check_non_negative


# Utility Functions
def _return_float_dtype(X, Y):
    """
    1. If dtype of X and Y is float32, then dtype float32 is returned.
    2. Else dtype float is returned.
    """
    xp, _ = get_namespace(X, Y)
    if not issparse(X) and not isinstance(X, np.ndarray):
        X = xp.asarray(X)

    if Y is None:
        Y_dtype = X.dtype
    elif not issparse(Y) and not isinstance(Y, np.ndarray):
        Y = xp.asarray(Y)
        Y_dtype = Y.dtype
    else:
        Y_dtype = Y.dtype

    if X.dtype == Y_dtype == np.float32:
        dtype = np.float32
    else:
        dtype = float

    return X, Y, dtype


def _find_floating_dtype_allow_sparse(X, Y, xp=None):
    """Find matching floating type, allowing for sparse input."""
    if any([issparse(X), issparse(Y)]) or _is_numpy_namespace(xp):
        X, Y, dtype_float = _return_float_dtype(X, Y)
    else:
        dtype_float = _find_matching_floating_dtype(X, Y, xp=xp)
    return X, Y, dtype_float


def check_pairwise_arrays(
    X,
    Y,
    *,

Review comment (refactor):
I have the feeling that this line is not needed. Can you try to remove it? Then we can simplify the if / else structure of this code.

Code after:
    MissingValues,
    Options,
    StrOptions,
    validate_params,
)
from sklearn.utils.extmath import row_norms, safe_sparse_dot
from sklearn.utils.fixes import parse_version, sp_base_version
from sklearn.utils.parallel import Parallel, delayed
from sklearn.utils.validation import _num_samples, check_non_negative


# Utility Functions
def _return_float_dtype(X, Y):
    """
    1. If dtype of X and Y is float32, then dtype float32 is returned.
    2. Else dtype float is returned.
    """
    xp, _ = get_namespace(X, Y)
    if not issparse(X) and not isinstance(X, np.ndarray):
        X = xp.asarray(X)

    if Y is None:
        Y_dtype = X.dtype
    elif not issparse(Y) and not isinstance(Y, np.ndarray):
        Y = np.asarray(Y)
        Y_dtype = Y.dtype
    else:
        Y_dtype = Y.dtype

    if X.dtype == Y_dtype == np.float32:
        dtype = np.float32
    else:
        dtype = float

    return X, Y, dtype


def _find_floating_dtype_allow_sparse(X, Y, xp=None):
    """Find matching floating type, allowing for sparse input."""
    if any([issparse(X), issparse(Y)]) or _is_numpy_namespace(xp):
        X, Y, dtype_float = _return_float_dtype(X, Y)
    else:
        dtype_float = _find_matching_floating_dtype(X, Y, xp=xp)
    return X, Y, dtype_float


def check_pairwise_arrays(
    X,
    Y,
    *,
    precomputed=False,
Repository: scikit-learn/scikit-learn
File: sklearn/metrics/pairwise.py (Python)

Code before:
        An optional second feature array. If `None`, uses `Y=X`.

    gamma : float, default=None
        Coefficient of the vector inner product. If None, defaults to 1.0 / n_features.

    coef0 : float, default=1
        Constant offset added to scaled inner product.

    Returns
    -------
    kernel : ndarray of shape (n_samples_X, n_samples_Y)
        Sigmoid kernel between two arrays.

    Examples
    --------
    >>> from sklearn.metrics.pairwise import sigmoid_kernel
    >>> X = [[0, 0, 0], [1, 1, 1]]
    >>> Y = [[1, 0, 0], [1, 1, 0]]
    >>> sigmoid_kernel(X, Y)
    array([[0.76, 0.76],
           [0.87, 0.93]])
    """
    xp, _ = get_namespace(X, Y)
    X, Y = check_pairwise_arrays(X, Y)
    xp, _ = get_namespace(X, Y)

    if gamma is None:
        gamma = 1.0 / X.shape[1]

    K = safe_sparse_dot(X, Y.T, dense_output=True)
    K *= gamma
    K += coef0

    # compute tanh in-place for numpy
    K = _modify_in_place_if_numpy(xp, xp.tanh, K, out=K)
    return K


@validate_params(
    {
        "X": ["array-like", "sparse matrix"],
        "Y": ["array-like", "sparse matrix", None],
        "gamma": [
            Interval(Real, 0, None, closed="left"),
            None,
            Hidden(np.ndarray),
        ],
    },
    prefer_skip_nested_validation=True,
)
def rbf_kernel(X, Y=None, gamma=None):

Review comment (bug):
`xp` is already retrieved 2 lines above. The call `check_pairwise` array should not change the namespace of `X` and `Y`. If it does, this is probably a bug and should be fixed.

```suggestion
```

Code after:
    Y : {array-like, sparse matrix} of shape (n_samples_Y, n_features), default=None
        An optional second feature array. If `None`, uses `Y=X`.

    gamma : float, default=None
        Coefficient of the vector inner product. If None, defaults to 1.0 / n_features.

    coef0 : float, default=1
        Constant offset added to scaled inner product.

    Returns
    -------
    kernel : ndarray of shape (n_samples_X, n_samples_Y)
        Sigmoid kernel between two arrays.

    Examples
    --------
    >>> from sklearn.metrics.pairwise import sigmoid_kernel
    >>> X = [[0, 0, 0], [1, 1, 1]]
    >>> Y = [[1, 0, 0], [1, 1, 0]]
    >>> sigmoid_kernel(X, Y)
    array([[0.76, 0.76],
           [0.87, 0.93]])
    """
    xp, _ = get_namespace(X, Y)
    X, Y = check_pairwise_arrays(X, Y)

    if gamma is None:
        gamma = 1.0 / X.shape[1]

    K = safe_sparse_dot(X, Y.T, dense_output=True)
    K *= gamma
    K += coef0

    # compute tanh in-place for numpy
    K = _modify_in_place_if_numpy(xp, xp.tanh, K, out=K)
    return K


@validate_params(
    {
        "X": ["array-like", "sparse matrix"],
        "Y": ["array-like", "sparse matrix", None],
        "gamma": [
            Interval(Real, 0, None, closed="left"),
            None,
            Hidden(np.ndarray),
        ],
    },
    prefer_skip_nested_validation=True,
)
def rbf_kernel(X, Y=None, gamma=None):
Repository: scikit-learn/scikit-learn
File: sklearn/metrics/pairwise.py (Python)

Code before:
    Interval,
    MissingValues,
    Options,
    StrOptions,
    validate_params,
)
from sklearn.utils.deprecation import _deprecate_force_all_finite
from sklearn.utils.extmath import row_norms, safe_sparse_dot
from sklearn.utils.fixes import parse_version, sp_base_version
from sklearn.utils.parallel import Parallel, delayed
from sklearn.utils.validation import _num_samples, check_non_negative


# Utility Functions
def _return_float_dtype(X, Y):
    """
    1. If dtype of X and Y is float32, then dtype float32 is returned.
    2. Else dtype float is returned.
    """
    xp, _ = get_namespace(X, Y)
    if not issparse(X) and not isinstance(X, np.ndarray):
        X = xp.asarray(X)

    if Y is None:
        Y_dtype = X.dtype
    else:
        Y_dtype = Y.dtype

    if X.dtype == Y_dtype == np.float32:
        dtype = np.float32
    else:
        dtype = float

    return X, Y, dtype


def _find_floating_dtype_allow_sparse(X, Y, xp=None):
    """Find matching floating type, allowing for sparse input."""
    if any([issparse(X), issparse(Y)]) or _is_numpy_namespace(xp):
        X, Y, dtype_float = _return_float_dtype(X, Y)
    else:
        dtype_float = _find_matching_floating_dtype(X, Y, xp=xp)
    return X, Y, dtype_float


def check_pairwise_arrays(
    X,
    Y,
    *,
    precomputed=False,
    dtype="infer_float",

Review comment (suggestion):
Question, why delete this?

This is the cause of the `AttributeError: 'list' object has no attribute 'dtype'` and `AttributeError: 'tuple' object has no attribute 'dtype'` errors, for when `Y` is not an array.

Code after:
    Interval,
    MissingValues,
    Options,
    StrOptions,
    validate_params,
)
from sklearn.utils.extmath import row_norms, safe_sparse_dot
from sklearn.utils.fixes import parse_version, sp_base_version
from sklearn.utils.parallel import Parallel, delayed
from sklearn.utils.validation import _num_samples, check_non_negative


# Utility Functions
def _return_float_dtype(X, Y):
    """
    1. If dtype of X and Y is float32, then dtype float32 is returned.
    2. Else dtype float is returned.
    """
    xp, _ = get_namespace(X, Y)
    if not issparse(X) and not isinstance(X, np.ndarray):
        X = xp.asarray(X)

    if Y is None:
        Y_dtype = X.dtype
    elif not issparse(Y) and not isinstance(Y, np.ndarray):
        Y = np.asarray(Y)
        Y_dtype = Y.dtype
    else:
        Y_dtype = Y.dtype

    if X.dtype == Y_dtype == np.float32:
        dtype = np.float32
    else:
        dtype = float

    return X, Y, dtype


def _find_floating_dtype_allow_sparse(X, Y, xp=None):
    """Find matching floating type, allowing for sparse input."""
    if any([issparse(X), issparse(Y)]) or _is_numpy_namespace(xp):
        X, Y, dtype_float = _return_float_dtype(X, Y)
    else:
        dtype_float = _find_matching_floating_dtype(X, Y, xp=xp)
    return X, Y, dtype_float


def check_pairwise_arrays(
    X,
    Y,
    *,