What is the best way to arrange items in an array based on their hierarchy?

Consider the following array as an example:

[1,2,2,3,4,1,2,3,4,1,1]

In this array, each element's value represents its level.

Now, I am looking to transform this array into the following structure:

[
  1: [2, 2: [3: [4]]],
  1: [2: [3: [4]]],
  1,
  1
]

Although the elements are represented as numbers, consider them as objects with properties that can hold arrays of their respective class.

Answer №1

This particular iteration assigns the positive whole number to indicate the exact depth of nesting:

def generate_tree(x, index=0, depth=1):
   level = x[index]
   if depth < level:
       index, deeper = generate_tree(x, index, depth + 1)
       return index, [deeper]
   so_far = [level]
   index += 1
   while index < len(x):
       #print(level, so_far, x[index:])
       this = x[index]
       if this == level:
           so_far.append(this)
       elif this > level:
           index, deeper = generate_tree(x, index, depth + 1)
           so_far.append(deeper)
       elif this < level:
           index -=1
           break
       index += 1
   return index, so_far

from pprint import pprint

lst = [1,2,3,4,5, 1,5, 1,2,2,3,4,1,2,3,4,1,1]
_, result = generate_tree(lst)

pprint(result, width=10)

Result

[1,
 [2,
  [3,
   [4,
    [5]]]],
 1,
 [[[[5]]]],
 1,
 [2,
  2,
  [3,
   [4]]],
 1,
 [2,
  [3,
   [4]]],
 1,
 1]

Observe how the sudden shift from 1,5, places the 5 at the same nesting level as the gradual progression of 1,2,3,4,5.

Answer №2

def tree_traversal(input_list, start_idx=0):
    current_level = input_list[start_idx]
    nodes_so_far = [current_level]
    start_idx += 1
    while start_idx < len(input_list):
        next_node = input_list[start_idx]
        if next_node == current_level:
            nodes_so_far.append(next_node)
        elif next_node > current_level:
            start_idx, deeper_nodes = tree_traversal(input_list, start_idx)
            nodes_so_far.append(deeper_nodes)
        elif next_node < current_level:
            start_idx -= 1
            break
        start_idx += 1
    return start_idx, nodes_so_far

from pprint import pprint

input_lst = [1,2,2,3,4,1,2,3,4,1,1]
_, output_answer = tree_traversal(input_lst)
assert output_answer == [1, [2, 2, [3, [4]]], 1, [2, [3, [4]]], 1, 1]

pprint(output_answer, width=10)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Error: TypeError encountered during UI Runtime JSON conversion of Circular Data Structure

I'm facing an issue while attempting to parse and stringify certain JSON data. The error occurs on this specific line of code: this.copyOfColumns = JSON.parse(JSON.stringify(Object.assign([], this.columns))); Below is the complete @Input (using Ang ...

Utilizing Props in TypeScript with React Styled Components

I created this styled component using TypeScript following the guidelines in their documentation import matrix from '../img/matrix.jpg'; const Style = styled.div` .fixed { background-image: url(${props => props.image ? pr ...

When working in VScode, there may be difficulty in locating project-specific imports for `tsx` files. However, the TypeScript compiler is able to locate

When converting a jsx component to tsx, my VScode editor highlights project-specific imports as errors. The following code is from components\molecules\WizardSteps.jsx JSX https://i.stack.imgur.com/tKZ35.png TSX The following code is from comp ...

Obtain redirected JSON data locally using Angular 5

Currently, I am working on retrieving JSON data which will be sent to my localhost through a POST method. The SpringBoot API controller will validate the JSON content before forwarding it to my localhost. My task is to intercept this JSON data when it is t ...

Tips for decoding the excel PRODUCT function

Seeking help to convert the =(1-PRODUCT(K5:K14)) Excel formula into JavaScript code. I attempted to write the code based on my own understanding, but the result is not what I expected. exp_PRODUCT= [ 0.993758608, 0.993847362, 0.993934866, 0.99402 ...

Starting a fresh Angular project yields a series of NPM warnings, notably one that mentions skipping an optional dependency with the message: "npm

Upon creating a new Angular project, I encounter warning messages from NPM: npm WARN optional SKIPPING OPTIONAL DEPENDENCY: <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="68e01b0d1e0d061c7518d7">[email protecte ...

Deriving the type of a generic parameter from another generic parameter in TypeScript

Apologies for the less-than-descriptive title of this question, but sometimes it's easier to demonstrate with code rather than words. Here's a snippet that's causing issues, and I'm wondering why it's not behaving as expected: int ...

Total the values of several items within the array

Here is the data I currently have: const arrayA = [{name:'a', amount: 10, serviceId: '23a', test:'SUCCESS'}, {name:'a', amount: 9, test:'FAIL'}, {name:'b', amount: ...

While attempting to send a GET Request in Angular, access to XMLHttpRequest has been denied due to CORS policy restrictions

I am attempting to establish a GET method for my PHP API. Here is the code snippet I am using: export class PerfilComponent { perfil: any; constructor(private http: HttpClient) { } ngOnInit() { const token:string | null = localStorage.getItem(&ap ...

How to Invoke a TypeScript Function in Angular 2 Using jQuery

Using the Bootstrap-select dropdown in Angular 2 forms with jQuery, I am attempting to call a Typescript method called onDropDownChangeChange on the onchange event. However, it seems to not be functioning as expected. import { Component, OnInit, ViewChi ...

Learn how to generate specific error messages based on the field that caused the failure of the @Column({ unique: true }) Decorator. Error code 23505

Hey there! I'm currently facing an issue while trying to handle Sign Up exceptions in my code. I want to inform the user if their username OR email is already in use. Although using the decorator @Column({ unique: true}) allows me to catch error 23505 ...

Potential 'undefined' object detected in Vuex mutation using TypeScript

Currently, I am diving into learning Vue.js alongside Vuex and TypeScript. While working on my application, I encountered an error stating "Object is possibly 'undefined'" within the Vuex Store. The error specifically arises in the "newCard" mut ...

Instructions for incorporating a TypeScript type into a Prisma model

I am trying to incorporate a Type Board into one of my Prisma models. However, I am encountering an error stating that "Type 'Board' is neither a built-in type, nor refers to another model, custom type, or enum." Can someone provide guidance on h ...

Is there a missing .fillGeometry in the Figma plugin VectorNode?

The documentation for VectorNode mentions a property called fillGeometry. Contrary to this, TypeScript indicates that "property 'fillGeometry' does not exist on type 'VectorNode'". https://i.sstatic.net/ICfdw.png I seem to be missing ...

When using Angular version 13 alongside rxjs 7.4 and TypeScript 4+, an issue arises with the error message: "Declaration file for module 'rxjs' not found"

Currently embarking on a new Angular app using V13 and rxjs7.4, I encountered the error shown above when trying to import: import { BehaviorSubject } from 'rxjs'; Initially, I attempted to address this by creating a typings.d.ts declaration as s ...

Why does TypeScript require a generic type parameter when arguments have already been provided?

When I attempted to use the argument p to infer type P, TypeScript still prompted me to provide type P. Why is that? const numberStringConverter = <T extends string | number,P extends {x: any}>(p: P): T => { if(typeof p.x === 'string') ...

Angular 12: TypeScript Issue TS2339 - Unable to Locate Property on Type

Whenever I use the code below, I encounter error TS2339: Property 'timestamp' does not exist on type 'LogRepair[]' In the component's HTML file, I am attempting to loop through an array of properties defined in the LogRepair typ ...

Angular6: Parent component fails to pass data to child component

My goal is to implement a loading message that displays when the page is loaded. I have created a loader component as a child component, and I am passing a value from the parent. However, for unknown reasons, the loader is not being displayed. I have atte ...

Error encountered in Jest when trying to use next/font/local: TypeError - (0, _local.default) is not a function

Currently, I am in the process of developing a UI library utilizing MUI, React, and TypeScript within Nx as the build system. To ensure smooth functionality, Jest is being used for testing purposes. However, I recently encountered an issue while attempting ...