Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Python Program To Check If A Singly Linked List Is Palindrome
Next article icon

Python Program to find all Palindromic Bitlists in length

Last Updated : 05 Sep, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

In this article, we will learn to generate all Palindromic Bitlists of a given length using Backtracking in Python. Backtracking can be defined as a general algorithmic technique that considers searching every possible combination in order to solve a computational problem. Whereas, Bitlists are lists of bits(0 and 1). A bit list that is a palindrome is called Palindromic Bitlists. To generate all Palindromic Bitlists of length N, the best way is to generate all possible bit lists of length N/2 and then form palindromic Bitlist using this list of length N/2. Here we will discuss 2 cases:

Case 1: When the length of the list is odd

Let's consider the value of N = 3. So, N/2 = 1 (floor value).

All possible bit lists of length 1 are [0], [1]. In this case, we can not do exact same thing which we have done for the even length case because doing that thing will give a bit list of length 2 and not 3. Here we will add [0] or [1] in mid of bit list. Consider [0], its reverse will be [0]. To generate bit lists we have to combine 3 lists that are generated bit lists of length 1, [0], Or [1], the reverse of the generated list. Here every bit list will produce 2-bit lists. For [0] there will be [0] + [0] +[0] and [0] + [1] +[0].

Example: The value of N is 5

Python
# list to store all the possible solutions fianl_ans = []  # this function generates all possible bitlists  # of length N//2 and then saves the final answer  # in the list   def generate_palindromic(n, is_even, lst=[]):     # n==0 is the base condition and after      # reaching here we don't go forward     if n == 0:         if is_even:             # even case             # final_ans = generated list + reverse              # of generated list             fianl_ans.append((lst + lst                               [-1::-1]))         else:             # odd case             # final_ans_1 = generated list +              # [0] + reverse of generated list             fianl_ans.append(lst + [0] +                               lst[-1::-1])             # final_ans_1 = generated list              # + [1] + reverse of generated list             fianl_ans.append(lst + [1] +                               lst[-1::-1])         return     # store 0 in the list to provide the value of      # this step to the next step     lst.append(0)     # call recursive function and decrease      # the value of n by 1     generate_palindromic(n-1, is_even, lst)     # remove 0 from the list (Backtrack)     lst.pop()     # store 1 in the list to provide the value      # of this step to the next step     lst.append(1)     # call recursive function and decrease      # the value of n by 1     generate_palindromic(n-1, is_even, lst)     # remove 1 from the list (Backtrack)     lst.pop()   def check(n):     if n % 2 == 0:         # if n is even then pass 1 to the          # recursive function         generate_palindromic(n/2, 1)     else:         # if n is odd then pass 0 to the          # recursive function         generate_palindromic(n//2, 0)   if __name__ == "__main__":     # calling function to generate all      # bitlists of length 5     check(5)     # printing final answers     for i in fianl_ans:         print(i) 

Output:

Use Backtracking to find all Palindromic Bitlists of a given length in Python
 

Case 2: When the length of the list is even

Let's consider the value of N = 4. So, N/2 = 2.

All possible bit lists of length 2 are [0,0], [0,1], [1,0], [1,1]. Consider [0,1], its reverse will be [1,0]. Combining both of them we will get [0,1,1,0] which is a Palindromic bit list of length 4. In this way, we can generate all Palindromic Bitlists of length N where N is even.

Example: The value of N is 4

Python
# list to store all the possible solutions fianl_ans = []  # this function generates all possible bitlists  # of length N//2 and then saves the final answer in the list   def generate_palindromic(n, is_even, lst=[]):     # n==0 is the base condition and after      # reaching here we don't go forward     if n == 0:         if is_even:             # even case             # final_ans = generated list + reverse              # of generated list             fianl_ans.append((lst +                                lst[-1::-1]))         else:             # odd case             # final_ans_1 = generated list +              # [0] + reverse of generated list             fianl_ans.append(lst + [0] +                               lst[-1::-1])             # final_ans_1 = generated list +               # [1] + reverse of generated list             fianl_ans.append(lst + [1] +                               lst[-1::-1])         return     # store 0 in the list to provide the value of      # this step to the next step     lst.append(0)     # call recursive function and decrease the      # value of n by 1     generate_palindromic(n-1, is_even, lst)     # remove 0 from the list (Backtrack)     lst.pop()     # store 1 in the list to provide the      # value of this step to the next step     lst.append(1)     # call recursive function and decrease      # the value of n by 1     generate_palindromic(n-1, is_even, lst)     # remove 1 from the list (Backtrack)     lst.pop()   def check(n):     if n % 2 == 0:         # if n is even then pass 1 to          # the recursive function         generate_palindromic(n/2, 1)     else:         # if n is odd then pass 0 to          # the recursive function         generate_palindromic(n//2, 0)   if __name__ == "__main__":     # calling function to generate all      # bitlists of length 5     check(4)     # printing final answers     for i in fianl_ans:         print(i) 

Output:

Use Backtracking to find all Palindromic Bitlists of a given length in Python
 

The time complexity of both Case 1 and Case 2 of the Python program to find all Palindromic Bitlists of a given length using backtracking is O(2^(N/2)), where N is the length of the bitlist.The space complexity of both Case 1 and Case 2 algorithms is O(2^(N/2)), where N is the length of the palindromic bitlist.

This is because the algorithms generate all possible palindromic bitlists of length N, which is equal to generating all possible bitlists of length N/2 and then combining them in a palindromic manner. Therefore, the space required to store all possible bitlists of length N/2 is O(2^(N/2)), which is the maximum space required by both the algorithms.

In both cases, the bitlists are generated recursively and stored in a list, which is then appended to the final_ans list. The maximum size of this list would be O(2^(N/2)), as there are 2^(N/2) possible bitlists of length N/2. Hence, the space complexity of both algorithms is O(2^(N/2)).


Next Article
Python Program To Check If A Singly Linked List Is Palindrome
author
06akshay2002
Improve
Article Tags :
  • Technical Scripter
  • Python
  • Python Programs
  • Technical Scripter 2022
Practice Tags :
  • python

Similar Reads

  • Python Program to Remove Palindromic Elements from a List
    Given a list, the task here is to write Python programs that can remove all the elements which have palindromic equivalent element present in the list. Examples: Input : test_list = [54, 67, 12, 45, 98, 76, 9] Output : [12, 98] Explanation : 67 has 76 as palindromic element, both are omitted. Input
    2 min read
  • Python Program To Check If A Singly Linked List Is Palindrome
    Given a singly linked list of characters, write a function that returns true if the given list is a palindrome, else false. Recommended: Please solve it on "PRACTICE" first, before moving on to the solution. METHOD 1 (Use a Stack): A simple solution is to use a stack of list nodes. This mainly invol
    6 min read
  • Python program to check if number is palindrome (one-liner)
    In this article, we are given a number and we have to check whether the number is palindrome or not in one-liner code. The output will be True if it's a Palindrome number otherwise it would be False. Let's discuss how to find whether a number is palindrome or not in this article. Input1: test_number
    3 min read
  • Python Program to Check if a String is Palindrome or Not
    The task of checking if a string is a palindrome in Python involves determining whether a string reads the same forward as it does backward. For example, the string "madam" is a palindrome because it is identical when reversed, whereas "hello" is not. Using two pointer techniqueThis approach involve
    3 min read
  • Python Program For Checking Linked List With A Loop Is Palindrome Or Not
    Given a linked list with a loop, the task is to find whether it is palindrome or not. You are not allowed to remove the loop. Examples: Input: 1 -> 2 -> 3 -> 2 /| |/ ------- 1 Output: Palindrome Linked list is 1 2 3 2 1 which is a palindrome. Input: 1 -> 2 -> 3 -> 4 /| |/ ------- 1
    4 min read
  • Python Program To Find Minimum Insertions To Form A Palindrome | DP-28
    Given string str, the task is to find the minimum number of characters to be inserted to convert it to a palindrome. Before we go further, let us understand with a few examples: ab: Number of insertions required is 1 i.e. babaa: Number of insertions required is 0 i.e. aaabcd: Number of insertions re
    9 min read
  • Python Program To Check If A Linked List Of Strings Forms A Palindrome
    Given a linked list handling string data, check to see whether data is palindrome or not? Examples: Input: a -> bc -> d -> dcb -> a -> NULL Output: True String "abcddcba" is palindrome. Input: a -> bc -> d -> ba -> NULL Output: False String "abcdba" is not palindrome. Reco
    2 min read
  • Python program to check if given string is vowel Palindrome
    Given a string (may contain both vowel and consonant letters), remove all consonants, then check if the resulting string is palindrome or not. Examples: Input : abcuhuvmnba Output : YES Explanation : The consonants in the string "abcuhuvmnba" are removed. Now the string becomes "auua". Input : xayzu
    5 min read
  • Test if List is Palindrome - Python
    We are given a list we need to find that given list is a palindrome. For example a = [1, 2, 3, 2, 1] we need to check whether it is a palindrome or not so that the output should be 'True'. Using SlicingWe can check if a list is a palindrome by comparing it with its reverse using slicing ([::-1]). If
    2 min read
  • Python program to sort Palindrome Words in a Sentence
    Given a string S representing a sentence, the task is to reorder all the palindromic words present in the sentence in sorted order. Examples: Input: S = "Please refer to the madam to know the level"Output: Please level to the madam to know the referExplanation: Here "refer", "madam", "level" are the
    5 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences