0% found this document useful (0 votes)
4 views

Programs

Uploaded by

Suresh
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)
4 views

Programs

Uploaded by

Suresh
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/ 9

Q89.

How to get items of series A that are not available in


another series B?
Ans. The below program will help you in identifying items in series A but no in series B:

1
2 import pandas as pd
3
4 # Creating 2 pandas Series
ps1 = pd.Series([2, 4, 8, 20, 10, 47, 99])
5 ps2 = pd.Series([1, 3, 6, 4, 10, 99, 50])
6
7 print("Series 1:")
8 print(ps1)
9 print("nSeries 2:")
10 print(ps2)
11
# Using Bitwise NOT operator along
12 # with pandas.isin()
13 print("nItems of Series 1 not present in Series 2:")
14 res = ps1[~ps1.isin(ps2)]
15 print(res)
16
Output:

Series 1:

0 2

1 4

2 8

3 20

4 10

5 47

6 99

Series 2:

0 1

1 3

2 6

3 4
4 10

5 99

6 50

Items of Series 1 not present in Series 2:

0 2

2 8

3 20

5 47

Q90. How to get the items that are not common to both
the given series A and B?
Ans. The below program is to identify the elements which are not common in both series:

1
import pandas as pd
2
import numpy as np
3 sr1 = pd.Series([1, 2, 3, 4, 5])
4 sr2 = pd.Series([2, 4, 6, 8, 10])
5 print("Original Series:")
6 print("sr1:")
print(sr1)
7 print("sr2:")
8 print(sr2)
9 print("nItems of a given series not present in another given
10 series:")
11 sr11 = pd.Series(np.union1d(sr1, sr2))
sr22 = pd.Series(np.intersect1d(sr1, sr2))
12 result = sr11[~sr11.isin(sr22)]
13 print(result)
14
Output:

Original Series:

sr1:

0 1

1 2

2 3

3 4
4 5

sr2:

0 2

1 4

2 6

3 8

4 10

Items of a given series not present in another given series:

0 1

2 3

4 5

5 6

6 8

7 10

Next, let us have a look at some Basic Python Programs in these Python Interview Questions.
Basic Python Programs – Interview
Questions
Q91. Write a program in Python to execute the Bubble sort
algorithm.

1
def bs(a):
2 # a = name of list
3 b=len(a)-1nbsp;
4 # minus 1 because we always compare 2 adjacent values
5 for x in range(b):
6 for y in range(b-x):
a[y]=a[y+1]
7
8 a=[32,5,3,6,7,54,87]
9 bs(a)
10
Output: [3, 5, 6, 7, 32, 54, 87]

Q92. Write a program in Python to produce Star triangle.

1 def pyfunc(r):
2 for x in range(r):
3 print(' '*(r-x-1)+'*'*(2*x+1))
4 pyfunc(9)
Output:

*
***
*****
*******
*********
***********
*************
***************
*****************

Q93. Write a program to produce Fibonacci series in


Python.

1
2 # Enter number of terms needednbsp;#0,1,1,2,3,5....
3 a=int(input("Enter the terms"))
f=0;#first element of series
4 s=1#second element of series
5 if a=0:
6 print("The requested series is",f)
7 else:
print(f,s,end=" ")
8
for x in range(2,a):
9 print(next,end=" ")
10 f=s
11 s=next
12

Output: Enter the terms 5 0 1 1 2 3

Q94. Write a program in Python to check if a number is


prime.

1
2 a=int(input("enter number"))
if a=1:
3 for x in range(2,a):
4 if(a%x)==0:
5 print("not prime")
6 break
else:
7
print("Prime")
8 else:
9 print("not prime")
10
Output:

enter number 3

Prime
Q95. Write a program in Python to check if a sequence is a
Palindrome.

1 a=input("enter sequence")
2 b=a[::-1]
3 if a==b:
4 print("palindrome")
else:
5
print("Not a Palindrome")
6
Output:

enter sequence 323 palindrome

Q96. Write a one-liner that will count the number of


capital letters in a file. Your code should work even if the
file is too big to fit in memory.
Ans:Let us first write a multiple line solution and then convert it to one-liner code.

1 with open(SOME_LARGE_FILE) as fh:


2 count = 0
3 text = fh.read()
4 for character in text:
if character.isupper():
5
count += 1
6
We will now try to transform this into a single line.

1 count sum(1 for line in fh for character in line if character.isupper())


Q97. Write a sorting algorithm for a numerical dataset in
Python.
Ans:The following code can be used to sort a list in Python:

1 list = ["1", "4", "0", "6", "9"]


2 list = [int(i) for i in list]
3 list.sort()
print (list)
4
Q98. Looking at the below code, write down the final
values of A0, A1, …An.

1 A0 = dict(zip(('a','b','c','d','e'),(1,2,3,4,5)))
2 A1 = range(10)A2 = sorted([i for i in A1 if i in A0])
3 A3 = sorted([A0[s] for s in A0])
4 A4 = [i for i in A1 if i in A3]
5 A5 = {i:i*i for i in A1}
A6 = [[i,i*i] for i in A1]
6 print(A0,A1,A2,A3,A4,A5,A6)
7
Ans:The following will be the final outputs of A0, A1, … A6

A0 = {'a': 1, 'c': 3, 'b': 2, 'e': 5, 'd': 4} # the order may vary


A1 = range(0, 10)
A2 = []
A3 = [1, 2, 3, 4, 5]
A4 = [1, 2, 3, 4, 5]
A5 = {0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81}
A6 = [[0, 0], [1, 1], [2, 4], [3, 9], [4, 16], [5, 25], [6, 36], [7, 49], [8,
64], [9, 81]]
Q99. Write a program in Python to print the given number
is odd or even.

1
2 </pre>
def check_odd_even(number):
3 if number % 2 == 0:
4 print(f"{number} is even.")
5 else:
6 print(f"{number} is odd.")
7
8 # Input from the user
num = int(input("Enter a number: "))
9
10 # Checking if the number is odd or even
11 check_odd_even(num)
12 <pre>
13
In this program a function named check_odd_even() is defined which takes a number as input
and prints whether it’s odd or even. After the program is executed, it will prompt the user to
enter a number and calls this function to determine if the entered number is odd or even.

Q100. Write a program to check if the given number is


Armstrong or not.

1 </pre>
def is_armstrong(num):
2
# Calculate the number of digits in the number
3 num_digits = len(str(num))
4
5 # Initialize sum to store the result
6 sum = 0
7
8 # Temporary variable to store the original number
temp = num
9
10 # Calculate Armstrong sum
11 while temp > 0:
12 digit = temp % 10
13 sum += digit ** num_digits
14 temp //= 10
15
# Check if the number is Armstrong or not
16 if num == sum:
17 return True
18 else:
19 return False
20
21
22
23 # Input from the user
24 number = int(input("Enter a number: "))
25
26 # Check if the number is Armstrong or not
if is_armstrong(number):
27 print(f"{number} is an Armstrong number.")
28 else:
29 print(f"{number} is not an Armstrong number.")
30 <pre>
31
32
In this program the function is_armstrong() which takes a number as input and
returns True if it’s an Armstrong number, otherwise False. It will prompt the user to enter a
number and calls this function to determine if the entered number is an Armstrong number or
not when executed.

Q101. Write a Python Program for calculating simple


interest.

1
def calculate_simple_interest(principal, rate, time):
2 # Simple interest formula: SI = (P * R * T) / 100
3 simple_interest = (principal * rate * time) / 100
4 return simple_interest
5
6 # Input from the user
principal = float(input("Enter the principal amount: "))
7 rate = float(input("Enter the annual interest rate (in percentage): "))
8 time = float(input("Enter the time period (in years): "))
9
10 # Calculate simple interest
11 interest = calculate_simple_interest(principal, rate, time)
12
13 # Display the result
print(f"The simple interest for the principal amount ${principal}, annual interest
14 period of {time} years is ${interest}.")
15
The function calculate_simple_interest() takes the principal amount, annual interest rate,
and time period as input and returns the simple interest. Then, it prompts the user to enter
these values and calls the function to calculate the simple interest, finally displaying the
result.

Q102. Write a Python program to check whether the string


is Symmetrical or Palindrome.

1 </div>
<div>
2
3
4
5
6 def is_symmetrical(input_string):
# Check if the string is symmetrical
7 return input_string == input_string[::-1]
8
9 def is_palindrome(input_string):
10 # Remove spaces and convert to lowercase
11 input_string = input_string.replace(" ", "").lower()
12 # Check if the string is a palindrome
return input_string == input_string[::-1]
13
14 # Input from the user
15 string = input("Enter a string: ")
16
17 # Check if the string is symmetrical
18 if is_symmetrical(string):
print(f"{string} is symmetrical.")
19
else:
20 print(f"{string} is not symmetrical.")
21
22 # Check if the string is a palindrome
23 if is_palindrome(string):
24 print(f"{string} is a palindrome.")
else:
25 print(f"{string} is not a palindrome.")
26
27 </div>
28 <div>
29
30
This program defines two functions is_symmetrical() and is_palindrome(). The
is_symmetrical() function checks if the string is symmetrical, and the is_palindrome() function
checks if the string is a palindrome. Then, it prompts the user to enter a string and calls these
functions to determine whether the entered string is symmetrical or a palindrome, and prints
the result accordingly.

Q104. Write a Python program to find yesterday’s, today’s


and tomorrow’s date.

1 from datetime import datetime, timedelta


2
def get_dates():
3
# Get today's date
4 today = datetime.now().date()
5
6 # Calculate yesterday's and tomorrow's date
7 yesterday = today - timedelta(days=1)
8 tomorrow = today + timedelta(days=1)
9
return yesterday, today, tomorrow
10
11 # Get the dates
12
13 yesterday_date, today_date, tomorrow_date = get_dates()
14
15 # Display the dates
16 print("Yesterday's date:", yesterday_date)
17 print("Today's date:", today_date)
print("Tomorrow's date:", tomorrow_date)
18
19
This program uses the datetime module to work with dates. It defines a
function get_dates() to calculate yesterday’s, today’s, and tomorrow’s dates
using timedelta objects. Then, it calls this function and prints the dates accordingly.

You might also like