0% found this document useful (0 votes)
219 views12 pages

Codings 1

The document discusses several programming problems including finding the maximum signal in a binary string, rearranging an array to push empty elements to the end, capitalizing names, printing alphabet rangoli patterns, and finding the minimum merge operations needed to make an array a palindrome. It provides sample inputs, outputs, and code solutions for each problem in Python.

Uploaded by

Nagaraja Rao
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
219 views12 pages

Codings 1

The document discusses several programming problems including finding the maximum signal in a binary string, rearranging an array to push empty elements to the end, capitalizing names, printing alphabet rangoli patterns, and finding the minimum merge operations needed to make an array a palindrome. It provides sample inputs, outputs, and code solutions for each problem in Python.

Uploaded by

Nagaraja Rao
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 12

1. A digital machine generates binary data which consists of a string of 0s and 1s.

A maximum signal M,
in the data, consists of the maximum number of either 1s or 0s appearing consecutively in the data but M
can’t be at the beginning or end of the string. Design a way to find the length of the maximum signal.
Input
The first line of the input consists of an integer N, representing the length of the binary string. The second
line consists of a string of length N consisting of 0s and 1s only.
Output
Print an integer representing the length of the maximum signal.
Example
Example 1:
Input
6
101000
Output
1
Explanation
For 101000, M can be 0 at the second index or at the third index so in both cases max length = 1.
Example2:
Input
9
101111110
Output
6
Explanation
For 101111110, M = 111111 so maxlength = 6.

Code:
n=int(input())
no=input()
list1=list(no)
k=list1[0]
list1.pop(0)
count=1
for i in range(0,n):
if k==list1[i]:
list1.pop(i)
count+=1
else:
break
l=list1[n-count-1]
for i in range(n-count-1,-1,-1):
if l==list1[i]:
list1.pop(i)
else:
break

max1=0
store=0
m=list1[0]
for i in range(0,len(list1)):
if m==list1[i]:
max1+=1
else:
m=list1[i]
if max1>store:
store=max1
max1=1
if max1>store:
store=max1
print(store)

2. A chocolate factory is packing chocolates into the packets. The chocolate packets here represent an
array of N number of integer values. The task is to find the empty packets(0) of chocolate and push it to
the end of the conveyor belt(array).
Example 1 :
N=7 and arr = [4,5,0,1,0,5,0].
There are 3 empty packets in the given set. These 3 empty packets represented as O should be pushed
towards the end of the array
Input :
7 – Value of N
4
5
0
1
0
0
5 – Element of arr[O] to arr[N-1],While input each element is separated by newline
Output:
4515000
Example 2:
Input:
6 — Value of N.
[6,0,1,8,0,2] – Element of arr[0] to arr[N-1], While input each element is separated by newline
Output:
618200

Code:
n=int(input())
j=0
L=[0 for i in range(n)]
for i in range(n):
a=int(input())
if a!=0:
L[j]=a
j+=1
for i in L:
print(i,end=" ")

3. Joseph is learning digital logic subject which will be for his next semester. He usually tries to solve unit
assignment problems before the lecture. Today he got one tricky question. The problem statement is “A
positive integer has been given as an input. Convert decimal value to binary representation. Toggle all
bits of it after the most significant bit including the most significant bit. Print the positive integer value
after toggling all bits”.
Constrains-
1<=N<=100
Example 1:
Input :
10 -> Integer
Output :
5 -> result- Integer
Explanation:
Binary representation of 10 is 1010. After toggling the bits(1010), will get 0101 which represents “5”.
Hence output will print “5”.
Code:
import math
n=int(input())
k=(1<<int(math.log2(n))+1)-1
print(n^k)

4. You are asked to ensure that the first and last names of people begin with a capital letter in their
passports. For example, alison heck should be capitalized correctly as Alison Heck.
Given a full name, your task is to capitalize the name appropriately.
Input Format
A single line of input containing the full name, .
Constraints

 The string consists of alphanumeric characters and spaces.
Note: in a word only the first character is capitalized. Example 12abc when capitalized remains 12abc.
Output Format
Print the capitalized string, .
Sample Input
chris alan
Sample Output
Chris Alan

Code:
import string
a=input()
b=string.capwords(a)
print(b)

5. You are given an integer, . Your task is to print an alphabet rangoli of size . (Rangoli is a form of
Indian folk art based on creation of patterns.)
Different sizes of alphabet rangoli are shown below:
#size 3

----c----
--c-b-c--
c-b-a-b-c
--c-b-c--
----c----
#size 5

--------e--------
------e-d-e------
----e-d-c-d-e----
--e-d-c-b-c-d-e--
e-d-c-b-a-b-c-d-e
--e-d-c-b-c-d-e--
----e-d-c-d-e----
------e-d-e------
--------e--------
The center of the rangoli has the first alphabet letter a, and the boundary has the alphabet letter (in
alphabetical order).
Function Description
Complete the rangoli function in the editor below.
rangoli has the following parameters:
 int size: the size of the rangoli
Returns
 string: a single string made up of each of the lines of the rangoli separated by a newline character (\n)
Input Format
Only one line of input containing , the size of the rangoli.
Constraints
Sample Input
5
Sample Output
--------e--------
------e-d-e------
----e-d-c-d-e----
--e-d-c-b-c-d-e--
e-d-c-b-a-b-c-d-e
--e-d-c-b-c-d-e--
----e-d-c-d-e----
------e-d-e------
--------e--------

Code:
def print_rangoli(size):
import string
alpha = string.ascii_lowercase

L = []
for i in range(n):
s = "-".join(alpha[i:n])
L.append((s[::-1]+s[1:]).center(4*n-3, "-"))

print('\n'.join(L[:0:-1]+L))
if __name__ == '__main__':
n = int(input())
print_rangoli(n)

6. You are given a positive integer .


Your task is to print a palindromic triangle of size .
For example, a palindromic triangle of size is:
1
121
12321
1234321
123454321
You can't take more than two lines. The first line (a for-statement) is already written for you.
You have to complete the code using exactly one print statement.
Note:
Using anything related to strings will give a score of .
Using more than one for-statement will give a score of .
Input Format
A single line of input containing the integer .
Constraints

Output Format
Print the palindromic triangle of size as explained above.
Sample Input
5
Sample Output
1
121
12321
1234321
123454321

Code:
def solve(n):
for i in range(1,n+1):
print((((10**i) - 1)//9)**2)

n =int(input())
solve(n)

7. Given an array of positive integers. We need to make the given array a ‘Palindrome’. Only allowed
operation on array is merged. Merging two adjacent elements means replacing them with their sum. The
task is to find minimum number of merge operations required to make given array a ‘Palindrome’.

Example:
Input : arr[] = {15, 4, 15}
Output : 0
Array is already a palindrome. So we do not need any merge operation.

Input : arr[] = {1, 4, 5, 1}


Output : 1
We can make given array palindrome with minimum one merging (merging 4 and 5 to make 9)

Input : arr[] = {11, 14, 15, 99}


Output : 3
We need to merge all elements to make a palindrome.

Input Format
First line consists of number of array elements. Second line consists of elements separated by a space.

Output Format
Output displays the minimum number of merge operations.

Sample Input
5
12345

Sample Output
4

Code:

def findMinOps(arr,n):
ans=0
i,j=0,n-1
while i<=j:
if arr[i]==arr[j]:
i+=1
j-=1
elif arr[i]>arr[j]:
j-=1
arr[j]+=arr[j+1]
ans+=1
else:
i+=1
arr[i]+=arr[i-1]
ans+=1
return ans
n=int(input())
p=input()
print("\n")
arr=p.split()
print(str(findMinOps(arr,n)))
8. Given N candies and K people. In the first turn, the first person gets 1 candy, the second gets 2 candies,
and so on till K people. In the next turn, the first person gets K+1 candies, the second person gets k+2
candies and so on. If the number of candies is less than the required number of candies at every turn, then
the person receives the remaining number of candies.

Example
Input: N = 7, K = 4

Output: 1 2 3 1

Input Format
Single line input where N and K are separated by space

Output Format
Output displays the number of candies in a single line separated by space

Sample Input
10 3
Sample Output
523

Code:
import math as mt

# Function to find out the number of


# candies every person received
def candies(n, k):

# Count number of complete turns


count = 0

# Get the last term


ind = 1

# Stores the number of candies


arr = [0 for i in range(k)]

while n > 0:

# Last term of last and


# current series
f1 = (ind - 1) * k
f2 = ind * k

# Sum of current and last series


sum1 = (f1 * (f1 + 1)) // 2
sum2 = (f2 * (f2 + 1)) //2

# Sum of current series only


res = sum2 - sum1

# If sum of current is less than N


if (res <= n):
count += 1
n -= res
ind += 1
else: # Individually distribute
i=0

# First term
term = ((ind - 1) * k) + 1

# Distribute candies till there


while (n > 0):

# Candies available
if (term <= n):
arr[i] = term
i += 1
n -= term
term += 1
else:
arr[i] = n
i += 1
n=0

# Count the total candies


for i in range(k):
arr[i] += ((count * (i + 1)) +
(k * (count * (count - 1)) // 2))

# Print the total candies


for i in range(k):
print(arr[i], end = " ")

# Driver Code
n,k=input().split()
n=int(n)
k=int(k)
candies(n, k)

9. Given a string and a positive integer d. Some characters may be repeated in the given string. Rearrange
characters of the given string such that the same characters become d distance away from each other.
Note that there can be many possible rearrangements, the output should be one of the possible
rearrangements.
Input Format
Single line input which has the string and integer d

Output Format
Output displays the rearranged string

Sample Input
aaabbbccc 3

Sample Output
abcabcabc

Code:
MAX = 256
class charFreq(object):
def __init__(self, c, f):
self.c = c
self.f = f
def swap(x, y):
return y, x
def toList(string):
t = []
for x in string:
t.append(x)
return t
def toString(l):
return ''.join(l)
def maxHeapify(freq, i, heap_size):
l = i*2 + 1
r = i*2 + 2
largest = i
if l < heap_size and freq[l].f > freq[i].f:
largest = l
if r < heap_size and freq[r].f > freq[largest].f:
largest = r
if largest != i:
freq[i], freq[largest] = swap(freq[i], freq[largest])
maxHeapify(freq, largest, heap_size)
def buildHeap(freq, n):
i = (n - 1)//2
while i >= 0:
maxHeapify(freq, i, n)
i -= 1
def extractMax(freq, heap_size):
root = freq[0]
if heap_size > 1:
freq[0] = freq[heap_size-1]
maxHeapify(freq, 0, heap_size-1)
return root
def rearrange(string, d):
n = len(string)
freq = []
for x in range(MAX):
freq.append(charFreq(0, 0))
m=0
for i in range(n):
x = ord(string[i])
if freq[x].c == 0:
freq[x].c = chr(x)
m += 1
freq[x].f += 1
string[i] = '\0'
buildHeap(freq, MAX)
for i in range(m):
x = extractMax(freq, MAX-i)
p=i
while string[p] != '\0':
p += 1
for k in range(x.f):
if p + d*k >= n:
print ("Cannot be rearranged")
return
string[p + d*k] = x.c
return toString(string)
string,p=input().split()
n=int(p)
print (rearrange(toList(string), n))

10. Given two array A1[] and A2[], sort A1 in such a way that the relative order among the elements will
be same as those in A2. For the elements not present in A2. Append them at last in sorted order. It is also
given that the number of elements in A2[] is smaller than or equal to a number of elements in A1[] and
A2[] has all distinct elements.

Input Format
The first line of the test case is M and N. M is the number of elements in A1 and N is the number of
elements in A2 ,followed by the array elements.

Output Format
Print the sorted array according to the order defined by another array.
Note : There is a space at the end of the output.

Constraints
Integers only.
Sample Input
11 4 2 1 2 5 7 1 9 3 6 8 8 2 1 8 3

Sample Output
22118835679

Code:
a=list(map(int,input().split()))
m=a[0]
n=a[1]
b=a[2:m+2].copy()
d=a[m+2:]
list_out=[]
list_not=[]
for i in d:
for j in b:
if(i==j):
list_out+=[j]
list_not=[]
for k in b:
if k in list_out:
pass
else:
list_not+=[k]
main_list=list_out+sorted(list_not)
string_out=""
for l in main_list:
string_out+=str(l)+" "
print(string_out[:-1])

You might also like