Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
34 views

Perumon Python Training

Next

Uploaded by

itsnotme23.14
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
34 views

Perumon Python Training

Next

Uploaded by

itsnotme23.14
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 65

Python Basics

Topics to be covered.
● Variables
● Strings
● List
● Dictionary , Tuple, Set
● If , else , elif
● Logical operators
● Loops
● Functions
● Lambda , Map , Filter
● Coding questions
Variables
EXAMPLE : OUTPUT :

x = 2022 2022
y = "CEK" CEK
print(x)
print(y)
Strings
EXAMPLE : OUTPUT :

print("Hello") Hello
print('Hola') Hola
a = "Adios" Adios
print(a)
Important String functions

lower()
upper()
count(value, start, end)
index()
find(value, start, end)
replace(old , new, count)
swapcase()
List
EXAMPLE : OUTPUT :

thislist = ["Python", "Blockchain", "Flutter"] [ ‘Python’ , ‘Blockchain’ , ‘Flutter’ ]


print(thislist)
Important List functions

append()
extend()
count()
index()
sort()
sorted()
insert(index,element)
pop(position) [returns the popped element]
remove(value) [removes first occurrence of value]
Dictionary
EXAMPLE : OUTPUT :

a = { { 'type': 'College', 'name': 'CEC', 'loc: ‘Chengannur’}


"type" :"College",
"name" :"CEC", College
"loc":"Chengannur"
}
print(a)
print(a["type"])
Important Dictionary functions

get()
items()
keys()
values()
pop(key,default_value)
setdefault()
update()
Tuple
EXAMPLE : OUTPUT :

thistuple = ("Kiwi", "Apple",


"Orange", "Apple", "banana") ('Kiwi', 'Apple', 'Orange', 'Apple', 'banana')
print(thistuple)
Set
EXAMPLE : OUTPUT :

this_set = {1,2,33,”anwar”}
print(this_set) {1,2,33,”anwar”}
If , elif , else
EXAMPLE : OUTPUT :

a = 30
b = 30 a and b are equal
if b > a: 0
print("b is greater than a")
c = a + b
elif a == b:
print("a and b are equal")
c = a - b
else:
print("a is greater than b")
c = a * b
print(c)
a = 30
b = 30
x = 15
y = 25
if b > a:
c = a + b
if x < y: OUTPUT :
z = x * 3
else:
z = x-y
elif a == b:
c = a + b
if x > y:
z = x * 2
elif x == y:
z = y * 2
else:
z = x + y
else:
c = a * b
if x > y:
z = y * 5
else:
z = x * 10
print(c)
print(z)
Any student with a cgpa of 7 or higher is eligible for scholarships
based on few criterias. The criteria is based on extra_activities or
recommendation.

If a student has extra_activities and also have recommendation, they


are eligible for full scholarship. If only extra_activities but no
recommendation , they are eligible for partial scholarship. Students
who dont have extra_activities but have recommendation is eligible
for Partial scholarship. If student dont have extra_activities and dont
have recommendation, can have 10% scholarship.
If CGPA is less than 7, no scholarship
Logical Operators

and

or

not

Conditional operators

True False

/ // %
For loop
EXAMPLE : OUTPUT :

adj = ["white", "yellow", "red"]


vehicle = ["Car", "bike",
"auto"]

for x in adj:
for y in vehicle:
print(y,x)
While loop
EXAMPLE : OUTPUT :

i = 1
while i < 10:
print(i)
i = i - 1
Functions
EXAMPLE : OUTPUT :

def my_function(): Hello


print("Hello")

my_function()

def my_function(lname): Mr.Anwar


print("Mr." + lname)
Mr.Jishnu
my_function("Anwar") Mr.Asif
my_function("Jishnu")
my_function("Asif")
Lambda

EXAMPLE : OUTPUT :

def square(n): 4
return n ** 2
16

square = lambda n: n**2

square(2)
square(4)
Map
SYNTAX:
map(function, iterable)

EXAMPLE : OUTPUT :
def square(n):
return n ** 2 [1, 9, 25, 49, 81]
squares = map(square, range(1,
10, 2))
print(list(squares))

The map function takes in a function and an iterable(list, tuple, etc.) as an input; applies passed
function to each item of an iterable.

squares = list(map(lambda n: n ** 2, range(1, 10, 2)))


Filter
SYNTAX:

filter(function, iterable)

EXAMPLE : OUTPUT :

def find_odd(x): [1, 23, 89]


if x % 2 != 0:
return x
nums = [1, 34, 23, 56, 89, 44,
92]
odds = list(filter(find_odd,
nums))
print(odds)
Some important functions
len
sorted
max , min
String : lower,upper, strip, replace, split, join
Lists; append, extend, remove, count, clear ,list.index()
List comprehension
Questions
1) Write a python program to Calculate the area of a triangle using Heron's
formula ?
Write a function that takes a number as a parameter and return the
number of digits in it
Write a function that takes a number as a parameter and return the sum
of digits in it
Write a function that takes a number as a parameter and return the sum
of digits in it
Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.

You may assume that each input would have exactly one solution, and you may not use the same element twice.

You can return the answer in any order.

Example 1:

Input: nums = [2,7,11,15], target = 9


Output: [0,1]
Explanation: Because nums[0] + nums[1] == 9, we return [0, 1].

Example 2:

Input: nums = [3,2,4], target = 6


Output: [1,2]

Example 3:

Input: nums = [3,3], target = 6


Output: [0,1]
Consider the given input and output:

Input: Get 3 strings in 3 lines as input

Hello

Good

BeTtEr

Output:

● In the 1st string, replace the vowels with @


● In the 2nd string, replace the consonants with *
● In the third string, convert the lowercase letters to upper case.

H@ll@

*oo*

BETTER
For Example, consider the given series: 1, 2, 1, 3, 2, 5, 3, 7, 5, 11, 8, 13, 13, 17,

This series is a mixture of 2 series all the odd terms in this series form a Fibonacci series and all
the even terms are the prime numbers in ascending order. Now write a program to find the Nth
term in this series. TCS - 2018

Input: 6 Output: 5

Input : 11 Output: 8
Questions
2) Consider the following series: 1,1,2,3,4,9,8,27,16,81,32,243,64,729,128,2187…

This series is a mixture of 2 series – all the odd terms in this series form a
geometric series and all the even terms form yet another geometric series.

Write a program to find the Nth term in the series.


Questions
3) Consider the following series: 0,0,2,1,4,2,6,3,8,4,10,5,12,6,14,7,16,8

This series is a mixture of 2 series all the odd terms in this series form even
numbers in ascending order and every even term is derived from the previous term
using the formula (x/2).

Write a program to find the nth term in this series.


Alex works at a clothing store. There is a large pile of socks that must be
paired by size for sale. Given an array of integers representing the size of
each sock, determine how many pairs of socks with matching size there are?

For example: There are n=7 socks with size arr= [1,2,1,2,1,3,2]. There is one pair
of size 1 and one of size 2. There are three odd socks left, one of each size. The
number of pairs is 2.

Output:

Return the total no of matching pairs of socks that Allen can sell.

Sample Input: [ 10, 20, 20, 10, 10, 30, 50, 10, 20] Output: 3

Explanation: Alex can match 3 pairs of socks i.e 10-10, 10-10, 20-20. While the
left out socks are 50, 60, 20.
Questions
4) Write a python program, to check whether the given year is a leap year or not .(A
leap year is a calendar year containing one additional day (Feb 29th) added to keep
the calendar year synchronized with the astronomical year.)

1. If a year is evenly divisible by 4 means having no remainder then go to next step. If it is not divisible
by 4. It is not a leap year. For example: 1997 is not a leap year.
2. If a year is divisible by 4, but not by 100. For example: 2012, it is a leap year. If a year is divisible by
both 4 and 100, go to next step.
3. If a year is divisible by 100, but not by 400. For example: 1900, then it is not a leap year. If a year is
divisible by both, then it is a leap year. So 2000 is a leap year.
Questions
5) Write a python program, to find the HCF of the given 2 numbers
Questions
6) Write a python program to check whether a given number is a prime number or
not.
Questions
7) Write a python program to check whether the given number is Palindrome or not
?
Questions
8) Write a program to find whether the given number is an Armstrong number or not
.

(An Armstrong number of three digits is an integer such that the sum of the cubes
of its digits is equal to the number itself. For example, 371 is an Armstrong number

since 3**3 + 7**3 + 1**3 = 371.)


Questions
10) Write a python program to generate Fibonacci Series.
Questions
12) Write a python program to count number of digits in an integer?
Questions
Input a number n, find the sum of digits of n. also find the no. of digits of n. let that
be denoted as dig. If either the sum of digits of the number or the no. of digits of
the number is a prime number, then print the dig th prime number. Else print the
sum of the digits of the sum of the digits of n

n = 123 . Its sum of digit is 6.

No. of digits of n, dig is 3. 3 is a prime number. so we have to find 3rd prime


number. so the output will be 5

n = 1234 . Its sum of digit is 10.

No of digit of n , dig is 4. Neither 4 nor 4 is a prime. so we have to output the sum of


digits of sum of digits. that is 1
Questions
13) Write a python program to count number of occurrence of a character in a
string?
Questions
14) Write a python program to check if two strings are anagrams or not
You are playing a computer game in which you have 3 enemies who have their health level as a,b,c. To kill
the enemies you can point your laser gun at them and shoot which will reduce their health by 1 points.
Laser gun has an enhanced-shot which activates in every n-th shot, which reduces health level of all
enemies by 1 point.You cant target an enemy whose health level is 0.Also enhanced shot dont have any
impact on them as they are already dead.Your task is to complete the game by killing all enemies in your
enhanced shot. i.e. before firing the enhanced shot all enemies should be on health level 1 and when you
fire the enhanced shot health level of all enemies should become 0.

Given the value of n and a list health_levels with health levels of all enemies, find if you can complete the
game as desired and return True if yes or else False

Example 1
Input:

n= 7
health_levels = [3, 4 , 2]

Output:
True
The first line of the input is a number n. Print whether the number is secure or not secure.
Note: A number n is said to be secure if it can be written as the sum of two numbers a and b, and
a and b can be expressed as product of two prime numbers(but not the same number) eg:
INPUT : 41
OUTPUT : Secure
EXPLANATION: 41 can be expressed as sum of 6 and 35. Here 6 can be expressed as product of two
prime numbers 2 & 3. Also 35 can be expressed as product of the prime numbers 5 and 7. hence the
number 41 is Secure

INPUT : 19
OUTPUT : Not secure
EXPLANATION: 19 cannot be expressed as the sum of two numbers which can be expressed as product
of prime numbers. Even though 19 can be written as sum of 4 and 15 , here 4 can be written as the
product of 2 & 2 and 15 can written as the product of 3 & 5 . but the factors of 4 are 2 & 2. two factors
cannot be the same number, hence 19 is not secure

INPUT : 12
OUTPUT : Secure
EXPLANATION: 12 can be expressed as sum of 6 and 6. Here 6 can be expressed as product of two prime
numbers 2 & 3. Hence the number 12 is Secure
We are running a hotel business. Given the number of customers we have, the check-in days of the
customer and the checkout days of the customer, Print the highest number of customers we had in our
rooms in any of the day. Note that if a customer checks out on a day, then that day’s count should not
include that checked out customer. First line of input contains the number of customers. second line
contains the respective days in which the nth customers checks in. third line contains the day in which the
customers check out
Input: 3
1 2 3
3 4 5
Output: 2
Explanation: 1st customer checks in on the first day and checks out on the third day.2nd customer checks
in on 2nd day and checks out on 4th day. 3rd customer checks in on 3rd day and checks out on fifth day.
Since the most no. of customers we had in any day is 2, output is 2

Case 2:
Input : 6 1 2 3 3 6 7
3 4 5 6 7 8
Output 3
Question :

Given Two binary numbers ( in 0 and 1 ) in the form of string. Find out whether there is a
possibility whether these numbers can become equal by rearranging their respective Os
and 1s. (TCS NQT 2022)

For ex: 101 and 011 can be arranged within themselves to become either 101 or 011.
Example 1 :
3 -> length of input string
101 -> input string 1
011 -> input string 2
Output 1 : Yes

Example 2 :
5 -> length of input string
10100 -> input string 1
01111-> input string 2
Output 2 : No
Alice and friends are playing game kho kho. Alice is actually a mediator and rest of the friends are seated on N chairs
one each.
Alice starts by providing a paper with single digit number to the friend that is present on chair number 1.
Lets denote friends by F, where F will be of size N.
F[1] ..... F[N] represents friends seated respectively.
After receiving paper with a digit. F[1] will enact and try to tell F[2] without speaking.
Similarly F[2] will communicate to next person F[3].

This continues until the last person F[n] understands the digit.
Finally the last person will write the digit on separate page and give to alice.
Alice will compare both the digits . If digits are same then alice will give t shirt to each friend.
However if the digits do not match he will ask digits from each friend and give t shirt to that friend who understood the
correct digit.
Find how many friends did not get t shirt (TCS NQT 2022)
Example 1:
Input 1 : 3
Input 2 : [4,3,4]
Output: 0

Example 2 :
Input 1 : 5
Input 2 : [1,3,4,1,2]
Output : 3
Bob is going to bet today on horse riding . There are N horses listed in a sequence of 1 to N.
The probability of winning of each horse is different so the prices for making a bet on the horses are not the same .
There is no limit on the number of horses on which he can bet , but he thinks that if he bets on continuous
sequence of horses then he has better chance of win.
Bob will get K units of money if any horse on which he bets will win. But as the award is only k units so he wants to
put money less than K. Bob wants to bet as many horses as he can.

Please help Bob to find out the length of maximum continuous sequence of horses on which bob can place bet and
remember he will invest money less than K.
If there are more than 1 possible combinations, bob will bet randomly on any one of them. (TCS NQT 2022)

Example 1 :
Input :
10
100
30 40 50 20 20 10 90 10 10 10
Output : 3
Example 2 :
Input :
10
100
10 90 80 20 90 60 40 60 70 75
Output : 1
Jack and Jill are playing a string game . Jack has given Jill 2 strings A & B . Jill has to derive string C from A, by
deleting elements from string A, such that string C does not contain any elements of string B. Jill needs help to do
this task , she wants you to write a program . Given String A and B as input derive string C. (TCS NQT 2022)

Input:
Tiger
Ti

Output:
ger

Input:
processed
esd

Output:
proc
Raju has two numbers A and B. If sum of digits of A is greater than B, then he increments the value of A by 1. He
checks the condition again and also continue to increment the value of A by 1. Find the number of times Raju
increments the value of A so that the sum of digits of A is less than or equal to B (Infosys 2022)

Input:
599
16

Output:
1

Input:
111
3

Output:
0
First line of input is a binary string S. Second line of input is a number N. You are allowed to take any substring of
length N from the string S and convert 0’s of that substring to 1’s. Find the maximum length of substring with
complete 1’s after the conversion

Input:
11111
2
Output:
5

Input:
1010100010010001
5
Output:
7
Jack is a sports teacher at St Michael School. he make games not only to make the student fit but also smart. so he
line up all the N number of students in his class. At each position he has fixed a board with the integer number printed
on it. Each of the number are unique and are in exactly the range of N. let say there are 10 students then the board
will be printed with number from 1 to 10 in a random order given by the sequence A[ ].
As a rule all students wear a Jersey with number printed on it. so if there are N students, each will have unique jersey
number just like a football team. Now in the beginning all the student will stand in the increasing order of their jersey
number from left to right . The board number which is placed at their respective fixed location and cannot be
changed. we can consider the arrangement as below

Board ----> 2 3 1 5 4
Student's jersey ----> 1 2 3 4 5
Now the game begins. after every beat of the drum each student will have to move to the location where his board is
pointing to. So After first beat of the drum the alignment will be
Board ----> 2 3 1 5 4
Student's jersey ----> 3 1 2 5 4 and in the next drum ,
Board ----> 2 3 1 5 4
Student's jersey ---->2 3 1 4 5 and in the nex drum ,
Board ----> 2 3 1 5 4
Student's jersey ---->1 2 3 5 4

This keep going on and on, until all the students are back the way they were at the beginning.
So, After 6 beats of the drum all the students will be aligned the same way as before , SO the output is 6
Given a string S and a number N, print the given string in a special pattern in N
lines. the pattern is given below. (QBURST)
S - - - - - - > QBURSTISGOOD
N- - - - - - >3

Q x x x S x x x G x x x
x B x R x T x S x O x D
x x U x x x I x x x O x

Output is QSGBRTSODUIO

2nd Input & O/p

S - - - - - - - > ABCD
N- - - - - - - > 2

A x C x
x B x D

output is ACBD
Given a String S, construct a list which resembles the alphabets count in the string.
for example if the first element is 2 it means there is 2 ‘a’ in the string. if the second
element is 3, it means ‘b’ occurs 3 times in string. (QBURST 2022)

Input
S----> acddde
O/P - - - - > [1,0,1,3,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]

Input
S - - - - > adcdbd
O/P - - - - - -> [1,1,1,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
You are given a list of n-1 numbers. and these numbers
are in the range 1 to n.There are no duplicates in the
list.One of the integer is missing in the list. write an
efficient code to find the missing code (Nagarro &
Netflix)

Input
[1,7,3,4,6,2]
output
5
A thief trying to escape from a jail. He has to cross N walls each with varying heights (every height is greater than 0).
He climbs X feet every time. But, due to the slippery nature of those walls, every time he slips back by Y feet. Now the
task is to calculate the total number of jumps required to cross all walls and escape from the jail.
Examples :

Input : heights = [11, 11]


X = 10;
Y = 1;
Output : 4
He needs to make 2 jumps for first wall
and 2 jumps for second wall.

Input : heights = [11, 10, 10, 9]


X = 10;
Y = 1;
Output : 5
A left rotation operation on an array of size shifts each of the array's elements unit to

the left. Given an integer, , rotate the array that many steps left and return the

result.(QBurst, TCS, IBM)

Example

n=2

array = [1, 2 , 3, 4, 5 ]

after 2 rotations output should be:

[3, 4, 5, 1, 2]
Sherlock considers a string to be valid if all characters of the string appear the same

number of times. It is also valid if he can remove just 1 character at 1 index in the

string, and the remaining characters will occur the same number of times. Given a

string , determine if it is valid. If so, return YES, otherwise return NO.

Example

s = abc
This is a valid string because frequencies are {a:1,b:1,c:1}

s = abcc
This is a valid string because we can remove one c and have 1 of each character in the

remaining string.

s = abccc
This string is not valid as we can only remove 1 occurrence of c. That leaves character
frequencies of
{a:1,b:1,c:2}
Find the pyramid sum of the given list. A pyramid sum is calculated by repeated addition

of consecutive numbers until the list has one element.(UST 2023)

eg. Input:

[1, 2 ,3]

Output:

Explanation. list is reduced as [ 1+2 , 2+3 ]. = [3,5] which is reduced to [3+5]. So the

output is 8
Display the reverse of a number. if number = 400, display as 4. not 004
given a space seperated string. calculate score of the string. Score of the string is

determined as follows:

If the word is pallindrome and the world length is 4, then add 5 to the score. If the word is

pallindrome and the world length is 5, then add 10 to the score.

If the word is not pallindrome, then add 0 to the score. EG:

Input: “asdfg htth jklm rrtrr qwerty”

output: 15
Write a program to find the sum of the prime factors of a number, other than 1 and the
number itself.
eg:

input: 30
output: 10
The factors of 30 other than 1 & 30 are 2 ,3, 5, 6, 10, 15 out of which the prime numbers
are 2,3 and 5. hence sum is 10

Example 2:
input : 2
output: 0
there is no primefactors for 2 other than 1 & 2
Print the count of pallindromic substrings of a string. Note that single character substrings
are not eligible as Pallindromic substring.
Example 1:
a = “abba”
output: 2
Here the two pallindromic substrings are ‘bb’ and ‘abba’

Example 2:
a = “abcnkdkef”
output: 1
Pallindromic substring is ‘kdk’
Good luck!

You might also like