🕶️
VICEINTELPRO
GitHub: HorrorClause
  • In Tenebris Videmus
  • 🚩CTFs
    • 💾Hack the Box
      • 🏫Academy
        • Command Injection Assessment
        • XSS Assessment
        • Web Attacks Assessment
    • Try Hack Me
      • In Progress
  • 📖Documents
  • 👨‍🏫HOW-TOs
    • Obisidian How-To
    • Setup Mandiant FLARE VM
  • 📑Security Fundamentals
    • Security Controls
      • Physical Security
      • Endpoint Security
      • Email Security
      • Network Security
      • AAA Controls
    • Networking 101
      • OSI Model
      • Network Fundamentals
      • Network Devices
      • Network Tools
      • Protocols and Ports
    • 👨‍💼Management Principles
      • Risk
      • Policies and Procedures
      • Compliance and Frameworks
      • Change and Patch Management
  • 🛡️Security Concepts
    • ⚠️Risk Assessment Models
      • DREAD Risk Assessment Model
      • STRIDE Threat Model
      • Common Vulnerability Scoring System (CVSS)
    • Pentesting
      • Common Terms
      • AV Identification-Evasion
      • Introduction to Payloads
      • Automating Payloads & Delivery with Metasploit
      • Shells Jack Us In, Payloads Deliver Us Shells
      • Web Shells
      • Pentesting Overview
      • Penetration Testing Process
    • 🐛Vulnerability Assessment
      • Common Vulnerabilities and Exposures (CVE)
      • Common Vulnerability Scoring System (CVSS)
      • Assessment Standards
      • Vulnerability Assessment
      • Vulnerability Scanning
      • Reporting
      • 🎯Nessus
        • Getting Started with Nessus
        • Nessus Scan
        • Working with Nessus Scan Output
        • Advanced Settings
        • Scanning Issues
      • 🦴OpenVAS (Greenbone)
        • Getting Started with OpenVAS
        • OpenVAS
        • Exporting Results
    • Passwords
      • Password Managers
      • Password Policies
      • Password Security Fundamentals
    • Frameworks
    • GRC
    • Logon Types
    • What is Dev-Null ?
  • ⚔️Offensive Security
    • OSINT
      • OSINT - Websites
      • Google Dorks
    • 🔫Attacking Common Services
      • The Concept of Attacks
      • Interacting with Common Services
      • Finding Sensitive Information
      • Attacking DNS
      • Attacking Email Services
      • Attacking FTP
      • Attacking RDP
      • Attacking SMB
      • Attacking SQL Databases
      • Cheat Sheet - Attacking Common Services
      • Service Misconfigurations
    • 🔪Attacking Web Apps with Ffuf
      • Web Fuzzing
      • Directory Fuzzing
      • Page Fuzzing
      • Recursive Fuzzing
      • DNS Records
      • Sub-domain Fuzzing
      • Vhost Fuzzing
      • Filtering Results
      • Parameter Fuzzing - GET
      • Parameter Fuzzing - POST
      • Value Fuzzing
    • ☁️Cloud
      • AWS
        • AWS S3 Buckets
    • 💉Command Injection
      • Command Injection Cheat Sheet
      • Intro to Command Injections
      • Detection
      • Injecting Commands
      • Other Injection Operators
      • Identifying Filters
      • Bypassing Space Filters
      • Bypassing Other Blacklisted Characters
      • Bypassing Blacklisted Commands
      • Advanced Command Obfuscation
      • Evasion Tools
      • Command Injection Prevention
    • Containers
      • Docker
    • ❌Cross-Site Scripting (XSS)
      • Introduction to XSS
      • Stored XSS
      • Reflected XSS
      • DOM XSS
      • XSS Discovery
      • Defacing
      • Phishing
      • Session Hijacking
      • XSS Prevention
    • Directory Busting
      • DirB
      • DirBuster
      • Ffuf
      • Gobuster
    • 🅰️DNS
      • DNSRecon
      • Fierce
    • File Inclusion
      • Local File Inclusion Cheatsheet
      • Intro to File Inclusion
      • Local File Inclusion (LFI)
      • Basic Bypass
      • PHP Filters
      • PHP Wrappers
      • Remote File Inclusion (RFI)
      • LFI and File Uploads
      • Log Poisoning
      • Automated Scanning
      • File Inclusion Prevention
    • File Transfers
      • Transferring Files
      • File Transfer - Quick Commands
      • Living off the Land
      • Windows File Transfer Methods
      • Linux File Transfer Methods
      • Catching Files over HTTP(S)
      • Transferring Files with Code
      • Miscellaneous File Transfer Methods
      • Protected File Transfers
      • Mounting Encrypted VHD Drives
      • Mounting VHD in Kali
      • File Transfer Detection
    • File Upload Attacks
      • File Upload Cheatsheet
      • Absent Validation
      • Upload Exploitation
      • Client-Side Validation
      • Blacklist Filters
      • Whitelist Filters
      • Type Filters
      • Limited File Uploads
      • Other Upload Attacks
      • Preventing File Upload Vulnerabilities
    • 👣Footprinting
      • Linux Remote Management Protocols
      • Windows Remote Management Protocols
      • Enumeration
        • Enumeration Methodology
        • 🖥️Host Based
          • Quick Commands
          • DNS
          • FTP
          • IMAP-POP3
          • IPMI
          • MSSQL
          • MySQL
          • NFS
          • Oracle TNS
          • SMB
  • Powershell
    • Powershell CheatSheet
  • Python
    • Map
    • Anonymous Functions
    • Recursion
      • ZipMap
      • Nested Sum
      • Recursion on a Tree
      • Count Nested Levels
      • Longest Word
    • Function Transformations
      • More Transformations
      • Why Transform?
    • Closures
    • Currying
    • Decorators
    • Sum Types
    • Enums
    • Match
    • Regex
  • Kusto (KQL)
    • SQL and KQL Comparison
    • Using the Where and Sort Operators
    • KQL Queries
  • HTML
  • Insecure File Uploads
Powered by GitBook
On this page
  • Assignment
  • Example
  • Solution
  • How it Works
  1. Python
  2. Recursion

Count Nested Levels

In Doc2Doc, we might have documents nested inside other documents, forming a kind of tree.

Assignment

Complete the count_nested_levels function.

Example

In this dictionary, the document with id 3 is nested 2 levels deep. Document 2 is nested 1 level deep.

{
    1: {
        3: {}
    },
    2: {}
}

Solution

def count_nested_levels(nested_documents, target_document_id, level=1):
    for id in nested_documents:
        #Check if current ID Matches
        if id == target_document_id:
            return level

        # Check nested documents
        foundLevel = count_nested_levels(nested_documents[id],target_document_id,level +1)
        
        # If found in nested docs, return that level
        if foundLevel != -1:
            return foundLevel
    # If we dont find anything, return -1
    return -1
        

How it Works

1️⃣ Loop Through Each Document

for id in nested_documents:
  • Go through each document ID in the dictionary.

2️⃣ Check if the Current Document is the One We're Looking For

if id == target_document_id:
    return level
  • If the current document ID matches the target, return the current level (how deep it is).

3️⃣ Search Inside Nested Documents

foundLevel = count_nested_levels(nested_documents[id], target_document_id, level + 1)
  • If the document isn’t the target, check inside its nested documents (recursively).

  • Increase the level because we’re going deeper.

4️⃣ Return the Found Level (if Exists)

if foundLevel != -1:
    return foundLevel
  • If we found the target document inside a nested document, return its level.

5️⃣ If Not Found, Return -1

return -1
  • If the document doesn’t exist anywhere, return -1.

Example Breakdown

Document Structure:

{
    1: {  # Level 1
        3: {}  # Level 2
    },
    2: {}  # Level 1
}
  • Document 1 contains Document 3 (which is nested inside it).

  • Document 2 is not nested inside anything.

Find the Depth of Document 3

count_nested_levels(nested_documents, 3)

✅ Steps:

  1. Look at Document 1 (Not 3, so check inside it).

  2. Look at Document 3 (Found! ✅ Return level 2).

📌 Output: 2

Visual Representation of the Document Tree

Consider this nested dictionary:

{
    1: {      # Level 1
        3: {} # Level 2
    },
    2: {}     # Level 1
}

You can picture it as a tree:

           Root
          /    \
         1      2
         |
         3
  • Document 1 and Document 2 are at Level 1.

  • Document 3 is nested inside Document 1, so it’s at Level 2.


How count_nested_levels Finds the Level

Let’s walk through finding the level of Document 3:

  1. Start at the Root Level (Level 1):

    • The function is called with the whole dictionary and level=1.

    • It loops over the keys:

      • First Key: 1

        • Check: Is 1 the target?

          • No (target is 3).

        • Then, it makes a recursive call:

          count_nested_levels(nested_documents[1], target_document_id, level + 1)

          Here, nested_documents[1] is {3: {}} and level + 1 is 2.

  2. Recursive Call for Document 1’s Contents (Level 2):

    • Now the function is processing the dictionary {3: {}} at Level 2.

    • It loops over the keys:

      • Key: 3

        • Check: Is 3 the target?

          • Yes!

        • The function returns 2 because it found the target at Level 2.

  3. Return the Result:

    • The recursive call returns 2 to the original call.

    • Since the target was found, the original call then returns 2 as well.

Thus, Document 3 is 2 levels deep.


What if the Target is Not Found?

  • If neither the keys at the current level nor in any nested dictionaries match the target, the function returns -1.

  • This indicates that the target document doesn’t exist in the provided structure.

PreviousRecursion on a TreeNextLongest Word

Last updated 2 months ago