Number Present Problem in Python

In this class, we write a program for the number present problem in python.

For Complete YouTube Video: Click Here

Number Present Problem

All these examples will help the reader to improve coding skills.

To take the complete placement training, please check our placement training course.

The reader should have basic knowledge of python. Click here.

Q1) Given an array of integers. For each element, determine Whether the number occurs before in the sub-array. And it appears later in the sub-array.

Return an array of two binary integers as strings where each binary digit is one, If the element occurs in before or later sub arrays, or 0 if not present.

The index of each binary digit matches the index of the array element being tested. 

The first output string is related to lower indices. And the second to higher.

Let’s take an example for a better understanding.

Input: [1,2,3,2,1]

Solution:

Our first output is 00011, and our second is 11000.

Number Present Problem in Python
Example

From the above example, the first element is considered. then before sub-array is Null. and later sub-array is [2,3,2,1].

Output values are given in the first and second columns.

The first element in the array is 1. 

The left sub-array is null, so one not present in the left sub-array. Output is 0.

Right sub-array is [2,3,2,1], so 1 is present in right sub array. output is 1.

Check for all the elements.

Display left sub array results for all numbers in the array as a string with index positions matching the input element.

In the same way, display right sub array results for all elements as a string.

Logic

Logic is straightforward.

Use the slicing concept on the list.

For each element, slice the left part and right part.

Use in operator to check the element present in the sub-array or not.

If element present, take the output as 1. otherwise 0.

Please identify the logic for better practice. The program has given below.

Program

n = int(input("enter the n value"))
list1=[]
out1=[]
out2=[]
print("enter the elements")
for i in range(n):
    x=int(input())
    list1.append(x)
#logic
for i in range(n):
    leftpart=list1[0:i]
    rightpart=list1[i+1:n]
    if(list1[i] in leftpart):
        out1.append("1")
    else:
        out1.append("0")
    if list1[i] in rightpart:
        out2.append("1")
    else:
        out2.append("0")
sout1="".join(out1)
sout2="".join(out2)
print(sout1)
print(sout2)