Mstering Python Cocept and Coding
Mstering Python Cocept and Coding
Mstering Python Cocept and Coding
import m
def monkey_function(self):
print "monkey_function()"
m.GeeksClass.function = monkey_function
obj = m.GeeksClass()
obj.function()
46. What is __init__() in Python?
Equivalent to constructors in OOP terminology, __init__ is a reserved method in Python
classes. The __init__ method is called automatically whenever a new object is initiated.
This method allocates memory to the new object as soon as it is created. This method can
also be used to initialize variables.
47. Write a code to display the current time?
import time
currenttime= time.localtime(time.time())
print (“Current time is”, currenttime)
48. What are Access Specifiers in Python?
Python uses the ‘_’ symbol to determine the access control for a specific data member or a
member function of a class. A Class in Python has three types of Python access modifiers:
• Public Access Modifier: The members of a class that are declared public are easily
accessible from any part of the program. All data members and member functions
of a class are public by default.
• Protected Access Modifier: The members of a class that are declared protected are
only accessible to a class derived from it. All data members of a class are declared
protected by adding a single underscore ‘_’ symbol before the data members of
that class.
• Private Access Modifier: The members of a class that are declared private are
accessible within the class only, the private access modifier is the most secure
access modifier. Data members of a class are declared private by adding a double
underscore ‘__’ symbol before the data member of that class.
49. What are unit tests in Python?
Unit Testing is the first level of software testing where the smallest testable parts of the
software are tested. This is used to validate that each unit of the software performs as
designed. The unit test framework is Python’s xUnit style framework. The White Box
Testing method is used for Unit testing.
50. Python Global Interpreter Lock (GIL)?
Python Global Interpreter Lock (GIL) is a type of process lock that is used by Python
whenever it deals with processes. Generally, Python only uses only one thread to execute
the set of written statements. The performance of the single-threaded process and the
multi-threaded process will be the same in Python and this is because of GIL in Python.
We can not achieve multithreading in Python because we have a global interpreter lock
that restricts the threads and works as a single thread.
51. What are Function Annotations in Python?
Function Annotation is a feature that allows you to add metadata to function parameters
and return values. This way you can specify the input type of the function parameters and
the return type of the value the function returns.
Function annotations are arbitrary Python expressions that are associated with various
parts of functions. These expressions are evaluated at compile time and have no life in
Python’s runtime environment. Python does not attach any meaning to these annotations.
They take life when interpreted by third-party libraries, for example, mypy.
52. What are Exception Groups in Python?
The latest feature of Python 3.11, Exception Groups. The ExceptionGroup can be handled
using a new except* syntax. The * symbol indicates that multiple exceptions can be
handled by each except* clause.
ExceptionGroup is a collection/group of different kinds of Exception. Without creating
Multiple Exceptions we can group together different Exceptions which we can later fetch
one by one whenever necessary, the order in which the Exceptions are stored in the
Exception Group doesn’t matter while calling them.
Python
try:
raise ExceptionGroup('Example ExceptionGroup', (
TypeError('Example TypeError'),
ValueError('Example ValueError'),
KeyError('Example KeyError'),
AttributeError('Example AttributeError')
))
except* TypeError:
...
except* ValueError as e:
...
except* (KeyError, AttributeError) as e:
...
53. What is Python Switch Statement
From version 3.10 upward, Python has implemented a switch case feature called
“structural pattern matching”. You can implement this feature with the match and case
keywords. Note that the underscore symbol is what you use to define a default case for
the switch statement in Python.
Note: Before Python 3.10 Python doesn’t support match Statements.
Python
match term:
case pattern-1:
action-1
case pattern-2:
action-2
case pattern-3:
action-3
case _:
action-default
54. What is Walrus Operator?
The Walrus Operator allows you to assign a value to a variable within an expression. This
can be useful when you need to use a value multiple times in a loop, but don’t want to
repeat the calculation.
The Walrus Operator is represented by the `:=` syntax and can be used in a variety of
contexts including while loops and if statements.
Note: Python versions before 3.8 doesn’t support Walrus Operator.
Python
names = ["Jacob", "Joe", "Jim"]
print("Before reverse:", n)
reverse = 0
while n != 0:
reverse = reverse * 10 + n % 10
n = n // 10
This code takes an input from the user and stores it in the variable n. Then, it prints the original
number n. After that, it initializes a variable reverse to 0 and uses a while loop to continuously add
the last digit of n to reverse while also updating n to be the integer division of n by 10, until n
becomes zero. Finally, it prints the reversed number.
Output:
1^3 = (1*1*1) = 1
3^3= (3*3*3) = 27
1+125+27 = 153
i=0
result = 0
number1 = n
temp = n
while n != 0:
n = n // 10
i += 1
while number1 != 0:
n = number1 % 10
result += pow(n, i)
number1 = number1 // 10
if temp == result:
else:
This code takes an input from the user and stores it in the variable n. Then, it initializes two variables
i and result to 0 and creates a copy of n in the variable number1 and temp.
The first while loop calculates the number of digits in n by repeatedly dividing n by 10 until it
becomes zero, and increments i by 1 for each iteration.
The second while loop calculates the sum of each digit of n raised to the power of i. It does this by
first finding the last digit of number1 using the modulus operator and adding the result of raising it to
the power of i to result. Then, it updates number1 to be the integer division of number1 by 10, until
number1 becomes zero.
Finally, the code checks if temp is equal to result. If they are equal, it prints “The number is an
Armstrong number”. Otherwise, it prints “The number is not an Armstrong number”.
If you entered 245 as the input, the code would produce the following output:
The number 245 is not an Armstrong number because 2^3 + 4^3 + 5^3 ≠ 245.
Here 2, 3 or any of the above number can only be divided by 1 or number itself.
Suppose if someone gives an input 2 then our program should give output “given number is a prime
number”.
And if someone gives 4 as an input then our program should give output “given number is not a
prime number”.
temp = 0
if n % i == 0:
temp = 1
break
if temp == 1:
else:
Output:
The number 7 is a prime number because it is only divisible by 1 and itself, so the for loop wouldn’t
find any numbers in the range 2 to 7//2 = 3 that divide 7 evenly.
4.Write a program in Python to print the Fibonacci series using iterative method.
A Fibonacci series is a series in which next number is a sum of previous two numbers.
For example : 0, 1, 1, 2, 3, 5, 8 ……
In Fibonacci Series, first number starts with 0 and second is with 1 and then its grow like,
1
0+1=1
1+1=2
1+2=3
2 + 3 = 5 and
so on…
Suppose if someone gives an input 5 then our program should print first 5 numbers of the series.
Like if someone given 5 as a input then our Fibonacci series which is written in C should print output
as,
0, 1, 1, 2, 3
first, second = 0, 1
if i <= 1:
result = i
else:
first = second
second = result
print(result
Output:
If you entered 7 as the input, the code would produce the following output:
3
5
The code generates the Fibonacci series up to the 7th term, which are the first 7 numbers in the
Fibonacci sequence: 0, 1, 1, 2, 3, 5, and 8.
5. Write a program in Python to print the Fibonacci series using recursive method.
def fibonacci(num):
if num == 0:
return 0
elif num == 1:
return 1
else:
print(fibonacci(i))
Output:
If you entered 5 as the input, the code would produce the following output:
The code generates the Fibonacci series up to the 5th term, which are the first 5 numbers in the
Fibonacci sequence: 0, 1, 1, 2, and 3.
6. Write a program in Python to check whether a number is palindrome or not using iterative
method.
In the above example you can see that 121 is a palindrome number. Because reverse of the 121 is
same as 121.
Suppose if someone gives an input 121 then our program should print “the given number is a
palindrome”.
And if someone given input 123 the our program should print “the given number is not a palindrome
number”.
temp = n
reverse = 0
while temp != 0:
temp = temp // 10
if reverse == n:
else:
Output:
If you entered 121 as the input, the code would produce the following output:
The code first stores the entered number in the temp variable and initializes reverse to 0. Then, it
uses a while loop to reverse the number. If the reversed number is equal to the original number, then
the code prints “The number is a palindrome”. If the reversed number is not equal to the original
number, then the code prints “The number is not a palindrome”.
7. Write a program in Python to check whether a number is palindrome or not using recursive
method.
return num
else:
def is_palindrome(num):
if num == reverse(num):
return True
else:
return False
if is_palindrome(n):
else:
Output: If you enter 535 as the input, the output will be:
Suppose if someone give 3 numbers as input 12, 15 and 10 then our program should return 15 as a
output because 15 is a greatest among three.
else:
If you enter 20, 30, and 10 as the inputs for n1, n2, and n3 respectively, the output will be:
n2 is the greatest
In the below program if someone give any input in 0 and 1 format then our program will run and give
output as given number is in binary format.
And if someone give another number different from 0 and 1 like 2, 3 or any other then our program
will give output as given number is not in a binary format.
def is_binary(num):
digit = num % 10
return False
num = num // 10
return True
if is_binary(num):
else:
Output:
10. Write a program in Python to find sum of digits of a number using recursion?
def sum_of_digits(num):
if num<10:
return num
else:
return (num%10) + sum_of_digits(num//10)
Output:
Enter a number: 10
11. Write a program in Python to swap two numbers without using third variable?
The swapping program without using third variable we will assign two different value to the different
variables.
a=a-b
b=a+b
a=b-a
print("After swapping")
Output:
After swapping
value of a is : 7
value of b is : 5
12. Write a program in Python to swap two numbers using third variable?
tempvar=a
a=b
b=tempvar
print("After swapping")
Output:
After swapping
value of a is : 20
value of b is : 10
def prime_factors(num):
i=2
factors = []
if num % i:
i += 1
else:
num //= i
factors.append(i)
if num > 1:
factors.append(num)
return factors
result = prime_factors(num)
Output:
Enter a number: 20
14. Write a program in Python to add two integer without using arithmetic operator?
This program will take two number as a Input. And After performing some operation as per program,
it will return addition.
Suppose if we give input 35 and 20. Our program will return 55 as an output without using of an
addition operator.
import java.util.Scanner;
int x, y;
x = sc.nextInt();
y = sc.nextInt();
while (y != 0) {
x = x ^ y;
y = temp << 1;
Output:
Sum = 30;
A perfect number is a positive integer that is equal to the sum of its positive divisors, excluding the
number itself.
sum=0
for i in range(1,(num//2)+1):
remainder = num % i
if remainder == 0:
sum = sum + i
if sum == num:
else:
Output:
The average of a set of numbers is simply the sum of the numbers divided by the total count of
numbers.
arr=[]
for i in range(0,size):
arr.append(elem)
avg=sum(arr)/size
Explanations:
• Define a function average that takes a list of numbers as input.
• Initialize two variables total and count to store the sum of numbers and the number of items
respectively.
• Loop through the list of numbers and add each number to the total and increment count by
1.
• Call the function with a list of numbers, and store the result in a variable result.
Output:
A factorial of a number n is the product of all positive integers less than or equal to n. It is denoted as
n!. For example, the factorial of 5 is 5! = 5 x 4 x 3 x 2 x 1 = 120.
In this article, we will write a Python program to calculate the factorial of a given number using an
iterative method.
def factorial(n):
fact = fact * i
return fact
result = factorial(num)
Output:
Enter a number: 5
3. Using a for loop, we are iterating over the range from 1 to n+1, and at each iteration, we are
multiplying fact with the current value of i.
4. The fact variable will keep updating its value at each iteration until i becomes equal to n+1.
5. Finally, the function returns the fact variable, which is the factorial of the number n.
6. After defining the function, we are taking an input of a number from the user, and calling
the factorial function by passing the input number as an argument.
This is how the iterative method can be used to calculate the factorial of a number in Python.
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n-1)
Output:
A program to check whether a given number is even or odd can be written in Python using simple
conditional statements.
def even_odd(num):
if num % 2 == 0:
else:
print(even_odd(num))
Output:
Enter a number: 5
Explanation:
• In the first line, we have defined a function named even_odd that takes a single
argument num.
• Inside the function, we use an if-else statement to check if the remainder of the division
of num by 2 is equal to 0.
• If the remainder is equal to 0, the number is even, and the function returns “The number is
Even”.
• If the remainder is not equal to 0, the number is odd, and the function returns “The number
is Odd”.
• After defining the function, we take input from the user and store it in the variable num.
• Finally, we call the function even_odd and pass the value of num as an argument. The result
is printed using the print statement.
The following program demonstrates how to print first n Prime Numbers using a for loop and a while
loop in Python:
def is_prime(num):
if num > 1:
if (num % i) == 0:
return Falseelse:
return Trueelse:
prime_list = []
count = 0
if is_prime(num):
prime_list.append(num)
count += 1
num += 1return prime_list
Output:
In this program, we have defined two functions – is_prime and print_first_n_prime. The is_prime
function takes a number as an argument and returns True if the number is prime, otherwise False.
The print_first_n_prime function takes the number of prime numbers we want to print and returns a
list of those prime numbers.
In the main program, we first ask the user for the value of n, which is the number of prime numbers
we want to print. Then, we call the print_first_n_prime function, which returns a list of prime
numbers, and finally, we print that list.
The following program demonstrates how to print Prime Number in a given range in Python:
def is_prime(n):
if n < 2:
return False
if n % i == 0:
return False
return True
primes = []
if is_prime(num):
primes.append(num)
return primes
if result == []:
Explanation:
• The program first defines a helper function is_prime to check if a number is prime or not.
• is_prime function checks if the number is less than 2, in that case it returns False as 1 and 0
are not prime numbers.
• If the number is greater than or equal to 2, it checks the number by dividing it with all
numbers between 2 and the square root of the number. If the number is divisible by any of
these numbers, it returns False, meaning the number is not prime.
• The function prime_in_range takes two inputs lower and upper which are the lower and
upper limits of the range of numbers we want to find prime numbers in.
• The function loops through all numbers from lower to upper and calls the is_prime function
to check if the number is prime or not. If the number is prime, it appends it to the
list primes.
• Finally, the program takes the lower and upper limits as inputs from the user and calls
the prime_in_range function to get the list of prime numbers in the given range. If the list is
empty, it prints “No prime number found in the given range.”, otherwise, it prints the list of
prime numbers.
Here is a simple Python program to find the smallest number among three:
smallest = num1
smallest = num2
smallest = num3
return smallest
Example Output:
Enter the first number: 25
Explanation:
1. The function find_smallest() takes three numbers as arguments and returns the smallest
number among them.
3. The next two if statements compare num2 and num3 with smallest and updates the value
of smallest if either num2 or num3 is smaller.
5. In the main part of the code, the three numbers are taken as input from the user and stored
in the variables num1, num2, and num3.
6. The smallest number is found using the find_smallest() function and stored in the
variable smallest.
23. Python program to calculate the power using the POW method.
The pow method in Python can be used to calculate the power of a number. The function pow(base,
exponent) returns the base raised to the power of exponent. Here is an example of how to use the
pow method in Python to calculate the power:
In this example, we take the base and exponent as input from the user and then use
the pow method to calculate the power of the base raised to the exponent. Finally, we print the
result.
24. Python Program to calculate the power without using POW function.(using for loop).
Python code to calculate the power using ‘for-loop’
result=1;
result *= base
print(result)
Output:
Explanation:
For the input from the user, the base number is 5, and the exponent number is 4. The ‘base
exponent’ will be 54, which is 5x5x5x5 i.e. 625.
25. Python Program to calculate the power without using POW function.(using while loop).
result=1;
#using while loop with a condition that come out of while loop if exponent is 0
while exponent != 0:
exponent-=1
print(result)
Output:
Explanation:
For the input from the user, the base number is 5, and the exponent number is 4. The ‘base e
exponent’ will be 54, which is 5x5x5x5 i.e. 625.
print("square =",num*num)
Output:
Explanation:
For input 7, the output generated by our program is 7*7 i.e. equals 49.
print("square =",num*num*num)
Output:
Explanation:
For input 7, the output generated by our program is 5*5*5 i.e. equals 125.
import math
if num<0:
print("Negative numbers can't have square roots")
else:
Output 1:
Explanation:
For input 81, the output generated by our program is math.sqrt(81) which is equal to 9.0.
greater = num1
else:
greater = num2
while(True):
lcm = greater
break
greater += 1
print("LCM of",num1,"and",num2,"=",greater)
Output 1:
Explanation:
For inputs 9 and 18, we are dividing the ‘greater’ with both num1 and num2 to find the common
multiple of 9 and 18. First greater assigned with value 18 and then in while loop it checking
continuously that if ‘18/9 == 0 and 18/18 == 0’ which is true so the value of greater is returned as the
L.C.M. of 9 and 18.
30. Python Program to find GCD or HCF of two numbers.
minimum = num2
else:
minimum = num1
hcf = i
print("hcf/gcd of",num1,"and",num2,"=",hcf)
Output :
Explanation:
For inputs 8 and 2, the program is finding the highest factor that is common in both 8 and 2.
The factor of 8 is 1,2,4,8 and the factor of 2 is 1,2. The highest factor common in both is 2.
def gcd(num1,num2):
if num2 == 0:
return num1;
Output :
Explanation:
For the inputs 8 and 6, which are then passed as an argument in recursive function gcd().
Problem statement
DecToBin(num):
if num > 1:
DecToBin(num // 2)
print num % 2
Example
dec_val = 35DecimalToBinary(dec_val)
Output
100011
Output
100011
The common method of calculating the octal representation of a decimal number is to divide the
number by 8 until it becomes 0. After the division is over, we print the array storing the remainders
at each division point in reverse order.
def DecimalToOctal(n):
i=0
# run until n is 0
while (n != 0):
octal[i] = n % 8
n = int(n / 8)
i += 1
print(octal[j], end=""
Output:
41
34. Python Program to check the given year is a leap year or not.
def CheckLeap(Year):
(Year % 4 == 0)):
else:
# Printing result
CheckLeap(Year)
Output:
Explanation:
We have implemented all the three mandatory conditions (that we listed above) in the program by
using the ‘and’ and ‘or’ keyword inside the if else condition. After getting input from the user, the
program first will go to the input part and check if the given year is a leap year. If the condition
satisfies, the program will print ‘Leap Year’; else program will print ‘Not a leap year.’
# given formula
%(celsius_1, Fahrenheit_1))
print("----OR----")
Output:
----OR----
celsius = ((fahrenheit-32)*5)/9
print("Celcius= ",celsius)
Output 1:
Explanation:
#taking the values of principal, rate of interest and time from the user
simpleInterest = (principal*rate*time)/100
Output :
Explanation:
For the input value of the principal, the rate of interest and the time simple interest is calculated
using the formula
def remove_char(s1,s2):
print(s1.replace(s2, ''))
remove_char(s1,s2)
Output:
def remove_char(s1,s2):
print(s1.translate(dict))
remove_char(s1,s2)
Output:
2. Python Program to count occurrence of a given characters in string.
count = 0
for i in range(len(string)):
if(string[i] == char):
count = count + 1
Output:
index, count = 0, 0
if(string[index] == char):
count = count + 1
index = index + 1
Output:
Using Method
for i in range(len(string)):
if(string[i] == char):
count = count + 1
return count
Output:
if (sorted(str1) == sorted(str2)) :
return True
else :
return False
if anagramCheck(str1,str2):
print("Anagram")
else:
print("Not an anagram")
Output:
4. Python program to check a String is palindrome or not.
def isPalindrome(string):
if string[i] != string[len(string)-i-1]:
return False
return True
if (isPalindrome(string)):
else:
Output:
else:
Output :
Explanation:
As we can see for the character ‘o’ output generated is “Vowel”, which is obvious as o is a vowel and
satisfying the ‘if ’ statement
else: #this block will execute if the condition will not satisfies
Output :
Explanation:
Here , the output generated is “ Given Character 8 is a Digit” for input 8 , as the 8>=’0’ and 8<=’9’ , so
both condition satisfy well hence the if block of our program is executed.
7.Python program to check given character is digit or not using isdigit() method.
Python code to check given character is digit or not using ‘isdigit()’ function:
if(ch.isdigit()):
else:
Output :
Explanation :
In this case, the user has given 5 as an inputs, and the code generate the output as “The Given
Character 5 is a Digit”. This shows the 5 is a numerical value, which is true. In the ‘condition’ block of
our program, ch.isdigit() returned true for character ‘5’. So the ‘if’ block executes and the desired
output is generated.
Here’s one way to replace spaces with a given character in a string in Python:
replacement_char = "-"
print(output_string
Output:
end-of-the-day
Explanation :
The code replaces spaces in a given string with a specified character. It defines a function
replace_space that takes a string string and a character char as input and returns a new string with
spaces replaced by the char input.
The string.replace() method is used to replace occurrences of a specified string in the input string
with another string. In this case, we replace each occurrence of the space character ” ” with the char
input.
The input string “end of the day” and the replacement character “-” are defined and passed as
arguments to the replace_space function. The output string is stored in the output_string variable
and printed.
9. Python program to replace the string space with a given character using replace() method.
Here’s one way to replace spaces with a given character in a string using the replace() method in
Python:
replacement_char = "**"
print(output_string
Output:
end-of-the-day
Here’s a Python program that converts the lowercase characters in a string to uppercase characters:
def to_uppercase(str):
return str.upper()
Output:
Here’s a Python program that converts the lowercase vowels in a string to uppercase vowels:
def convert_vowels_to_uppercase(str):
vowels = "aeiou"
str_list = list(str)
for i in range(len(str_list)):
if str_list[i].lower() in vowels:
str_list[i] = str_list[i].upper()
return "".join(str_list)
convert_vowels_to_uppercase(input_string))
Output:
def delete_vowels(str):
vowels = "aeiouAEIOU"
str_without_vowels = "".join([c for c in str if c not in vowels])
return str_without_vowels
delete_vowels(input_string))
Output:
Here’s a Python program that counts the occurrence of vowels and consonants in a given string:
def count_vowels_and_consonants(str):
vowels = "aeiouAEIOU"
consonants = "bcdfghjklmnpqrstvwxyzBCDFGHJKLMNPQRSTVWXYZ"
vowels_count = 0
consonants_count = 0
if char in vowels:
vowels_count += 1
consonants_count += 1
Output:
Number of vowels: 4
Number of consonants: 7
14. Python program to print the highest frequency character in a String.
def highest_frequency_char(str):
char_frequency = {}
char_frequency[char] = char_frequency.get(char, 0) + 1
max_frequency = max(char_frequency.values())
if frequency == max_frequency:
return char
highest_frequency_char = highest_frequency_char(input_string)
Output:
15. Python program to Replace First Occurrence Of Vowel With ‘-‘ in String.
Here’s a Python program that replaces the first occurrence of a vowel in a given string with the
character ‘-‘:
def replace_vowel(string):
if char in vowels:
new_string = replace_vowel(string)
print(new_string)
H-llo World!
Python code to count alphabets, digits, and special characters in the string
#taking string as an input from the user
alphabets=0
digits=0
specialChars=0
for i in string:
if i.isalpha():
alphabets+=1
elif i.isdigit():
digits+=1
specialChars+=1
Output:
Explanation:
For the input string ‘Ques123!@we12’, the alphabets used in this string are ‘Q’, ‘u’, ‘e’, ‘s’, ‘w’, ‘e’. The
digits used in this string are ‘1’, ‘2’, ‘3’, ‘1’, and ‘2’.
And the special character used in this string is ‘!’, ‘@’, and ‘#’.
Here’s a simple program in Python that separates the characters in a given string:
def separate_characters(string):
return characters
string = "Hello World!"
separated_characters = separate_characters(string)
print(separated_characters)
['H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd', '!']
result=''
for i in string:
if i!=' ':
result += i
Output 1:
Explanation:
In this case, the input string is ‘que scolweb site’, which consists of two spaces in the string. During
the iteration of the string, While comparing using ‘if’ statement if space found then skips the spaces.
And if no space found then concatenate the remaining character in the empty string ‘result’ and
finally print the ‘result’ as the output of the program. In this case, the output is ‘quescolwebsite’.
Explanation:
In this example, the two strings entered by the user are ‘quescol’ and ‘website’ after using the join()
method which took two strings as iterable and returns the output as ‘quescolwebsite’.
20. Python program to concatenate two strings without using join() method.
Output 1:
Explanation:
The user is given the input ‘quescol’ and ‘website’, now to join them together our program used the
‘+’ operator which joins two strings together and the final string generated is ‘quescolwebsite’.
def remove_duplicates(string):
new_string = ""
new_string += char
return new_string
output_string = remove_duplicates(input_string)
print(output_string)
This will output:
example string
This program uses a loop to iterate over each character in the input string, and checks if the
character is already in the new string using the in operator. If the character is not in the new string, it
is added to it. The final output is the string with no repeated characters.
sum=0
for i in string:
if i.isdigit():
sum=sum+int(i)
print("sum=",sum)
Output :
Explanation:
In this example, the user input the string ‘qwel123rty456’. While iterating the character of the string,
the digits were found using the isdigit() method and when this happens the if block start executing
which is taking the sum of digits. Finally, the program will return the sum of those digits as the
output of the program.
result=""
for i in str1:
count = 0
for j in str1:
if i == j:
count=count+1
if count > 1:
break
if count == 1:
result+=i
Output:
Explanation:
For the input string ‘aabbcdeeffgh’, as the characters ‘a’, ‘b’, ‘e’, and ‘f’ are repeating but ‘c’, ‘d’, ‘g’ and
‘h’ are not repeating so the generated output should be ‘cdgf’.
def copy_string(original_string):
copied_string = original_string[:]
return copied_string
You can call this function and pass the original string as an argument, like this:
copied_string = copy_string(original_string)
strList=list(string)
#sorting elements of list
sortedString=''.join(sorted(strList))
Output 1:
Explanation:
For the input string ‘quescol’, firstly, the string’s elements get stored in a list that looks like
Then, after using the sorted() function which re-arranges the list elements in ascending order as
Finally, the join() function will concatenate the elements of the string and returns the concatenated
string as output.
strList=list(string)
Output:
Explanation:
For the input string ‘quescol’, firstly, the string’s elements get stored in a list that looks like
Then, after using the sorted() function with argument ‘reverse =True’ which re-arranges the list
elements in descending order as
1. Write a program in Python for, In array 1-100 numbers are stored, one number is missing how do
you find it.
Here’s one way to find the missing number in an array of 1-100 numbers:
def find_missing_number(array):
actual_sum = sum(array)
missing_number = find_missing_number(array)
This code first calculates the expected sum of the numbers 1-100, then calculates the actual sum of
the numbers in the input array. The missing number can then be found by subtracting the actual sum
from the expected sum. In this example, the missing numbers are 3, 4, 6, 7, and 9, so the missing
number found by the program would be 5.
2. Write a program in Python for, In a array 1-100 multiple numbers are duplicates, how do you
find it.
def find_duplicates(array):
duplicate_numbers = []
if array.count(i) > 1:
duplicate_numbers.append(i)return duplicate_numbers
array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 9, 10, 10, 11, 12, 13, 14, 15, 15]
duplicates = find_duplicates(array)
This code iterates over the numbers 1 to 100, and for each number it checks the count of that
number in the input array. If the count is greater than 1, the number is added to a list of duplicate
numbers. The final list of duplicate numbers is returned as the result. In this example, the duplicates
would be [9, 10, 15].
3. Write a program in Python for, How to find all pairs in array of integers whose sum is equal to
given number.
Here’s one way to find all pairs of integers in an array whose sum is equal to a given number:
pairs = []
for i in range(len(array)):
pairs.append((array[i], array[j]))
return pairs
sum_value = 10
This code iterates over the elements in the input array, and for each element, it checks if adding the
element to any other element in the array results in the sum_value. If a pair is found, it is added to
the pairs list. The final list of pairs is returned as the result. In this example, the pairs with sum 10
would be [(1, 9), (2, 8), (3, 7), (4, 6)].
4. Write a program in Python for, How to compare two array is equal in size or not.
array1 = [1, 2, 3, 4, 5]
if are_equal:
else:
This code uses the len function to find the length of each input array, and compares the lengths using
the equality operator ==. If the lengths are equal, the function returns True, otherwise it
returns False. The output of this code would be “The arrays have the same length.”
Here’s one way to find the largest and smallest numbers in an array:
def find_min_max(array):
return min(array), max(array)
This code uses the min and max functions to find the minimum and maximum elements in the
input array, respectively. The result of these functions are returned as a tuple, which can then be
unpacked into separate variables minimum and maximum. In this example, the minimum number
would be 1 and the maximum number would be 10.
Here’s one way to find the second highest number in an integer array in Python:
def second_highest(numbers):
return sorted_numbers[1]
numbers = [1, 2, 3, 4, 5, 5, 5, 6, 7, 8, 9, 9]
In this implementation, the second_highest function takes an array of integers as input and returns
the second highest number by:
1. Removing duplicates from the input array using set, which returns a set of unique elements
3. Returning the second element of the sorted set, which is the second highest number.
Here’s a program in Python to find the top two maximum numbers in an array:
def top_two_maximum(numbers):
numbers = [1, 2, 3, 4, 5, 5, 5, 6, 7, 8, 9, 9]
top_two = top_two_maximum(numbers)
In this implementation, the top_two_maximum function takes an array of integers as input and
returns a tuple containing the top two maximum numbers by:
1. Removing duplicates from the input array using set, which returns a set of unique elements
Let’s learn writing program for how to remove duplicates from an array Python.
To remove duplicate elements from an array first we will count the occurrence of all elements.
After finding occurrence we will print elements only one time and can get element after removing
duplicates.
import array
for x in range(n):
count.append(0)
arr.append(x)
for x in range(n):
count[arr[x]]=count[arr[x]]+1
if count[arr[x]]==1:
print(arr[x])
Output:
Here’s a Python program to find the top two maximum numbers in an array:
def top_two_maximum(arr):
second_max = first_max
first_max = num
second_max = num
arr = [1, 5, 2, 9, 8, 3]
print(top_two_maximum(arr))
def reverse_array(arr):
return arr[::-1]
arr = [1, 2, 3, 4, 5]
print(reverse_array(arr))
def reverse_array(arr):
return arr[::-1]
arr = [1, 2, 3, 4, 5]
print(reverse_array(arr))
1. Using a loop:
def reverse_array(arr):
arr = [1, 2, 3, 4, 5]
print(reverse_array(arr))
def array_length(arr):
return len(arr)
arr = [1, 2, 3, 4, 5]
print(array_length(arr))
arr.append(element)
return arr
arr = [1, 2, 3, 4, 5]
print(insert_at_end(arr, 6))
arr[index:index] = [element]
return arr
arr = [1, 2, 3, 4, 5]
print(insert_at_index(arr, 2, 6))
def delete_at_end(arr):
return arr[:-1]
arr = [1, 2, 3, 4, 5]
print(delete_at_end(arr))
The output will be [1, 2, 3, 4].
arr.remove(element)
return arr
arr = [1, 2, 3, 4, 5]
print(delete_element(arr, 3))
arr = [1, 2, 3, 4, 5]
print(delete_at_index(arr, 2))
def sum_of_elements(arr):
return sum(arr)
arr = [1, 2, 3, 4, 5]
print(sum_of_elements(arr))
def even_numbers(arr):
arr = [1, 2, 3, 4, 5]
print(even_numbers(arr))
def odd_numbers(arr):
arr = [1, 2, 3, 4, 5]
print(odd_numbers(arr))
21. Python program to perform left rotation of array elements by two positions.
Here’s a Python program to perform left rotation of array elements by two positions:
arr = [1, 2, 3, 4, 5]
print(left_rotate(arr, 2))
Here’s a Python program to perform right rotation of array elements by two positions:
arr = [1, 2, 3, 4, 5]
print(right_rotate(arr, 2))
arr1 = [1, 2, 3]
arr2 = [4, 5, 6]
print(merge_arrays(arr1, arr2))
count = Counter(arr)
arr = [1, 2, 3, 4, 5, 3, 2, 2]
print(highest_frequency(arr)
The output will be 2, which is the element with the highest frequency in the array.
if b == 0:
return a
print(add_recursive(2, 3))
Here’s a Python program to find the sum of digits of a number using recursion:
def sum_of_digits(n):
if n == 0:
print(sum_of_digits(123))
class Node:
self.data = data
def __init__(self):
new_node = Node(data)
if self.head is None:
self.head = new_node
return
last_node = self.head
while last_node.next:
last_node = last_node.next
last_node.next = new_node
def traverse(self):
current_node = self.head
while current_node:
current_node = current_node.nextprint("None")
linked_list = LinkedList()
linked_list.insert_at_end(1)
linked_list.insert_at_end(2)
linked_list.insert_at_end(3)
linked_list.traverse()
class Node:
self.data = data
def __init__(self):
new_node = Node(data)
if self.head is None:
self.head = new_node
return
last_node = self.head
while last_node.next:
last_node = last_node.next
last_node.next = new_node
new_node = Node(data)
new_node.next = self.head
self.head = new_node
def traverse(self):
current_node = self.head
while current_node:
current_node = current_node.nextprint("None")
linked_list = LinkedList()
linked_list.insert_at_end(1)
linked_list.insert_at_end(2)
linked_list.insert_at_end(3)
linked_list.insert_at_beginning(0)
linked_list.traverse()
class Node:
self.data = data
def __init__(self):
new_node = Node(data)
if self.head is None:
self.head = new_node
return
last_node = self.head
while last_node.next:
last_node = last_node.next
last_node.next = new_node
def reverse(self):
prev = None
current = self.head
while current:
next = current.next
current.next = prev
prev = current
current = next
self.head = prev
def traverse(self):
current_node = self.head
while current_node:
current_node = current_node.nextprint("None")
linked_list = LinkedList()
linked_list.insert_at_end(1)
linked_list.insert_at_end(2)
linked_list.insert_at_end(3)
linked_list.traverse()
linked_list.reverse()
linked_list.traverse()
class Node:
def __init__(self):
new_node = Node(data)
if self.head is None:
self.head = new_node
return
last_node = self.head
while last_node.next:
last_node = last_node.next
last_node.next = new_node
current_node = self.head
while current_node:
if current_node.data == key:
return True
linked_list = LinkedList()
linked_list.insert_at_end(1)
linked_list.insert_at_end(2)
linked_list.insert_at_end(3)
if linked_list.search(3):
print("Element found")
else:
Element found
Here is a Python program to delete a node in a singly linked list at the beginning, end, and a given
location:
class Node:
self.data = data
def __init__(self):
new_node = Node(data)
if self.head is None:
self.head = new_node
return
last_node = self.head
while last_node.next:
last_node = last_node.next
last_node.next = new_node
def delete_at_beginning(self):
if self.head is None:
return
if self.head is None:
self.head = Nonereturn
second_last_node = self.head
while second_last_node.next.next:
second_last_node = second_last_node.next
if self.head is None:
returnif position == 0:
self.head = self.head.nextreturn
current_node = self.head
current_node = current_node.next
current_position += 1if current_node.next is None:
return
current_node.next = current_node.next.next
linked_list = LinkedList()
linked_list.insert_at_end(1)
linked_list.insert_at_end(2)
linked_list.insert_at_end(3)
linked_list.delete_at_beginning()
linked_list.delete_at_end()
linked_list.delete_at_position(0
With these functions, you can delete a node at the beginning, end, or given location of a singly linked
list in Python.
6. Write a program in Python to find 3rd element of Linked List from last in single pass.
Here is a Python program to find the 3rd element from the last in a single pass in a linked list:
class Node:
self.data = data
def __init__(self):
new_node = Node(data)
if self.head is None:
self.head = new_node
return
last_node = self.head
while last_node.next:
last_node = last_node.next
last_node.next = new_node
first_pointer = self.head
second_pointer = self.head
for i in range(n):
if second_pointer is None:
return None
first_pointer = first_pointer.next
linked_list = LinkedList()
linked_list.insert_at_end(1)
linked_list.insert_at_end(2)
linked_list.insert_at_end(3)
linked_list.insert_at_end(4)
linked_list.insert_at_end(5)
result = linked_list.find_nth_element_from_last(3)
print(result
This program uses two pointers, first_pointer and second_pointer, to traverse the linked list. The
second_pointer is moved n positions ahead, and then both pointers are moved until the
second_pointer reaches the end of the linked list. The data of the node where the first_pointer is
pointing to will be the nth element from the last.
7. Write a program in Python to find middle element of a linked list in single pass.
Here is a Python program to find the middle element of a linked list in a single pass:
class Node:
self.data = data
def __init__(self):
new_node = Node(data)
if self.head is None:
self.head = new_node
return
last_node = self.head
while last_node.next:
last_node = last_node.next
last_node.next = new_node
def find_middle_element(self):
slow_pointer = self.head
fast_pointer = self.head
slow_pointer = slow_pointer.next
linked_list = LinkedList()
linked_list.insert_at_end(1)
linked_list.insert_at_end(2)
linked_list.insert_at_end(3)
linked_list.insert_at_end(4)
linked_list.insert_at_end(5)
result = linked_list.find_middle_element()
print(result
This program uses two pointers, slow_pointer and fast_pointer, to traverse the linked list. The
fast_pointer moves two nodes ahead for every iteration, while the slow_pointer moves one node
ahead. When the fast_pointer reaches the end of the linked list, the slow_pointer will be pointing to
the middle node.
FAQ’s
• Python is designed to be highly readable and compatible with different platforms such as
Mac, Windows, Linux, Raspberry Pi, etc.
An interpreted language is any programming language that executes its statements line by line.
Programs written in Python run directly from the source code, with no intermediary compilation step
PYTHONPATH has a role similar to PATH. This variable tells Python Interpreter where to locate the
module files imported into a program. It should include the Python source library directory and the
directories containing Python source code. PYTHONPATH is sometimes preset by Python Installer.