code: def weighted_sum(
      items: Sequence[T],
      weights: Sequence[float | None] = cast(
          Sequence[Optional[float]], None
      ),
  ) -> T:
      """Return a weighted sum of items.
  
      Items can be list of tensors, numpy arrays, or nested lists / dicts.
  
      If ``weights`` is None, this is simply an unweighted sum.
      """
  
      if weights is None:
          weights = [None] * len(items)
  
      assert len(items) == len(weights) > 0
      elem = items[0]
      unsupported_msg = (
          "Unsupported element type in weighted sum: {}. Value is: {}"
      )
  
      if isinstance(elem, str):
          # Need to check this first. Otherwise it goes into sequence and causes infinite recursion.
          raise TypeError(unsupported_msg.format(type(elem), elem))
  
      try:
          if isinstance(
              elem, (torch.Tensor, np.ndarray, float, int, np.number)
          ):
              if weights[0] is None:
                  res = elem
              else:
                  res = elem * weights[0]
              for it, weight in zip(items[1:], weights[1:]):
                  if type(it) != type(elem):
                      raise TypeError(
                          f"Expect type {type(elem)} but found {type(it)}. Can not be summed"
                      )
  
                  if weight is None:
                      res = res + it  # type: ignore
                  else:
                      res = res + it * weight  # type: ignore
              return cast(T, res)
  
          if isinstance(elem, Mapping):
              for item in items:
                  if not isinstance(item, Mapping):
                      raise TypeError(
                          f"Expect type {type(elem)} but found {type(item)}"
                      )
                  if set(item) != set(elem):
                      raise KeyError(
                          f"Expect keys {list(elem)} but found {list(item)}"
                      )
              return cast(
                  T,
                  {
                      key: weighted_sum(
                          cast(
                              List[dict],
                              [cast(Mapping, d)[key] for d in items],
                          ),
                          weights,
                      )
                      for key in elem
                  },
              )
          if isinstance(elem, Sequence):
              for item in items:
                  if not isinstance(item, Sequence):
                      raise TypeError(
                          f"Expect type {type(elem)} but found {type(item)}"
                      )
                  if len(item) != len(elem):
                      raise ValueError(
                          f"Expect length {len(item)} but found {len(elem)}"
                      )
              transposed = cast(Iterable[list], zip(*items))  # type: ignore
              return cast(
                  T,
                  [
                      weighted_sum(column, weights)
                      for column in transposed
                  ],
              )
      except (TypeError, ValueError, RuntimeError, KeyError):
          raise ValueError(
              "Error when summing items. Value format / shape does not match. See full traceback for details."
              + "".join(
                  [
                      f"\n  {idx}: {_summarize_elem_format(it)}"
                      for idx, it in enumerate(items)
                  ]
              )
          )
  
      # Dealing with all unexpected types.
      raise TypeError(unsupported_msg)
  
file_path: nni/nni/nas/oneshot/pytorch/supermodule/_expression_utils.py
imports: from __future__ import annotations
  import operator
  from typing import Any, TypeVar, List, cast, Mapping, Sequence, Optional, Iterable, overload
  import numpy
  import torch
  from nni.mutable import MutableExpression, Categorical
label_desc: Use image node_id 6 for calling a global function with example usage: weighted_sum(items, weights) and returns: cast, cast, cast