0% found this document useful (0 votes)
89 views21 pages

Python Coding Challenges

The document provides 10 programming problems involving tasks like reading lists from user input, finding maximum profit from price lists, using list comprehension to manipulate lists, incrementing numbers represented as arrays, and maximizing scores by selecting boxes from a list. Sample inputs and outputs are provided for each problem to illustrate the required tasks.

Uploaded by

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

Python Coding Challenges

The document provides 10 programming problems involving tasks like reading lists from user input, finding maximum profit from price lists, using list comprehension to manipulate lists, incrementing numbers represented as arrays, and maximizing scores by selecting boxes from a list. Sample inputs and outputs are provided for each problem to illustrate the required tasks.

Uploaded by

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

Program 1:

"""
Write a program to read n elements and display those items from a list that are
divisible by 5.

Input format:
----------------------------------------------
Read n value, followed by list elements

Output format:
------------------------------------------------
Print only elements that are divisible by 5

Sample Input:1
----------------------------------------------
5 #n value
10
12
13
15
30

Sample Output:1
----------------------------------------------
10 15 30
"""
num=[]
n=int(input())
for i in range(n):
x=int(input())
num.append(x)
for i in range(len(num)):
if num[i]%5==0:
print(num[i],end=' ')
case=1
input=5
10
20
30
40
50
output=10 20 30 40 50

case=2
input=2
1
20
output=20

case=3
input=1
100
output=100

case=4
input=3
1
2
60
output=60

___________________________________________________________________________________
_________________

Program 2:
"""
Ganesh's lucky number is 3.
He works as an accountant in a company.
He likes to know the third highest salary among all the employees.

You will be given an array of salaries salary[].


You need to help Ganesh to find the third highest salary (distinct).

NOTE: Salary is in lakhs per annum.

Input Format:
-------------
Line-1: N space separated integers

Output Format:
--------------
Print an integer, third highest salary.

Sample Input-1:
---------------
3 5 2 7 6

Sample Output-1:
----------------
5

Sample Input-2:
---------------
5 5 4 7 7

Sample Output-2:
----------------
4

"""
sal = list(map(int,input().split()))
us = []
for s in sal:
if s not in us:
us.append(s)

us.sort()
print(us[-3])

case=1
input=3 5 2 7 6
output=5

case=2
input=5 5 4 7 7 6
output=5
case=3
input=1 7 3 5 8 9
output=7
___________________________________________________________________________________
_______________

Program 3:
"""
Sachin wants to try his luck in diamonds business.
He decides to purchase and sell one diamond.

He is given the list of price of one diamond for N days by his friend.
Initially, it is assumed that he has no diamonds.

You need to help Sachin in making the maximum profit that is possible.
He can sell the diamond only after he purchases it.

Note: He is allowed to do only one complete transaction


(purchase one diamond and sell it).

Input Format:
-------------
N space separated integers, price of the diamond for N days.

Output Format:
--------------
Print an integer, maximum profit.

Sample Input-1:
---------------
7 1 5 3 6 4

Sample Output-1:
----------------
5

Explanation:
------------
Purchase on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5.

Sample Input-2:
---------------
7 6 5 4 2

Sample Output-2:
----------------
0

"""
prices = list(map(int,input().split()))
n=len(prices)
profit=0
for i in range(n-1):
for j in range(i+1,n):
diff = prices[j]-prices[i]
if( diff > profit):
profit=diff
print(profit)

case=1
input=7 1 5 3 6 4
output=5

case=2
input=7 6 5 4 2
output=0

case=3
input=6 3 4 6 9 8
output=6

case=4
input=7 2 5 1 0 2
output=3
_________________________________________________________________________________
Program 4:
"""
Write a python program using list comprehension
Note: Using the given list perform the given tasks
1. Create a new list: add 3 to given list elements if that element is even
2. construct a list from the squares of each element in the list,
if the square is greater than 50.
3. Create a new list: make all negative elements to positive elements

Test case 1:
Enter list elements: 5 3 7 -6 9 -4 11 2
New list after adding 3
[-3, -1, 5]
New list with squared elements
[81, 121]
New list with Positive elements
[6, 4]
"""
numList = list(map(int,input("Enter list elements: ").split()))
newList1 = [x+3 for x in numList if x%2==0]
newList2 = [x*x for x in numList if x*x>50]
newList3 = [abs(x) for x in numList if x<0]
print("New list after adding 3")
print(newList1)
print("New list with squared elements")
print(newList2)
print("New list with Positive elements")
print(newList3)
"""
Test cases:
case=1
input=5 3 7 -6 9 -4 11 2
output=Enter list elements:
New list after adding 3
[-3, -1, 5]
New list with squared elements
[81, 121]
New list with Positive elements
[6, 4]
"""
___________________________________________________________________________________
____

Program 5:
"""
Write a python program using list comprehension

1. Read a list from user


2. Make a new list with the words starts with a given character (user input)
3. Create a new list by removing all the duplicate words from the existing list

Test case 1:

Enter list elements :


kmit ngit jntu kmec cbit rvrj jntu ou ngit
Enter a character :k
List with given character
['kmit', 'kmec',]
List without duplicates
['kmit', 'ngit', 'jntu', 'kmec', 'cbit', 'rvrj', 'ou']
"""
words = input("Enter list elements :\n").split()
ch = input("Enter a character :")
clist = [word for word in words if word.startswith(ch)]
print("List with given character")
print(clist)

dlist = []
#s=
[dlist.append(word) for word in words if word not in dlist]
print("List without duplicates")
print(dlist)
#print(s)

"""
Test cases:
case=1
input=kmit ngit jntu kmec cbit rvrj jntu ou ngit
k
output=Enter list elements :
Enter a character :
List with given character
['kmit', 'kmec']
List without duplicates
['kmit', 'ngit', 'jntu', 'kmec', 'cbit', 'rvrj', 'ou']
"""

___________________________________________________________________________________
___________
Program 6:
"""
...
Mr Crazy Robert is given in integer array arr[], where arr[i] value is between
[0,9]
For example: if the arr[]=[1, 2, 3, 4], then the number can be formed is N=1234.
Now, increment the valuf of N by 1, and the resultant array is arr[]= [1, 2, 3, 5]

Your task is to help Mr Crazy Robert, to increment the number formed using arr[]
and print the resultant array.
Note: There should be no leading zeros in the number/array[]

Input Format:
-------------
N space separated integers, array[] the integers are in the range of [0,9].

Output Format:
--------------
Print the integer array, resultant array.

Sample Input-1:
---------------
1 2 3 4

Sample Output-1:
----------------
1 2 3 5

Sample Input-2:
---------------
1 2 9 9

Sample Output-2:
----------------
1 3 0 0

Sample Input-3:
---------------
9 9 9

Sample Output-3:
----------------
1 0 0 0
"""
arr = input().split()
num = int("".join(arr))
num = num+1
num = list(map(int,list(str(num))))
print(*num)

Test cases:
case=1
input=1 2 9 9
output=1 3 0 0

case=2
input=4 9 9
output=5 0 0

case=3
input=2 5 6 2
output=2 5 6 3

case=4
input=9 9
output=1 0 0

___________________________________________________________________________________
______________
Program 7:

"""
You are playing a game. There are N boxes placed in a row (0-indexed),
every box has some points. You need to play the game with the following rules:
- Initially your score is '0' points.
- Suppose the box has P points in it.
if p>0 you will gain P points, if p<0 you will loose P points.
- You are allowed to choose any number of consecutive boxes, atleast 1 box.

You are given the points in the N boxes as points[].


Your target is to maximize your score, and return the highest score possible.

Input Format:
-------------
Line-1: An integer N.
Line-2: N space separated integers, points[].

Output Format:
--------------
An integer, print the highest score.

Sample Input-1:
---------------
9
-3 1 -2 4 -2 2 3 -5 4

Sample Output-1:
----------------
7

Explanation:
------------
By selecting consecutive boxes are [4,-2,2,3] has the highest score is 7

Sample Input-2:
---------------
2
1 -2

Sample Output-2:
----------------
1

Explanation:
------------
By picking the box is [1] has the highest score is 7

"""
n = int(input())
points = list(map(int,input().split()))
max1=0
max2=0
for i in range(n):
max2 = max2+points[i]
if(max1<max2):
max1=max2
if max2<0:
max2=0
print(max1)

Test cases:
case=1
input=9
-3 1 -2 4 -2 2 3 -5 4
output=7

case=2
input=2
1 -2
output=1

case=3
input=8

-2 5 -6 3 -1 2 3 -1

output=7

___________________________________________________________________________________
___
Program 8:

"""
With a given integral number n, write a program to generate a dictionary that
contains (i, i*i) such that dictionary includes between 1 and n (both included).

Sample input & output:

Enter a number :7
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49}

"""
n = int(input("Enter a number :"))
d = dict()
for i in range(1,n+1):
d.update({i: i*i}) #or d[i]=i*i
print(d)

Test cases:
case=1
input=7
output=Enter a number :
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49}

case=2
input=3
output=Enter a number :

{1: 1, 2: 4, 3: 9}
______________________________________________________________
Program 9:
"""
Write a Python program to find if we can make first string
from second string by deleting some characters from
second string and rearranging remaining characters.

Test case 1:
Enter string 1: nikitha

Enter string 2: askdnikathih

Possible

Test case 2:
Enter string 1: himabindu

Enter string 2: asdghkimahiman

Not Possible

"""
def makeString(str1,str2):
s1=set(str1)
s2=set(str2)
for ch in s1:
if str2.count(ch)<str1.count(ch):
return False
return True

str1 = input("Enter string 1: ")


str2 = input("Enter string 2: ")
if (makeString(str1,str2)==True):
print("Possible")
else:
print("Not Possible")

Test cases:
case=1
input=nikitha
askdnikathih
output=
Enter string 1:

Enter string 2:

Possible

case=2
input=himabindu
asdghkimahiman
output=
Enter string 1:

Enter string 2:

Not Possible

case=3
input=nidhi
asdghkimahiman
output=
Enter string 1:

Enter string 2:

Possible

case=4
input=bandubindu
asbinduandu
output=
Enter string 1:

Enter string 2:

Not Possible
___________________________________________________

Program 10:

"""
Write a program to find total frequency of different webpages which are accessed
multiple number of times by different users.

Sample:
Input=
5 #Number of users visited webpages
Yahoo 2
Gmail 5
Javatpoint 4
Yahoo 4
Gmail 5

Output=
{'Yahoo': '6', 'Gmail': '10', 'Javatpoint': '4'}

"""
n = int(input())
pf = {}
for i in range(n):
k,v = input().split()
x = pf.get(k,0)
pf[k]=int(v)+x
print(pf)

Test cases:

case=1
input=5

Yahoo 2

Gmail 5

Javatpoint 4

Yahoo 4
Gmail 5

output={'Yahoo': '6', 'Gmail': '10', 'Javatpoint': '4'}

case=2
input=4
GFG 6
GoogleScholar 4
FaceBook 10
GFG 2
output=
{GFG=8, GoogleScholar=4, FaceBook=10}
___________________________________________________

Program 11:

"""
Write a python program to find all the duplicate words from given line of string

Sample I/O:

Enter a string:

it was the age of wisdom it was the age of foolishness


Duplicate words are:
it was the age of

"""
words = input("Enter a string:\n").split()
freqdict = dict()
for w in words:
freqdict[w]=words.count(w)

print("Duplicate words are:")


for w in freqdict:
if freqdict[w] > 1:
print(w,end=" ")

Test cases:
case=1
input=it was the age of wisdom it was the age of foolishness

output=
Enter a string:

Duplicate words are:


it was the age of

case=2
input=it was the best of times it was the worst of times

output=
Enter a string:
Duplicate words are:
it was the of times
___________________________________________________________________
Program 12:

"""
You are given a string S, consist of both lowercase and uppercase alphabets.

Your task is to find out the length of the longest word W with the
following properties:
- The word should be the longest.
- The word can be formed with letters of S, and you can shuffle the letters
as your need. You cannot use the letters more than their occurence count.
- The word should be equal to the reverse of it.

NOTE: Alphabets are case sensitive


"Aa" is not equal to "aA". The letters 'a' and 'A' are not same

Input Format:
-------------
A string S, consist of lower/uppercase letters

Output Format:
--------------
Print an integer, length of longest word W.

Sample Input-1:
---------------
pqrrrrss

Sample Output-1:
----------------
7

Explanation:
------------
One of the longest word can be formed is "srrqrrs", with length 7.

Sample Input-2:
---------------
AIbohPhObia

Sample Output-2:
----------------
5

Explanation:
------------
One of the longest word can be formed is "bhPhb", with length 5.

"""
s=input()
st=set(s)
freq = {}
for ch in st:
freq[ch]=s.count(ch)

c=0
oc=0
for ch in st:
if freq[ch]%2==0:
c=c+freq[ch]
else:
oc+=1
if freq[ch]>1 and freq[ch]%2==1:
c=c+freq[ch]-1
if oc>0:
c=c+1
print(c)

Test cases:
case=1
input=pqrrrrss
output=7

case=2
input=AIbohPhObia
output=5

case=3
input=chcaikvi
output=5

case=4
input=abcddcbadcbcbe
output=13
__________________________________________________________________________

Program 13:

A palindrome is a word whose order of letters remains the same whether it is read
from left to right or from right to left.
For example: 'laval', 'radar,' sos' ... are palindromes.
Write a program in Python that asks the user to enter a word and return it if it is
a palindrome or not?

code
----
n = input("Enter a string: ")
s2 = n [::-1]
if n == s2:
print(n, "is a palindrome")
else:
print(n, "is not a palindrome")

Test cases:
case=1
Enter a string: madam
madam is a palindrome

case=2
Enter a string: hello
hello is not a palindrome

case=3
Enter a string: welcome
welcome is not a palindrome

case=4
Enter a string: radar
radar is a palindrome
___________________________________________________________________________________
__________________________________________________
Program 14:

Given a string of odd length greater 7, return a string made of the middle three
chars of a given String.
Sample Input: GoodMorning
Sample Output: Mor

code
----
n = input()
a = len(n)
b = a // 2
c = b + 1
d = b - 1
s = n[d : c + 1]
if a > 7 and a % 2 != 0:
print(s)
else:
print("Invalid")

Test cases:
-----------
case=1
input=GoodMorning
output=Mor

case=2
input=world
output=Invalid

case=3
input=welcometokmit
output=met

case=4
input=welcomestudent
output=Invalid

case=5
input=welcome
output=Invalid
___________________________________________________________________________________
______________________________________
Program 15:

Write a program to print the following pattern for given n value


Sample input: 4
Sample output:
*
* *
* * *
* * * *

code
----
n = int(input())
s = "* "
for i in range(0, n + 1):
print(s*i)
___________________________________________________________________________________
______________________________________________
Program 16:

Write a program to print the following pattern for given n value


Sample input: 4
Sample output:
1
2 2
3 3 3
4 4 4 4

code
----
n = int(input())
for i in range(0, n + 1):
print((str(i)+" ")*i)

___________________________________________________________________________________
________________
Program 17
"""
You are given two codes C1 and C2, both are strings.
Your task is to check whether C2 lies in C1 or not.
If yes, return the first occurence index of C2 in C1.
Otherwise print -1.

NOTE:
Do not use predefined library methods..

Input Format:
-------------
Line-1: A string C1.
Line-2: A string C2.

Output Format:
--------------
An integer, print the index.

Sample Input-1:
---------------
goibibo
ib

Sample Output-1:
----------------
2

Sample Input-2:
---------------
goibibo
ibb

Sample Output-2:
----------------
-1

"""

c1=input()
c2=input()
if c2 in c1:
l1 = len(c1)
l2 = len(c2)
for i in range(l1):
if(c1[i:i+l2]==c2):
print(i)
break
else:
print(-1)

Test cases:
case=1
input=goibibo
ib
output=2

case=2
input=goibibo
ibb
output=-1

case=3
input=goibibo
bo
output=5

case=4
input=nikitha
itha
output=3

case=5
input=bindusri
sree
output=-1

case=6
input=nidhi
i
output=1
___________________________________________________________________________________
____________

Program 18:
"""
Bablu is playing a word puzzle game.
Initially, puzzle conatins a word S, you need to form another word 'T' using 'S'.
The game rules are as follows:
1. You can jumble the letters in the given word as your need.
2. You can add only one letter to the jumbled word at any position.

You are given two words, S and T.


Your task is to find and print the newly added character to S to form T.

Input Format:
-------------
Two space separated Strings S and T.

Output Format:
--------------
Print a character, added to S.

Sample Input-1:
---------------
ram marg

Sample Output-1:
----------------
g

Sample Input-2:
---------------
av ava

Sample Output-2:
----------------
a
"""
S,T=input().split()
for c in T:
if c not in S:
print(c)
break
if T.count(c)>S.count(c):
print(c)
break

Test cases:
case=1
input=ram marg
output=g

case=2
input=av ava
output=a

case=3
input=avatar avatara
output=a

case=4
input=ram mark
output=k
case=5
input=nikitha nikhitha
output=h
___________________________________________________________________________________
_____________________

Program 19:
"""
Ramesh and Suresh are best friends.
They decided to play a word game.

The game rules are as follows:


- The game board shows a word W consist of two characters only A and B.
- You are allowed to replace a pair of neighbour letters AA with BB in W.
- Finally, The one who failed to replace the letters will lose the game.

Your task is to find all the possible ways of W, after one valid replacement.
You have to perform the replacement of the pair from left to right in the word.
and print the result in the same order of replacement.

Input Format:
-------------
A string W, word.

Output Format:
--------------
Print the list of possible replacements of W.

Sample Input-1:
---------------
AAABAA

Sample Output-1:
----------------
[BBABAA, ABBBAA, AAABBB]

Sample Input-2:
---------------
AAAAA

Sample Output-2:
----------------
[BBAAA, ABBAA, AABBA, AAABB]

"""
w=input()
words=[]
l=len(w)
for i in range(l-1):
if w[i]==w[i+1] and w[i]=='A':
nw=w[0:i]+'BB'+w[i+2:l]
words.append(nw)

print(words)
Test cases:
case=1
input=AAABAA
output=
[BBABAA, ABBBAA, AAABBB]

case=2
input=AAAAA
output=
[BBAAA, ABBAA, AABBA, AAABB]

case=3
input=AAABAABBAAA
output=
[BBABAABBAAA, ABBBAABBAAA, AAABBBBBAAA, AAABAABBBBA, AAABAABBABB]

case=4
input=AAAABBBBAABAAA
output=
[BBAABBBBAABAAA, ABBABBBBAABAAA, AABBBBBBAABAAA, AAAABBBBBBBAAA, AAAABBBBAABBBA,
AAAABBBBAABABB]

___________________________________________________________________________________
___________________

Program 20:

"""
Bantu has an habit of writing the content vertically
For example:
Given line is "AMUL BABY"
He will wrtie it as
AB
MA
UB
LY

You will be given a list of words.


Your task is to print the words vertically like Bantu.

Return the words as a list of strings, complete with spaces when is necessary.
(Trailing spaces are not allowed).

Note:
Each word in the list, should be in single column.

Input Format:
-------------
A string S, contains space separated words.

Output Format:
--------------
Print the the words as a list of strings.
As shown below.

Sample Input-1:
---------------
HOW ARE YOU
Sample Output-1:
----------------
HAY,ORO,WEU,

Explanation:
------------
Each word is printed vertically.
"HAY"
"ORO"
"WEU"

Sample Input-2:
---------------
TO BE OR NOT TO BE

Sample Output-2:
----------------
TBONTB,OEROOE, T,

Explanation:
------------
Trailing spaces is not allowed.
"TBONTB"
"OEROOE"
" T"

Sample Input-3:
---------------
CONTEST IS COMING

Sample Output-3:
----------------
CIC,OSO,N M,T I,E N,S G,T,

"""
words = input().split()
r=0
c=len(words)
for word in words:
if len(word)>r:
r=len(word)
nwords = []

for i in range(r):
w=""
for j in range(c):
if i+1>len(words[j]):
w=w+" "
else:
w=w+words[j][i]
nwords.append(w)

for w in nwords:
print(w.rstrip(),end=",")

Test cases:
case=1
input=AMUL BABY
output=
AB,MA,UB,LY,

case=2
input=HOW ARE YOU
output=
HAY,ORO,WEU,

case=3
input=TO BE OR NOT TO BE
output=
TBONTB,OEROOE, T,

case=4
input=CONTEST IS COMING
output=
CIC,OSO,N M,T I,E N,S G,T,

You might also like