(defun calculate-level-sums (lst)
  (prepare-result (calculate-level-sums-helper lst 1 '())))

(defun calculate-level-sums-helper (lst level acc)
  (cond
    ((null lst) acc)
    (t (let ((head (car lst))
             (tail (cdr lst)))
         (multiple-value-bind (new-acc remaining-tail)
           (process-item head level acc)
           (calculate-level-sums-helper tail level new-acc))))))

(defun process-item (item level acc)
  (cond
    ((numberp item)
     (values (update-level-sum acc level item) nil))
    ((listp item)
     (values (calculate-level-sums-helper item (1+ level) acc) nil))
    (t (values acc nil))))

(defun update-level-sum (acc level value)
  (let ((existing (assoc level acc)))
    (if existing
        (let ((new-acc (remove existing acc :test #'equal)))
          (cons (list level (+ value (cadr existing))) new-acc))
        (cons (list level value) acc))))

(defun prepare-result (acc)
  (if (assoc 1 acc)
      (sort acc #'< :key #'car)
      (sort (cons '(1 0) acc) #'< :key #'car)))
;; Тесты
(format t "~a~%" (calculate-level-sums '(a (b (4 (2 e (3) k 15) e 5) 7)))) ; ((1 0) (2 7) (3 9) (4 17) (5 3))
(format t "~a~%" (calculate-level-sums '(a b c))) ; ((1 0))
(format t "~a~%" (calculate-level-sums '(1 (2 (3))))) ; ((1 1) (2 2) (3 3))
(format t "~a~%" (calculate-level-sums'(1 (2 3 (4 (5 6)))))) ; ((1 1) (2 5) (3 4) (4 11))
