ÔN TẬP FINAL NGÔN NGỮ LẬP TRÌNH

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 121

II.

PYTHON BASIC (PART II)


1. Write a Python function that takes a sequence of numbers and determines
whether all the numbers are different from each other.

# Define a function named test_distinct that takes a list 'data' as a parameter.

def test_distinct(data):

# Check if the length of the list is equal to the length of the set created from
the list.

if len(data) == len(set(data)):

# If the lengths are equal, it means all elements in the list are distinct.

return True

else:

# If the lengths are not equal, there are duplicate elements in the list.

return False

# Call the test_distinct function with a list [1, 5, 7, 9] and print the result.

print(test_distinct([1, 5, 7, 9]))

# Call the test_distinct function with a list [2, 4, 5, 5, 7, 9] and print the result.

print(test_distinct([2, 4, 5, 5, 7, 9]))
2. Write a Python program that creates all possible strings using the letters
'a', 'e', 'i', 'o', and 'I'. Ensure that each character is used only once.

# Import the 'random' module to shuffle elements in a list randomly.

import random

# Create a list of characters containing vowels.

char_list = ['a', 'e', 'i', 'o', 'u']

# Shuffle the elements in the 'char_list' randomly.

random.shuffle(char_list)

# Print the shuffled list of characters as a string.

print(''.join(char_list))

3. Write a Python program that removes and prints every third number from a
list of numbers until the list is empty.
# Define a function named 'remove_nums' that takes a list 'int_list' as a
parameter.

def remove_nums(int_list):

# Set the starting position for removal to the 3rd element (0-based index).

position = 3 - 1
# Initialize the index variable to 0.

idx = 0

# Get the length of the input list.

len_list = len(int_list)

# Continue removing elements until the list is empty.

while len_list > 0:

# Calculate the new index based on the starting position and current
index.

idx = (position + idx) % len_list

# Print and remove the element at the calculated index.

print(int_list.pop(idx))

# Decrement the length of the list.

len_list -= 1

# Create a list of numbers.

nums = [10, 20, 30, 40, 50, 60, 70, 80, 90]

# Call the 'remove_nums' function with the list of numbers.

remove_nums(nums)
4. Write a Python program to identify unique triplets whose three elements
sum to zero from an array of n integers.
# Define a function named 'three_sum' that takes a list of numbers 'nums' as a
parameter.

def three_sum(nums):

# Initialize an empty list to store the results.

result = []

# Sort the input list in ascending order.

nums.sort()

# Iterate through the list up to the third-to-last element.

for i in range(len(nums) - 2):

# Skip duplicate values at the current position.

if i > 0 and nums[i] == nums[i - 1]:

continue

# Set two pointers, 'l' and 'r', to find the other two elements in the triplet.

l, r = i + 1, len(nums) - 1

# Perform a two-pointer search to find triplets with the sum equal to zero.

while l < r:
s = nums[i] + nums[l] + nums[r]

if s > 0:

r -= 1

elif s < 0:

l += 1

else:

# Found a triplet with the sum equal to zero, add it to the result.

result.append((nums[i], nums[l], nums[r]))

# Remove duplicates in the left and right pointers.

while l < r and nums[l] == nums[l + 1]:

l += 1

while l < r and nums[r] == nums[r - 1]:

r -= 1

# Move the pointers towards the center.

l += 1

r -= 1
# Return the final result containing unique triplets.

return result

# Create a list of numbers.

x = [1, -6, 4, 2, -1, 2, 0, -2, 0]

# Call the 'three_sum' function with the list and print the result.

print(three_sum(x))

5. Write a Python program to make combinations of 3 digits.


# Create an empty list to store formatted numbers.

numbers = []

# Iterate through numbers from 0 to 999 (exclusive).

for num in range(1000):

# Convert the number to a string and fill with zeros to make it three digits
long.

num = str(num).zfill(3)

# Print the last formatted number (outside the loop, indentation issue).

print(num)
# Append the last formatted number to the 'numbers' list.

numbers.append(num)

6. Write a Python program that prints long text, converts it to a list, and prints
all the words and the frequency of each word.
# Define a multiline string containing a passage about the United States
Declaration of Independence.

string_words = '''United States Declaration of Independence

From Wikipedia, the free encyclopedia

... (omitting the rest for brevity) ...

... much scholarly inquiry.

Europe and Latin America, as well as Africa (Liberia) and Oceania (New
Zealand) during the first half of the

19th century.'''

# Split the string into a list of words.

word_list = string_words.split()

# Create a list of word frequencies using list comprehension.

word_freq = [word_list.count(n) for n in word_list]


# Print the original string, the list of words, and pairs of words along with their
frequencies.

print("String:\n {} \n".format(string_words))

print("List:\n {} \n".format(str(word_list)))

print("Pairs (Words and Frequencies:\n {}".format(str(list(zip(word_list,


word_freq)))))

7. Write a Python program to count the number of each character in a text


file.
# Import necessary modules.

import collections # Import the 'collections' module for Counter.

import pprint # Import 'pprint' for pretty printing.

# Get the file name as input from the user.

file_input = input('File Name: ')

# Open the file in read mode using a 'with' statement to ensure proper
handling of resources.

with open(file_input, 'r') as info:

# Read the contents of the file and count the occurrences of each
uppercase character.

count = collections.Counter(info.read().upper())
# Use 'pprint' to format the count output for better readability.

value = pprint.pformat(count)

# Print the formatted count of characters in the file.

print(value)

8. Write a Python program that retrieves the top stories from Google News.
# Import the 'bs4' module for web scraping and 'urlopen' function for opening
URLs.

import bs4

from bs4 import BeautifulSoup as soup

from urllib.request import urlopen

# URL of the news RSS feed

news_url = "https://news.google.com/news/rss"

# Open the URL using 'urlopen' and read the content of the webpage.

Client = urlopen(news_url)

xml_page = Client.read()

Client.close()
# Create a BeautifulSoup object to parse the XML content of the webpage.

soup_page = soup(xml_page, "xml")

# Find all XML tags with the name "item" to extract news items.

news_list = soup_page.findAll("item")

# Print news title, URL, and publish date for each news item.

for news in news_list:

print(news.title.text)

print(news.link.text)

print(news.pubDate.text)

print("-" * 60)

9. Write a Python program to get a list of locally installed Python modules.


# Import the 'pkg_resources' module for working with Python packages.

import pkg_resources

# Get the list of installed packages using 'pkg_resources.working_set'.

installed_packages = pkg_resources.working_set
# Create a sorted list of strings representing installed packages and their
versions.

installed_packages_list = sorted(["%s==%s" % (i.key, i.version) for i in


installed_packages])

# Print each package and its version in the sorted list.

for m in installed_packages_list:

print(m)

10. Write a Python program to display some information about the OS where
the script is running.
# Import the 'platform' module and alias it as 'pl'.

import platform as pl

# List of attributes to retrieve from the 'platform' module.

os_profile = [

'architecture',

'linux_distribution',

'mac_ver',

'machine',

'node',

'platform',
'processor',

'python_build',

'python_compiler',

'python_version',

'release',

'system',

'uname',

'version',

# Iterate through the list of attributes.

for key in os_profile:

# Check if the attribute exists in the 'platform' module.

if hasattr(pl, key):

# Print the attribute name and its corresponding value.

print(key + ": " + str(getattr(pl, key)()))

11. Write a Python program to check the sum of three elements (each from an array)
from three arrays is equal to a target value. Print all those three-element combinations.
Sample data:
/*
X = [10, 20, 20, 20]
Y = [10, 20, 30, 40]
Z = [10, 30, 40, 20]
target = 70
*/

# Import the 'itertools' module for advanced iteration tools and 'partial' from
'functools'.

import itertools

from functools import partial

# Define three lists and a target sum value.

X = [10, 20, 20, 20]

Y = [10, 20, 30, 40]

Z = [10, 30, 40, 20]

T = 70

# Define a function to check if the sum of a set of numbers equals a given


target.

def check_sum_array(N, *nums):

if sum(x for x in nums) == N:

return (True, nums)


else:

return (False, nums)

# Generate the Cartesian product of the three lists.

pro = itertools.product(X, Y, Z)

# Create a partial function using the 'check_sum_array' function and the target
sum 'T'.

func = partial(check_sum_array, T)

# Use 'starmap' to apply the partial function to each element in the Cartesian
product.

sums = list(itertools.starmap(func, pro))

# Use a set to store unique valid combinations.

result = set()

# Iterate through the sums and print unique valid combinations.

for s in sums:

if s[0] == True and s[1] not in result:


result.add(s[1])

print(result)

12. Write a Python program that generates a list of all possible permutations
from a given collection of distinct numbers.
# Define a function 'permute' that generates all permutations of a list of
numbers.

def permute(nums):

# Initialize the result list with an empty permutation.

result_perms = [[]]

# Iterate through each number in the input list.

for n in nums:

# Create a new list to store permutations with the current number.

new_perms = []

# Iterate through each existing permutation in the result list.

for perm in result_perms:

# Insert the current number at different positions within each existing


permutation.

for i in range(len(perm)+1):

new_perms.append(perm[:i] + [n] + perm[i:])


# Update the result list with the new permutations.

result_perms = new_perms

# Return the final list of permutations.

return result_perms

# Create a list of numbers.

my_nums = [1, 2, 3]

# Print the original collection and the collection of distinct numbers.

print("Original Collection: ", my_nums)

print("Collection of distinct numbers:\n", permute(my_nums))

13. Write a Python program to get all possible two-digit letter combinations
from a 1-9 digit string.
string_maps = {
"1": "abc",
"2": "def",
"3": "ghi",
"4": "jkl",
"5": "mno",
"6": "pqrs",
"7": "tuv",
"8": "wxy",
"9": "z"
}


# Define a function 'letter_combinations' that generates letter combinations based on
input digits.

def letter_combinations(digits):

# Check if the input string is empty.

if digits == "":

return []

# Define a mapping of digits to corresponding letters.

string_maps = {

"1": "abc",

"2": "def",

"3": "ghi",

"4": "jkl",

"5": "mno",

"6": "pqrs",

"7": "tuv",
"8": "wxy",

"9": "z"

# Initialize the result list with an empty string.

result = [""]

# Iterate through each digit in the input string.

for num in digits:

# Create a temporary list to store new combinations.

temp = []

# Iterate through each existing combination in the result list.

for an in result:

# Append each letter corresponding to the current digit to create new


combinations.

for char in string_maps[num]:

temp.append(an + char)

# Update the result list with the new combinations.


result = temp

# Return the final list of letter combinations.

return result

# Define input digit strings and print the corresponding letter combinations.

digit_string = "47"

print(letter_combinations(digit_string))

digit_string = "29"

print(letter_combinations(digit_string))

14. Write a Python program to add two positive integers without using the '+'
operator.
Note: Use bit wise operations to add two numbers.
# Define a function 'add_without_plus_operator' that performs addition without
using the '+' operator.

def add_without_plus_operator(a, b):

# Continue the loop until the carry (b) becomes zero.

while b != 0:

# Calculate the bitwise AND of 'a' and 'b'.

data = a & b

# XOR 'a' and 'b' to get the sum without considering carry.
a=a^b

# Left shift the carry by 1 position.

b = data << 1

# Return the final sum.

return a

# Test the function with different inputs and print the results.

print(add_without_plus_operator(2, 10))

print(add_without_plus_operator(-20, 10))

print(add_without_plus_operator(-10, -20))

15. Write a Python program to check the priority of the four operators (+, -,
*, /).
# Import the 'deque' class from the 'collections' module and the 're' module for
regular expressions.

from collections import deque

import re

# Define operators, parentheses, and operator priorities.

__operators__ = "+-/*"

__parenthesis__ = "()"
__priority__ = {

'+': 0,

'-': 0,

'*': 1,

'/': 1,

# Define a function 'test_higher_priority' to compare the priorities of two


operators.

def test_higher_priority(operator1, operator2):

# Return True if the priority of 'operator1' is higher than or equal to


'operator2'.

return __priority__[operator1] >= __priority__[operator2]

# Test the function with different operator pairs and print the results.

print(test_higher_priority('*','-'))

print(test_higher_priority('+','-'))

print(test_higher_priority('+','*'))

print(test_higher_priority('+','/'))

print(test_higher_priority('*','/'))
16. Write a Python program to get the third side of a right-angled triangle from
two given sides.
# Define a function 'pythagoras' that calculates the missing side of a right-
angled triangle.

def pythagoras(opposite_side, adjacent_side, hypotenuse):

# Check if the opposite side is marked as unknown.

if opposite_side == str("x"):

return ("Opposite = " + str(((hypotenuse**2) - (adjacent_side**2))**0.5))

# Check if the adjacent side is marked as unknown.

elif adjacent_side == str("x"):

return ("Adjacent = " + str(((hypotenuse**2) - (opposite_side**2))**0.5))

# Check if the hypotenuse is marked as unknown.

elif hypotenuse == str("x"):

return ("Hypotenuse = " + str(((opposite_side**2) +


(adjacent_side**2))**0.5))

else:

return "You know the answer!" # Return this message if all sides are
known.

# Test the function with different inputs and print the results.

print(pythagoras(3, 4, 'x'))
print(pythagoras(3, 'x', 5))

print(pythagoras('x', 4, 5))

print(pythagoras(3, 4, 5))

17. Write a Python program to get all strobogrammatic numbers that are of
length n.
A strobogrammatic number is a number whose numeral is rotationally
symmetric, so that it appears the same when rotated 180 degrees. In other
words, the numeral looks the same right-side up and upside down (e.g., 69,
96, 1001).
For example,
Given n = 2, return ["11", "69", "88", "96"].
Given n = 3, return ['818', '111', '916', '619', '808', '101', '906', '609', '888', '181',
'986', '689']

# Define a function 'gen_strobogrammatic' that generates strobogrammatic


numbers of length 'n'.

def gen_strobogrammatic(n):

"""

:type n: int

:rtype: List[str]

"""

# Call the helper function with the given length 'n'.

result = helper(n, n)
return result

# Define a helper function 'helper' to recursively generate strobogrammatic


numbers.

def helper(n, length):

# Base case: when 'n' is 0, return an empty string.

if n == 0:

return [""]

# Base case: when 'n' is 1, return the strobogrammatic digits for length 1.

if n == 1:

return ["1", "0", "8"]

# Recursive case: generate strobogrammatic numbers for 'n-2'.

middles = helper(n-2, length)

result = []

# Iterate over the generated middles and create strobogrammatic numbers.

for middle in middles:

# If 'n' is not equal to the original length, add "0" on both sides.

if n != length:

result.append("0" + middle + "0")

# Add strobogrammatic numbers with "8" in the middle.


result.append("8" + middle + "8")

# Add strobogrammatic numbers with "1" in the middle.

result.append("1" + middle + "1")

# Add strobogrammatic numbers with "9" in the first half and "6" in the
second half.

result.append("9" + middle + "6")

# Add strobogrammatic numbers with "6" in the first half and "9" in the
second half.

result.append("6" + middle + "9")

return result

# Test the function with different values of 'n' and print the results.

print("n = 2: \n", gen_strobogrammatic(2))

print("n = 3: \n", gen_strobogrammatic(3))

print("n = 4: \n", gen_strobogrammatic(4))

18. Write a Python program to find the median among three given numbers.
# Input the first number from the user

x = input("Input the first number: ")

# Input the second number from the user


y = input("Input the second number: ")

# Input the third number from the user

z = input("Input the third number: ")

# Print a message indicating that the program will calculate the median

print("Median of the above three numbers -")

# Check conditions to determine the median and print the result

if y < x and x < z:

print(x)

elif z < x and x < y:

print(x)

elif z < y and y < x:

print(y)

elif x < y and y < z:

print(y)

elif y < z and z < x:

print(z)
elif x < z and z < y:

print(z)

19. Write a Python program that finds the value of n when n degrees of
number 2 are written sequentially on a line without spaces between them.
# Define a function 'ndegrees' that calculates the highest power of a number
'n'

# such that the resulting number is found within a given input string 'num'.

def ndegrees(num):

ans = True # Initialize a boolean variable 'ans' to True.

n, tempn, i = 2, 2, 2 # Initialize variables 'n', 'tempn', and 'i'.

# Use a while loop to check conditions.

while ans:

# Check if the string representation of 'tempn' is found within 'num'.

if str(tempn) in num:

i += 1 # Increment 'i'.

tempn = pow(n, i) # Update 'tempn' with the next power of 'n'.

else:

ans = False # Set 'ans' to False if 'tempn' is not found in 'num'.


return i - 1 # Return the highest power (i-1).

# Test the 'ndegrees' function with different input strings and print the results.

print(ndegrees("2481632"))

print(ndegrees("248163264"))

20. Write a Python program to find the number of zeros at the end of a
factorial of a given positive number.
Range of the number(n): (1 <= n <= 2*109).
# Define a function 'factendzero' that calculates the number of trailing zeros

# in the factorial of a given number 'n'.

def factendzero(n):

# Initialize variables 'x' and 'y'.

x = n // 5

y=x

# Use a while loop to iteratively calculate the number of trailing zeros.

while x > 0:

x /= 5

y += int(x)
return y # Return the final count of trailing zeros.

# Test the 'factendzero' function with different values of 'n' and print the
results.

print(factendzero(5))

print(factendzero(12))

print(factendzero(100))

21. Write a Python program to find the number of notes (Samples of notes: 10,
20, 50, 100, 200, 500) against an amount.
Range - Number of notes(n) : n (1 <= n <= 1000000).
# Define a function 'no_notes' that calculates the minimum number of notes
required

# to represent a given amount 'a' using denominations of 500, 200, 100, 50,
20, and 10.

def no_notes(a):

# List of denominations in descending order.

Q = [500, 200, 100, 50, 20, 10]

# Initialize a variable 'x' to 0.

x=0
# Iterate over each denomination in the list.

for i in range(6):

q = Q[i] # Get the current denomination.

x += int(a / q) # Add the count of notes for the current denomination to


'x'.

a = int(a % q) # Update the remaining amount after using the current


denomination.

# Check if there is any remaining amount not covered by the available


denominations.

if a > 0:

x = -1 # If there is a remainder, set 'x' to -1.

return x # Return the minimum number of notes required.

# Test the 'no_notes' function with different amounts and print the results.

print(no_notes(880))

print(no_notes(1000))

22. Write a Python program to create a sequence where the first four
members of the sequence are equal to one. Each successive term of the
sequence is equal to the sum of the four previous ones. Find the Nth member
of the sequence.
# Define a recursive function 'new_seq' that generates a new sequence based
on the sum

# of the four previous terms. The base cases are when 'n' is 1, 2, 3, or 4,
where the

# function returns 1.

def new_seq(n):

if n == 1 or n == 2 or n == 3 or n == 4:

return 1

# Recursive step: The function returns the sum of the four previous terms.

return new_seq(n - 1) + new_seq(n - 2) + new_seq(n - 3) + new_seq(n - 4)

# Test the 'new_seq' function with different values of 'n' and print the results.

print(new_seq(5))

print(new_seq(6))

print(new_seq(7))

23. Write a Python program that accepts a positive number and subtracts
from it the sum of its digits, and so on. Continue this operation until the
number is positive.
# Define a function 'repeat_times' that repeatedly subtracts the sum of the
digits
# of a number from the number until it becomes non-positive, and then returns
the result.

def repeat_times(n):

# Convert the input number 'n' to a string for digit manipulation.

n_str = str(n)

# Continue the loop while 'n' is greater than 0.

while n > 0:

# Subtract the sum of the digits of 'n' from 'n'.

n -= sum([int(i) for i in list(n_str)])

# Update 'n_str' with the string representation of the updated 'n'.

n_str = list(str(n))

# Return the final value of 'n'.

return n

# Test the 'repeat_times' function with different values of 'n' and print the
results.

print(repeat_times(9))
print(repeat_times(20))

print(repeat_times(110))

print(repeat_times(5674))

24. Write a Python program to find the total number of even or odd divisors of
a given integer.
# Define a function 'divisor' that calculates the number of divisors for a given
integer 'n'.

def divisor(n):

# Count the number of integers from 1 to 'n' that divide 'n' without
remainder.

x = len([i for i in range(1, n + 1) if not n % i])

# Return the count of divisors.

return x

# Test the 'divisor' function with different values of 'n' and print the results.

print(divisor(15))

print(divisor(12))

print(divisor(9))

print(divisor(6))

print(divisor(3))
25. Write a Python program to find the digits that are missing from a given
mobile number.
# Define a function 'absent_digits' that finds the absent digits from the given
list 'n'.

def absent_digits(n):

# Create a set containing all possible digits (0 to 9).

all_nums = set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])

# Convert the list 'n' to a set of integers.

n = set([int(i) for i in n])

# Find the symmetric difference between the set of all_nums and the set 'n'.

n = n.symmetric_difference(all_nums)

# Sort the result to get a list of absent digits.

n = sorted(n)

# Return the list of absent digits.

return n

# Test the 'absent_digits' function with a given list and print the result.
print(absent_digits([9, 8, 3, 2, 2, 0, 9, 7, 6, 3]))

26. Write a Python program to compute the summation of the absolute difference of
all distinct pairs in a given array (non-decreasing order).
Sample array: [1, 2, 3]
Then all the distinct pairs will be:
12
13
23

# Define a function 'sum_distinct_pairs' that calculates the sum of distinct


pairs.

def sum_distinct_pairs(arr):

# Initialize the result variable to store the sum.

result = 0

# Initialize the index variable.

i=0

# Iterate through the array elements.

while i < len(arr):

# Calculate the contribution of the current element to the sum.

result += i * arr[i] - (len(arr) - i - 1) * arr[i]


# Increment the index.

i += 1

# Return the final result.

return result

# Test the 'sum_distinct_pairs' function with different arrays and print the
results.

print(sum_distinct_pairs([1, 2, 3]))

print(sum_distinct_pairs([1, 4, 5]))

27. Write a Python program to find the type of the progression (arithmetic
progression / geometric progression) and the next successive member of the three
successive members of a sequence.
According to Wikipedia, an arithmetic progression (AP) is a sequence of numbers
such that the difference of any two successive members of the sequence is a constant.
For instance, the sequence 3, 5, 7, 9, 11, 13, . . . is an arithmetic progression with
common difference 2. For this problem, we will limit ourselves to arithmetic
progression whose common difference is a non-zero integer.
On the other hand, a geometric progression (GP) is a sequence of numbers where each
term after the first is found by multiplying the previous one by a fixed non-zero
number called the common ratio. For example, the sequence 2, 6, 18, 54, . . . is a
geometric progression with common ratio 3. For this problem, we will limit ourselves
to geometric progression whose common ratio is a non-zero integer.

# Define a function 'ap_gp_sequence' that identifies whether a given


sequence is an Arithmetic Progression (AP) or Geometric Progression (GP).

def ap_gp_sequence(arr):

# Check if the first three elements are all zero.

if arr[0] == arr[1] == arr[2] == 0:

return "Wrong Numbers" # If all three are zero, it's not a valid sequence.

else:

# Check if the sequence is an AP (Arithmetic Progression).

if arr[1] - arr[0] == arr[2] - arr[1]:

n = 2 * arr[2] - arr[1]

return "AP sequence, " + 'Next number of the sequence: ' + str(n)

else:

# If not an AP, assume it's a GP (Geometric Progression).

n = arr[2] ** 2 / arr[1]

return "GP sequence, " + 'Next number of the sequence: ' + str(n)

# Test the 'ap_gp_sequence' function with different sequences and print the
results.
print(ap_gp_sequence([1, 2, 3]))

print(ap_gp_sequence([2, 6, 18]))

print(ap_gp_sequence([0, 0, 0]))

28. Write a Python program to print the length of the series and the series from the
given 3rd term, 3rd last term and the sum of a series.
Sample Data:
Input third term of the series: 3
Input 3rd last term: 3
Input Sum of the series: 15
Length of the series: 5
Series:
12345

# Input the third term of the series

tn = int(input("Input third term of the series:"))

# Input the 3rd last term

tltn = int(input("Input 3rd last term:"))

# Input the sum of the series

s_sum = int(input("Sum of the series:"))

# Calculate the length of the series using the formula for the sum of an
arithmetic series

n = int(2 * s_sum / (tn + tltn))

print("Length of the series: ", n)


# Calculate the common difference 'd' based on the length of the series

if n - 5 == 0:

d = (s_sum - 3 * tn) // 6

else:

d = (tltn - tn) / (n - 5)

# Calculate the first term 'a' using the third term and common difference

a = tn - 2 * d

j=0

# Print the series

print("Series:")

for j in range(n - 1):

print(int(a), end=" ")

a += d

print(int(a), end=" ")

29. Write a Python program to find common divisors between two numbers in
a given pair.
# Function to calculate the greatest common divisor (GCD) of two numbers
def ngcd(x, y):

i=1

while(i <= x and i <= y):

# Check if both x and y are divisible by i

if(x % i == 0 and y % i == 0):

gcd = i # Set gcd to the current common factor

i += 1

return gcd

# Function to calculate the number of common divisors of two numbers

def num_comm_div(x, y):

# Calculate the greatest common divisor (GCD) using the ngcd function

n = ngcd(x, y)

result = 0

z = int(n ** 0.5) # Square root of n

i=1

while(i <= z):

if(n % i == 0):

result += 2 # Increment the count for each pair of divisors


if(i == n/i):

result -= 1 # Adjust count if i is a perfect square divisor

i += 1

return result

# Test cases

print("Number of common divisors: ", num_comm_div(2, 4))

print("Number of common divisors: ", num_comm_div(2, 8))

print("Number of common divisors: ", num_comm_div(12, 24))

30. Write a Python program to reverse the digits of a given number and add them to
the original. Repeat this procedure if the sum is not a palindrome.
Note: A palindrome is a word, number, or other sequence of characters which reads
the same backward as forward, such as madam or racecar.

# Function to reverse a number and add it to the original number until a


palindrome is obtained

def rev_number(n):

s = 0 # Initialize a variable to count the number of iterations

while True:

k = str(n) # Convert the number to a string for comparison

if k == k[::-1]: # Check if the number is a palindrome


break # If it is a palindrome, exit the loop

else:

m = int(k[::-1]) # Reverse the digits and convert back to an integer

n += m # Add the reversed number to the original number

s += 1 # Increment the iteration count

return n # Return the palindrome obtained

# Test cases

print(rev_number(1234)) # Example: 1234 + 4321 = 5555 (palindrome)

print(rev_number(1473)) # Example: 1473 + 3741 = 5214 + 4125 = 9339


(palindrome)

31. Write a Python program to count the number of carry operations for each
addition problem.
According to Wikipedia " In elementary arithmetic, a carry is a digit that is transferred
from one column of digits to another column of more significant digits. It is part of the
standard algorithm to add numbers together by starting with the rightmost digits and
working to the left. For example, when 6 and 7 are added to make 13, the "3" is
written to the same column and the "1" is carried to the left".

# Define a function to count the number of carry operations when adding two
numbers digit by digit.

def carry_number(x, y):


# Initialize a counter for carry operations.

ctr = 0

# Check if both numbers are zero, in which case there are no carry
operations.

if x == 0 and y == 0:

return 0

# Initialize a carry digit to zero.

z=0

# Loop through each digit from right to left.

for i in reversed(range(10)):

# Sum the current digits of x, y, and the carry digit.

z = x % 10 + y % 10 + z

# Check if the sum is greater than 9 (carry condition).

if z > 9:

z = 1 # Set the carry digit to 1.

else:
z = 0 # Reset the carry digit to 0.

# Increment the counter based on the carry digit.

ctr += z

# Move to the next digit by removing the last digit of each number.

x //= 10

y //= 10

# Check the counter to determine the result.

if ctr == 0:

return "No carry operation."

elif ctr == 1:

return ctr # Return the count of carry operations.

else:

return ctr # Return the count of carry operations.

# Test cases

print(carry_number(786, 457)) # Example with carry operations

print(carry_number(5, 6)) # Example with no carry operations


32. Write a Python program to find the heights of the top three buildings in
descending order from eight given buildings.
Input:
0 <= height of building (integer) <= 10,000
Input the heights of eight buildings:
25
35
15
16
30
45
37
39
Heights of the top three buildings:
45
39
37

# Print statement to prompt the user to input the heights of eight buildings

print("Input the heights of eight buildings:")

# List comprehension to take input for the heights of eight buildings

l = [int(input()) for i in range(8)]

# Print statement to display the heights of the top three buildings


print("Heights of the top three buildings:")

# Sorting the list of building heights in ascending order

l = sorted(l)

# Printing the top three building heights in descending order using slicing and
the 'sep' parameter for newlines

print(*l[:4:-1], sep='\n')

33. Write a Python program to compute the digit number of the sum of two
given integers.
Input:
Each test case consists of two non-negative integers x and y which are separated by a
space in a line.
0 <= x, y <= 1,000,000
Input two integers(a b):
57
Sum of two integers a and b.:
2

# Print statement to prompt the user to input two integers

print("Input two integers(a b): ")


# Using map and split to take two space-separated integers as input, then
converting them to integers

a, b = map(int, input().split(" "))

# Print statement to display the number of digits in the sum of a and b

print("Number of digits of a and b:")

# Using len and str functions to find and print the length (number of digits) of
the sum of a and b

print(len(str(a + b)))

34. Write a Python program to check whether three given lengths (integers) of
three sides form a right triangle. Print "Yes" if the given sides form a right
triangle otherwise print "No".
Input:
Integers separated by a single space.
1 <= length of the side <= 1,000
Input three integers(sides of a triangle)
867
No


# Print statement to prompt the user to input three integers representing sides of a
triangle

print("Input three integers (sides of a triangle)")


# Using map and split to take three space-separated integers as input, then
converting them to a list of integers

int_num = list(map(int, input().split()))

# Sorting the list of integers to assign variables x, y, and z with the values of
the sorted sides

x, y, z = sorted(int_num)

# Checking if the given sides form a Pythagorean triple (right-angled triangle)

if x**2 + y**2 == z**2:

print('Yes') # Print 'Yes' if the condition is met

else:

print('No') # Print 'No' if the condition is not met

35. Write a Python program which solve the equation:


ax+by=c
dx+ey=f
Print the values of x, y where a, b, c, d, e and f are given.
Input:
a,b,c,d,e,f separated by a single space.
(-1,000 <= a,b,c,d,e,f <= 1,000)
Input the value of a, b, c, d, e, f:
586794
Values of x and y:
-2.000 2.000

# Print statement to prompt the user to input the values of a, b, c, d, e, f

print("Input the value of a, b, c, d, e, f:")

# Using map and split to take six space-separated float values as input, then
converting them to float

a, b, c, d, e, f = map(float, input().split())

# Calculating the determinant of the system of linear equations

n=a*e-b*d

# Print statement to display the values of x and y

print("Values of x and y:")

# Checking if the determinant is not zero to avoid division by zero

if n != 0:

# Calculating the values of x and y using Cramer's rule

x = (c * e - b * f) / n
y = (a * f - c * d) / n

# Printing the values of x and y with three decimal places

print('{:.3f} {:.3f}'.format(x + 0, y + 0))

36. Write a Python program to compute the amount of debt in n months. Each
month, the loan adds 5% interest to the $100,000 debt and rounds to the
nearest 1,000 above.
Input:
An integer n (0 <= n <= 100)
Input number of months: 7
Amount of debt: $144000

# Function to round a given number to the nearest thousand

def round_n(n):

if n % 1000:

return (1 + n // 1000) * 1000

else:

return n

# Recursive function to compute the debt amount for a given number of


months

def compute_debt(n):
if n == 0:

return 100000

return int(round_n(compute_debt(n - 1) * 1.05))

# Print statement to prompt the user to input the number of months

print("Input number of months:")

# Calling the compute_debt function with user input, calculating the debt
amount, and printing the result

result = compute_debt(int(input()))

print("Amount of debt: ", "$" + str(result).strip())

37. Write a Python program that reads an integer n and finds the number of
combinations of a,b,c and d (0 = a,b,c,d = 9) where (a + b + c + d) will be
equal to n.
Input:
n (1 <= n <= 50)
Input the number(n): 15
Number of combinations: 592

# Import the itertools module to work with iterators and combinatorial functions

import itertools
# Prompt the user to input a number 'n'

print("Input the number(n):")

# Read the user input and convert it to an integer

n = int(input())

# Initialize the variable 'result' to store the count of combinations

result = 0

# Iterate over all combinations of (i, j, k) where i, j, k are in the range [0, 9]

for (i, j, k) in itertools.product(range(10), range(10), range(10)):

# Check if the sum of i, j, and k lies between 0 and 9 (inclusive)

result += (0 <= n - (i + j + k) <= 9)

# Print the number of combinations that satisfy the condition

print("Number of combinations:", result)

38. Write a Python program to print the number of prime numbers that are
less than or equal to a given number.
Input:
n (1 <= n <= 999,999)
Input the number(n): 35
Number of prime numbers which are less than or equal to n.: 11

# Initialize a list to represent prime numbers up to 500000

primes = [1] * 500000

primes[0] = 0 # 0 is not a prime number

# Sieve of Eratosthenes: Mark non-prime numbers in the list

for i in range(3, 1000, 2):

if primes[i // 2]:

primes[(i * i) // 2::i] = [0] * len(primes[(i * i) // 2::i])

# Prompt user to input a number 'n'

print("Input the number(n):")

n = int(input())

# Check and print the number of primes less than or equal to 'n'

if n < 4:

print("Number of prime numbers which are less than or equal to n.:", n - 1)

else:
print("Number of prime numbers which are less than or equal to n.:",
sum(primes[:(n + 1) // 2]) + 1)

39. Write a program to compute the radius and the central coordinate (x, y) of
a circle which is constructed from three given points on the plane surface.
Input:
x1, y1, x2, y2, x3, y3 separated by a single space.
Input three coordinate of the circle:
936836
Radius of the said circle:
3.358
Central coordinate (x, y) of the circle:
6.071 4.643
⇒ # Prompt the user to input three coordinates of the circle

print("Input three coordinates of the circle:")

x1, y1, x2, y2, x3, y3 = map(float, input().split())

# Calculate distances between points

c = (x1 - x2)**2 + (y1 - y2)**2

a = (x2 - x3)**2 + (y2 - y3)**2

b = (x3 - x1)**2 + (y3 - y1)**2

# Calculate the cross-product

s = 2 * (a * b + b * c + c * a) - (a**2 + b**2 + c**2)


# Calculate the central coordinate of the circle

px = (a * (b + c - a) * x1 + b * (c + a - b) * x2 + c * (a + b - c) * x3) / s

py = (a * (b + c - a) * y1 + b * (c + a - b) * y2 + c * (a + b - c) * y3) / s

# Calculate the radius of the circle

ar = a**0.5

br = b**0.5

cr = c**0.5

r = ar * br * cr / ((ar + br + cr) * (-ar + br + cr) * (ar - br + cr) * (ar + br - cr))**0.5

# Print the radius and central coordinate of the circle

print("Radius of the said circle:")

print("{:>.3f}".format(r))

print("Central coordinate (x, y) of the circle:")

print("{:>.3f}".format(px), "{:>.3f}".format(py))

40. Write a Python program to check if a point (x,y) is in a triangle or not. A


triangle is formed by three points.
Input:
x1,y1,x2,y2,x3,y3,xp,yp separated by a single space.
Input three coordinate of the circle:
936836
Radius of the said circle:
3.358
Central coordinate (x, y) of the circle:
6.071 4.643

# Prompt user to input coordinates of the triangle vertices (x1, y1), (x2, y2),
(x3, y3),

# and the point (xp, yp) to check if it lies inside the triangle

print("Input x1, y1, x2, y2, x3, y3, xp, yp:")

x1, y1, x2, y2, x3, y3, xp, yp = map(float, input().split())

# Calculate the cross products (c1, c2, c3) for the point relative to each edge
of the triangle

c1 = (x2 - x1) * (yp - y1) - (y2 - y1) * (xp - x1)

c2 = (x3 - x2) * (yp - y2) - (y3 - y2) * (xp - x2)

c3 = (x1 - x3) * (yp - y3) - (y1 - y3) * (xp - x3)

# Check if all cross products have the same sign (inside the triangle) or
different signs (outside the triangle)

if (c1 < 0 and c2 < 0 and c3 < 0) or (c1 > 0 and c2 > 0 and c3 > 0):

print("The point is in the triangle.")


else:

print("The point is outside the triangle.")

41. Write a Python program to compute and print the sum of two given integers
(greater or equal to zero). In the event that the given integers or the sum exceed 80
digits, print "overflow".
Input first integer:
25
Input second integer:
22
Sum of the two integers: 47

# Print statement to prompt the user to input the first integer

print("Input first integer:")

# Take user input and convert it to an integer

x = int(input())

# Print statement to prompt the user to input the second integer

print("Input second integer:")

# Take user input and convert it to an integer

y = int(input())
# Check if any of the integers or their sum exceeds 10^80

if x >= 10 ** 80 or y >= 10 ** 80 or x + y >= 10 ** 80:

print("Overflow!") # Print overflow message if the condition is met

else:

print("Sum of the two integers: ", x + y) # Print the sum if no overflow


occurs

42. Write a Python program that accepts six numbers as input and sorts them
in descending order.
Input:
Input consists of six numbers n1, n2, n3, n4, n5, n6 (-100000 <= n1, n2, n3, n4, n5, n6
<= 100000). The six numbers are separated by a space.
Input six integers:
15 30 25 14 35 40
After sorting the said integers:
40 35 30 25 15 14

# Print statement to prompt the user to input six integers

print("Input six integers:")

# Take user input, split it into a list of integers, and assign it to the variable
'nums'
nums = list(map(int, input().split()))

# Sort the list of integers in ascending order

nums.sort()

# Reverse the order of the sorted list to get descending order

nums.reverse()

# Print statement to indicate the result after sorting the integers

print("After sorting the said integers:")

# Unpack and print the sorted integers

print(*nums)

43. Write a Python program to test whether two lines PQ and RS are parallel.
The four points are P(x1, y1), Q(x2, y2), R(x3, y3), S(x4, y4).
Input:
x1,y1,x2,y2,x3,y3,xp,yp separated by a single space
Input x1,y1,x2,y2,x3,y3,xp,yp:
25648397
PQ and RS are not parallel
⇒ # Print statement to prompt the user to input coordinates of two line segments (PQ
and RS)
print("Input x1, y1, x2, y2, x3, y3, x4, y4:")

# Take user input for coordinates of the two line segments and convert them
to float

x1, y1, x2, y2, x3, y3, x4, y4 = map(float, input().split())

# Check if PQ and RS are parallel using the cross product of their direction
vectors

# The condition uses a small tolerance (1e-10) to handle floating-point


precision issues

print('PQ and RS are parallel.' if abs((x2 - x1)*(y4 - y3) - (x4 - x3)*(y2 - y1)) <
1e-10 else 'PQ and RS are not parallel')

44. Write a Python program to find the maximum sum of a contiguous


subsequence from a given sequence of numbers a1, a2, a3, ... an. A
subsequence of one element is also a continuous subsequence.
Input:
You can assume that 1 <= n <= 5000 and -100000 <= ai <= 100000.
Input numbers are separated by a space.
Input 0 to exit.
Input number of sequence of numbers you want to input (0 to exit):
3
Input numbers:
2
4
6
Maximum sum of the said contiguous subsequence: 12
Input number of sequence of numbers you want to input (0 to exit):
0

# Infinite loop to continuously receive input until the user enters 0

while True:

# Prompt the user to input the number of sequence of numbers (0 to exit)

print("Input number of sequence of numbers you want to input (0 to exit):")

# Take user input for the number of sequences

n = int(input())

# Break the loop if the user enters 0

if n == 0:

break

else:

# Initialize empty lists A and Sum to store input numbers and cumulative
sums

A = []

Sum = []
# Prompt the user to input numbers for the sequence

print("Input numbers:")

# Take user input for the sequence of numbers

for i in range(n):

A.append(int(input()))

# Calculate the cumulative sum of the sequence

Wa = 0

for i in range(0, n):

Wa += A[i]

Sum.append(Wa)

# Generate all possible contiguous subsequences and add them to the


Sum list

for i in range(0, n):

for j in range(0, i):

Num = Sum[i] - Sum[j]

Sum.append(Num)
# Print the maximum sum of the contiguous subsequence

print("Maximum sum of the said contiguous subsequence:")

print(max(Sum))

45. There are two circles C1 with radius r1, central coordinate (x1, y1) and C2
with radius r2 and central coordinate (x2, y2).

Write a Python program to test the followings -

● "C2 is in C1" if C2 is in C1
● "C1 is in C2" if C1 is in C2
● "Circumference of C1 and C2 intersect" if circumference of C1 and C2 intersect
● "C1 and C2 do not overlap" if C1 and C2 do not overlap and
● "Circumference of C1 and C2 will touch" if C1 and C2 touch

Input:

Input numbers (real numbers) are separated by a space.

Input x1, y1, r1, x2, y2, r2:

542392

C1 and C2 do not overlap

Input x1, y1, r1, x2, y2, r2:

5 4 3 5 10 3

Circumference of C1 and C2 will touch

Input x1, y1, r1, x2, y2, r2:

6 4 3 10 4 2

Circumference of C1 and C2 intersect


Input x1, y1, r1, x2, y2, r2:

543542

C2 is in C1

Input x1, y1, r1, x2, y2, r2:

542543

C1 is in C2

# Import the math module

import math

# Prompt the user to input x1, y1, r1, x2, y2, r2

print("Input x1, y1, r1, x2, y2, r2:")

# Take user input and convert it to floating-point numbers

x1, y1, r1, x2, y2, r2 = [float(i) for i in input().split()]

# Calculate the distance between the centers of the two circles

d = math.sqrt((x1 - x2)**2 + (y1 - y2)**2)

# Check and print the relationship between the two circles based on their radii and
distance
if d <= r1 - r2:

print("C2 is in C1")

elif d <= r2 - r1:

print("C1 is in C2")

elif d < r1 + r2:

print("Circumference of C1 and C2 intersect")

elif d == r1 + r2:

print("Circumference of C1 and C2 will touch")

else:

print("C1 and C2 do not overlap")

46. Write a Python program that reads a date (from 2016/1/1 to 2016/12/31)
and prints the day of the date. Jan. 1, 2016, is Friday. Note that 2016 is a leap
year.
Input:
Two integers m and d separated by a single space in a line, m ,d represent the month
and the day.
Input month and date (separated by a single space):
5 15
Name of the date: Sunday

# Import the 'date' class from the 'datetime' module

from datetime import date


# Prompt the user to input the month and date separated by a single space

print("Input month and date (separated by a single space):")

# Take user input for month and date, and convert them to integers

m, d = map(int, input().split())

# Define a dictionary mapping weekdays' numeric representation to their


names

weeks = {1: 'Monday', 2: 'Tuesday', 3: 'Wednesday', 4: 'Thursday', 5: 'Friday',


6: 'Saturday', 7: 'Sunday'}

# Calculate the ISO weekday for the given date using 'date.isoweekday'
method

w = date.isoweekday(date(2016, m, d))

# Print the name of the date based on the calculated weekday

print("Name of the date: ", weeks[w])

47. Write a Python program that reads text (only alphabetical characters and
spaces) and prints two words. The first word is the one that appears most
often in the text. The second one is the word with the most letters.
Note: A word is a sequence of letters which is separated by the spaces.

Input:

A text is given in a line with following condition:

a. The number of letters in the text is less than or equal to 1000.

b. The number of letters in a word is less than or equal to 32.

c. There is only one word which is arise most frequently in given text.

d. There is only one word which has the maximum number of letters in given text.

Input text: Thank you for your comment and your participation.

Output: your participation.

# Import the 'collections' module

import collections

# Prompt the user to input a text in a line

print("Input a text in a line.")

# Take user input, split it into a list of words, and convert each word to a string

text_list = list(map(str, input().split()))

# Use Counter to count the occurrences of each word in the text


sc = collections.Counter(text_list)

# Find the most common word in the text

common_word = sc.most_common()[0][0]

# Initialize an empty string to store the word with the maximum number of letters

max_char = ""

# Iterate through each word in the text

for s in text_list:

# Check if the length of the current word is greater than the length of 'max_char'

if len(max_char) < len(s):

max_char = s # Update 'max_char' with the current word

# Print the most frequent text and the word with the maximum number of letters

print("\nMost frequent text and the word which has the maximum number of letters.")

print(common_word, max_char)

48. Write a Python program that reads n digits (given) chosen from 0 to 9 and
prints the number of combinations where the sum of the digits equals another
given number (s). Do not use the same digits in a combination.
Input:
Two integers as number of combinations and their sum by a single space in a line.
Input 0 0 to exit.
Input number of combinations and sum, input 0 0 to exit:
56
24
00
2

# Import the 'itertools' module

import itertools

# Prompt the user to input the number of combinations and sum, input 0 0 to
exit

print("Input number of combinations and sum, input 0 0 to exit:")

# Infinite loop for continuous input until the user enters 0 0

while True:

# Take user input for the number of combinations and sum, and convert to
integers

x, y = map(int, input().split())

# Check if the user wants to exit the loop


if x == 0 and y == 0:

break

# Generate all combinations of 'x' elements from the range 0 to 9

s = list(itertools.combinations(range(10), x))

# Initialize a counter variable to count the valid combinations

ctr = 0

# Iterate through each combination

for i in s:

# Check if the sum of the current combination is equal to the target sum
'y'

if sum(i) == y:

ctr += 1

# Print the total count of valid combinations

print(ctr)

49. Write a Python program that reads the two adjoining sides and the diagonal of a
parallelogram and checks whether the parallelogram is a rectangle or a rhombus.
According to Wikipedia-
parallelograms: In Euclidean geometry, a parallelogram is a simple (non-self-
intersecting) quadrilateral with two pairs of parallel sides. The opposite or facing sides
of a parallelogram are of equal length and the opposite angles of a parallelogram are
of equal measure.
rectangles: In Euclidean plane geometry, a rectangle is a quadrilateral with four right
angles. It can also be defined as an equiangular quadrilateral, since equiangular means
that all of its angles are equal (360°/4 = 90°). It can also be defined as a parallelogram
containing a right angle.
rhombus: In plane Euclidean geometry, a rhombus (plural rhombi or rhombuses) is a
simple (non-self-intersecting) quadrilateral whose four sides all have the same length.
Another name is equilateral quadrilateral, since equilateral means that all of its sides
are equal in length. The rhombus is often called a diamond, after the diamonds suit in
playing cards which resembles the projection of an octahedral diamond, or a lozenge,
though the former sometimes refers specifically to a rhombus with a 60° angle, and
the latter sometimes refers specifically to a rhombus with a 45° angle.
Input:
Two adjoined sides and the diagonal.
1 <= ai, bi, ci <= 1000, ai + bi > ci
Input two adjoined sides and the diagonal of a parallelogram (comma separated):
3,4,5
This is a rectangle.

# Prompt the user to input two adjoined sides and the diagonal of a
parallelogram (comma separated)

print("Input two adjoined sides and the diagonal of a parallelogram (comma


separated):")
# Take user input for the sides and diagonal, and map to integers

a, b, c = map(int, input().split(","))

# Check if the parallelogram is a rectangle using the Pythagorean theorem

if c**2 == a**2 + b**2:

print("This is a rectangle.")

# Check if the parallelogram is a rhombus by comparing the lengths of the


adjoined sides

if a == b:

print("This is a rhombus.")

50. Write a Python program to replace a string " Python" with "Java" and
"Java" with "Python" in a given string.
Input:
English letters (including single byte alphanumeric characters, blanks, symbols) are
given on one line. The length of the input character string is 1000 or less.
Input a text with two words 'Python' and 'Java'
Python is popular than Java
Java is popular than Python

# Print statement to prompt the user to input a text with two words 'Python'
and 'Java'
print("Input a text with two words 'Python' and 'Java'")

# Split the input text into a list of words

text = input().split()

# Iterate through each word in the text

for i in range(len(text)):

# Check if 'Python' is present in the current word

if "Python" in text[i]:

# Find the index of 'Python' in the current word

n = text[i].index("Python")

# Replace 'Python' with 'Java' in the current word

text[i] = text[i][:n] + "Java" + text[i][n + 6:]

# Check if 'Java' is present in the current word

elif "Java" in text[i]:

# Find the index of 'Java' in the current word

n = text[i].index("Java")

# Replace 'Java' with 'Python' in the current word

text[i] = text[i][:n] + "Python" + text[i][n + 4:]


# Print the modified text with replaced words

print(*text)

51. Write a Python program that determines the difference between the
largest and smallest integers created by 8 numbers from 0 to 9. The number
that can be rearranged shall start with 0 as in 00135668.
Input:
Input an integer created by 8 numbers from 0 to 9.:
2345
Difference between the largest and the smallest integer from the given integer:
3087

# Print statement to prompt the user to input an integer created by 8 numbers


from 0 to 9

print("Input an integer created by 8 numbers from 0 to 9.:")

# Convert the input integer to a list of characters

num = list(input())

# Print statement to calculate and display the difference between the largest
and smallest integer from the given integer

print("Difference between the largest and the smallest integer from the given
integer:")
# Convert the list of characters to integers after sorting in ascending and
descending order

# Calculate the difference between the largest and smallest integers and print
the result

print(int("".join(sorted(num, reverse=True))) - int("".join(sorted(num))))

52. Write a Python program to compute the sum of the first n prime numbers.
Input:
n ( n <= 10000). Input 0 to exit the program.
Input a number (n<=10000) to compute the sum:(0 to exit)
25
Sum of first 25 prime numbers:
1060

# Set the maximum limit for prime number computation

MAX = 105000

# Print statement to prompt the user to input a number (n≤10000) to compute the sum
(0 to exit)

print("Input a number (n≤10000) to compute the sum:(0 to exit)")

# Boolean list to track prime numbers using the Sieve of Eratosthenes


algorithm
is_prime = [True for _ in range(MAX)]

is_prime[0] = is_prime[1] = False

# Iterate through the range to mark non-prime numbers

for i in range(2, int(MAX ** (1 / 2)) + 1):

if is_prime[i]:

for j in range(i ** 2, MAX, i):

is_prime[j] = False

# Create a list of prime numbers within the given range

primes = [i for i in range(MAX) if is_prime[i]]

# Infinite loop to continuously accept user input until 0 is entered

while True:

# Prompt the user to input a number

n = int(input())

# Check if the entered number is 0, and exit the loop if true

if not n:
break

# Print statement to display the sum of the first n prime numbers

print("Sum of first", n, "prime numbers:")

# Calculate and print the sum of the first n prime numbers using list slicing

print(sum(primes[:n]))

53. Write a Python program which accepts an even number (>=4, Goldbach
number) from the user and creates combinations which express the given number as a
sum of two prime numbers. Print the number of combinations.
Goldbach number: A Goldbach number is a positive even integer that can be
expressed as the sum of two odd primes.[4] Since four is the only even number greater
than two that requires the even prime 2 in order to be written as the sum of two
primes, another form of the statement of Goldbach's conjecture is that all even integers
greater than 4 are Goldbach numbers.
The expression of a given even number as a sum of two primes is called a Goldbach
partition of that number. The following are examples of Goldbach partitions for some
even numbers:
6=3+3
8=3+5
10 = 3 + 7 = 5 + 5
12 = 7 + 5
...
100 = 3 + 97 = 11 + 89 = 17 + 83 = 29 + 71 = 41 + 59 = 47 + 53
Input an even number (0 to exit):
100
Number of combinations:
6

# Import necessary modules

import sys

from bisect import bisect_right

from itertools import chain

# Print statement to prompt the user to input an even number (0 to exit)

print("Input an even number (0 to exit):")

# Set the upper bound for prime number computation

ub = 50000

# Initialize a boolean list to track prime numbers using the Sieve of


Eratosthenes algorithm

is_prime = [0, 0, 1, 1] + [0]*(ub-3)

is_prime[5::6] = is_prime[7::6] = [1]*int(ub/6)

# Initialize a list to store prime numbers


primes = [2, 3]

append = primes.append

# Sieve of Eratosthenes algorithm to find prime numbers

for n in chain(range(5, ub, 6), range(7, ub, 6)):

if is_prime[n]:

append(n)

is_prime[n*3::n*2] = [0]*((ub-n)//(n*2))

primes.sort()

# Infinite loop to continuously accept user input until 0 is entered

for n in map(int, sys.stdin):

# Check if the entered number is 0, and break the loop if true

if not n:

break

# Check if the number is odd

if n % 2:

# Print statement to display the number of combinations


print("Number of combinations:")

# Print the number of combinations using the count of is_prime[n-2]

print(is_prime[n-2])

else:

# Print statement to display the number of combinations

print("Number of combinations:")

# Print the number of combinations using the count of prime pairs that
sum to n

print(len([1 for p in primes[:bisect_right(primes, n/2)] if is_prime[n-p]]))

54. If you draw a straight line on a plane, the plane is divided into two regions.
For example, if you draw two straight lines in parallel, you get three areas, and
if you draw vertically one to the other you get 4 areas.
Write a Python program to create the maximum number of regions obtained
by drawing n given straight lines.
Input:
(1 <= n <= 10,000)
Input number of straight lines (o to exit):
5
Number of regions:
16

# Infinite loop to continuously prompt the user for input

while True:
# Print statement to prompt the user to input the number of straight lines (0
to exit)

print("Input number of straight lines (0 to exit): ")

# Take user input for the number of straight lines

n = int(input())

# Check if the entered number is less than or equal to 0, and break the loop
if true

if n <= 0:

break

# Print statement to display the number of regions

print("Number of regions:")

# Calculate and print the number of regions using the given formula

print((n*n + n + 2)//2)

55. There are four different points on a plane, P(xp,yp), Q(xq, yq), R(xr, yr) and
S(xs, ys). Write a Python program to determine whether AB and CD are
orthogonal.
Input:
xp,yp, xq, yq, xr, yr, xs and ys are -100 to 100 respectively and each value can be up to
5 digits after the decimal point It is given as a real number including the number of.
Output:
Output AB and CD are not orthogonal! or AB and CD are orthogonal!.

# Infinite loop to continuously prompt the user for input

while True:

try:

# Print statement to prompt the user to input coordinates of points xp, yp,
xq, yq, xr, yr, xs, ys

print("Input xp, yp, xq, yq, xr, yr, xs, ys:")

# Take user input for the coordinates of points and convert them to float

x_p, y_p, x_q, y_q, x_r, y_r, x_s, y_s = map(float, input().split())

# Calculate vectors pq and rs

pq_x, pq_y = x_q - x_p, y_q - y_p

rs_x, rs_y = x_s - x_r, y_s - y_r

# Calculate the dot product of pq and rs

rs = pq_x * rs_x + pq_y * rs_y


# Check if the dot product is close to zero, and print the result
accordingly

if abs(rs) > 1e-10:

print("AB and CD are not orthogonal!")

else:

print("AB and CD are orthogonal!")

# Exception handling to break out of the loop if an error occurs (e.g., invalid
input)

except:

break

56. Write a Python program to sum all numerical values (positive integers)
embedded in a sentence.
Input:
Sentences with positive integers are given over multiple lines. Each line is a character
string containing one-byte alphanumeric characters, symbols, spaces, or an empty line.
However the input is 80 characters or less per line and the sum is 10,000 or less.
Input some text and numeric values ( to exit):
Sum of the numeric values: 80
None
Input some text and numeric values ( to exit):
Sum of the numeric values: 17
None
Input some text and numeric values ( to exit):
Sum of the numeric values: 10
None

# Import sys and re modules

import sys

import re

# Define a function named 'test' that takes a string 'stri' as a parameter

def test(stri):

# Print statement to instruct the user to input text and numeric values
(terminate with )

print("Input some text and numeric values ( to exit):")

# Use regex to find all numeric values in the input string and sum them

numeric_sum = sum(map(int, re.findall(r"[0-9]{1,5}", stri)))

# Print the sum of the numeric values

print("Sum of the numeric values: ", numeric_sum)

# Test the 'test' function with different input strings


print(test("sd1fdsfs23 dssd56"))

print(test("15apple2banana"))

print(test("flowers5fruit5"))

57. There are 10 vertical and horizontal squares on a plane. Each square is
painted blue and green. Blue represents the sea, and green represents the
land. When two green squares are in contact with the top and bottom, or right
and left, they are said to be ground. The area created by only one green
square is called "island". For example, there are five islands in the figure
below.
Write a Python program to read the mass data and find the number of
islands.
Input:
Input 10 rows of 10 numbers representing green squares (island) as 1 and blue squares
(sea) as zeros
1100000111
1000000111
0000000111
0010001000
0000011100
0000111110
0001111111
1000111110
1100011100
1110001000
Number of islands:
5

# Initialize counter variable 'c' to 0

c=0

# Define a recursive function 'f' with parameters x, y, and z

def f(x, y, z):

# Check conditions for valid coordinates and if the square is part of the
island ('1')

if 0 <= y < 10 and 0 <= z < 10 and x[z][y] == '1':

# Change the square to '0' to mark it as visited

x[z][y] = '0'

# Recursively call 'f' for neighboring squares

for dy, dz in [[-1, 0], [1, 0], [0, -1], [0, 1]]:

f(x, y + dy, z + dz)

# Print a statement instructing the user to input 10 rows of 10 numbers


representing the island and sea

print("Input 10 rows of 10 numbers representing green squares (island) as 1


and blue squares (sea) as zeros")

# Run an infinite loop


while 1:

try:

# If 'c' is not 0, prompt the user to input (used for multiple test cases)

if c:

input()

except:

# Break the loop if an exception occurs (typically EOF)

break

# Read 10 rows of 10 characters each to represent the island and sea

x = [list(input()) for _ in [0] * 10]

# Set 'c' to 1 to indicate subsequent iterations

c=1

# Initialize counter 'b' to 0 to count the number of islands

b=0

# Nested loops to iterate through each square in the grid

for i in range(10):

for j in range(10):
# Check if the square is part of an island ('1')

if x[j][i] == '1':

# Increment the island counter 'b'

b += 1

# Call the recursive function 'f' to mark the connected island squares

f(x, i, j)

# Print the number of islands in the input grid

print("Number of islands:")

print(b)

58. When character are consecutive in a string , it is possible to shorten the


character string by replacing the character with a certain rule. For example, in
the case of the character string YYYYY, if it is expressed as # 5 Y, it is
compressed by one character.
Write a Python program to restore the original string by entering the
compressed string with this rule. However, the # character does not appear in
the restored character string.
Input:
The restored character string for each character on one line.
Original text: XY#6Z1#4023
XYZZZZZZ1000023
Original text: #39+1=1#30
999+1=1000

# Define a function 'restore_original_str' with parameter 'a1'

def restore_original_str(a1):

# Initialize an empty string 'result' to store the restored original text

result = ""

# Initialize index 'ind' to 0

ind = 0

# Set 'end' to the length of the input string 'a1'

end = len(a1)

# Start a while loop until 'ind' reaches the end of the input string

while ind < end:

# Check if the current character is '#' (indicating a pattern)

if a1[ind] == "#":

# Append the character at the next position repeated by the integer at


the position after that

result += a1[ind + 2] * int(a1[ind + 1])

# Move the index 'ind' to the position after the pattern

ind += 3

else:

# If not a pattern, append the current character


result += a1[ind]

# Move the index 'ind' to the next position

ind += 1

# Return the restored original text

return result

# Print a statement indicating the original text and the input string

print("Original text:", "XY#6Z1#4023")

# Call the 'restore_original_str' function with the input string and print the result

print(restore_original_str("XY#6Z1#4023"))

# Print another statement with a different input string

print("Original text:", "#39+1=1#30")

# Call the 'restore_original_str' function with the second input string and print
the result

print(restore_original_str("#39+1=1#30"))

59. A convex polygon is a simple polygon in which no line segment between


two points on the boundary ever goes outside the polygon. Equivalently, it is a
simple polygon whose interior is a convex set. In a convex polygon, all interior
angles are less than or equal to 180 degrees, while in a strictly convex
polygon all interior angles are strictly less than 180 degrees.
Write a Python program that compute the area of the polygon . The vertices
have the names vertex 1, vertex 2, vertex 3, ... vertex n according to the order
of edge connections
Note: The original sentences are uppercase letters, lowercase letters,
numbers, symbols, less than 100 letters, and consecutive letters are not more
than 9 letters.
Input:
Input number of sides: 5
Side: 1
Input the Coordinate:
Input Coordinate x: 1
Input Coordinate y: 0
Side: 2
Input the Coordinate:
Input Coordinate x: 0
Input Coordinate y: 0
Side: 3
Input the Coordinate:
Input Coordinate x: 1
Input Coordinate y: 1
Side: 4
Input the Coordinate:
Input Coordinate x: 2
Input Coordinate y: 0
Side: 5
Input the Coordinate:
Input Coordinate x: -1
Input Coordinate y: 1
Area of the Polygon: 0.5

# Define a function 'poly_area' to calculate the area of a polygon

def poly_area(c):

# Initialize an empty list 'add' to store intermediate values

add = []

# Use a loop to iterate through the coordinates

for i in range(0, (len(c) - 2), 2):

# Calculate and append the cross product of consecutive coordinate


pairs

add.append(c[i] * c[i + 3] - c[i + 1] * c[i + 2])

# Calculate and append the cross product of the last and first coordinate
pairs

add.append(c[len(c) - 2] * c[1] - c[len(c) - 1] * c[0])

# Return the absolute value of half of the sum of all cross products

return abs(sum(add) / 2)

# Prompt the user to input the number of sides of the polygon


no_sides = int(input('Input number of sides: '))

# Initialize an empty list 'cord_data' to store coordinates

cord_data = []

# Use a loop to input coordinates for each side of the polygon

for z in range(no_sides):

print("Side:", z+1)

print("Input the Coordinate:")

# Input x-coordinate

x = int(input('Input Coordinate x:'))

# Input y-coordinate

y = int(input('Input Coordinate y:'))

# Append the coordinates to 'cord_data'

cord_data.append(x)

cord_data.append(y)

# Print the area of the polygon using the 'poly_area' function

print("\nArea of the Polygon:", poly_area(cord_data))

60. Internet search engine giant, such as Google accepts web pages around
the world and classify them, creating a huge database. The search engines
also analyze the search keywords entered by the user and create inquiries for
database search. In both cases, complicated processing is carried out in order
to realize efficient retrieval, but basics are all cutting out words from
sentences.
Write a Python program to cut out words of 3 to 6 characters length from a
given sentence not more than 1024 characters.
Input:
English sentences consisting of delimiters and alphanumeric characters are given on
one line.
Input a sentence (1024 characters. max.)
The quick brown fox
3 to 6 characters length of words:
The quick brown fox

# Print statement to prompt the user to input a sentence (1024 characters


max.)

print("Input a sentence (1024 characters max.)")

# Input a sentence and store it in the variable 'yy'

yy = input()

# Replace commas and periods with spaces in the input sentence

yy = yy.replace(",", " ")

yy = yy.replace(".", " ")


# Print statement to display words with lengths between 3 and 6 characters

print("3 to 6 characters length of words:")

# Print the words with lengths between 3 and 6 characters using list
comprehension

print(*[y for y in yy.split() if 3 <= len(y) <= 6])

61. Arrange integers (0 to 99) as narrow hilltop, as illustrated in Figure 1.


Reading such data representing huge, when starting from the top and
proceeding according to the next rule to the bottom. Write a Python program
that compute the maximum value of the sum of the passing integers.
Input:
A series of integers separated by commas are given in diamonds. No spaces are
included in each line. The input example corresponds to Figure 1. The number of lines
of data is less than 100 lines.
Output:
The maximum value of the sum of integers passing according to the rule on one line.
Input the numbers (ctrl+d to exit):
8
4, 9
9, 2, 1
3, 8, 5, 5
5, 6, 3, 7, 6
3, 8, 5, 5
9, 2, 1
4, 9
8
Maximum value of the sum of integers passing according to the rule on one line.
64

# Import the sys module for reading input

import sys

# Print statement to instruct the user to input numbers (ctrl+d to exit)

print("Input the numbers (ctrl+d to exit):")

# Read lines from the standard input and create a list of lists of integers

nums = [list(map(int, l.split(","))) for l in sys.stdin]

# Initialize the maximum value vector with the first row of input

mvv = nums[0]

# Iterate over the remaining rows in a pyramid fashion to find the maximum
path sum

for i in range(1, (len(nums) + 1) // 2):

rvv = [0] * (i + 1)

for j in range(i):
rvv[j] = max(rvv[j], mvv[j] + nums[i][j])

rvv[j + 1] = max(rvv[j + 1], mvv[j] + nums[i][j + 1])

mvv = rvv

# Continue iterating over the remaining rows in a reversed pyramid fashion

for i in range((len(nums) + 1) // 2, len(nums)):

rvv = [0] * (len(mvv) - 1)

for j in range(len(rvv)):

rvv[j] = max(mvv[j], mvv[j + 1]) + nums[i][j]

mvv = rvv

# Print the maximum value of the sum of integers passing according to the
rule

print("Maximum value of the sum of integers passing according to the rule on


one line.")

print(mvv[0])

62. Write a Python program to find the number of combinations that satisfy p + q +
r + s = n where n is a given number <= 4000 and p, q, r, s are between 0 to 1000.
Input a positive integer: (ctrl+d to exit)
252
Number of combinations of a,b,c,d: 2731135

# Import the Counter class from the collections module

from collections import Counter

# Print statement to instruct the user to input a positive integer (ctrl+d to exit)

print("Input a positive integer: (ctrl+d to exit)")

# Create a Counter object to store pairs of integers and their counts

pair_dict = Counter()

# Assign counts to pairs of integers based on their minimum and maximum


values

for i in range(2001):

pair_dict[i] = min(i, 2000 - i) + 1

# Continuous loop to read input until EOFError (ctrl+d) is encountered

while True:

try:

# Read a positive integer from the user

n = int(input())
# Initialize a variable to store the number of combinations

ans = 0

# Iterate over possible values of 'i' and calculate combinations

for i in range(n + 1):

ans += pair_dict[i] * pair_dict[n - i]

# Print the number of combinations of a, b, c, d

print("Number of combinations of a, b, c, d:", ans)

# Break the loop when EOFError is encountered

except EOFError:

break

63. Write a Python program that adds up the columns and rows of the given table as
shown in the specified figure.
Input number of rows/columns (0 to exit)
4
Input cell value:
25 69 51 26
68 35 29 54
54 57 45 63
61 68 47 59
Result:
25 69 51 26 171
68 35 29 54 186
54 57 45 63 219
61 68 47 59 235
208 229 172 202 811
Input number of rows/columns (0 to exit)

# Continuous loop to execute the program until the user chooses to exit (input
0)

while True:

# Print statement to instruct the user to input the number of rows/columns


(0 to exit)

print("Input number of rows/columns (0 to exit)")

# Read the input for the number of rows/columns

n = int(input())

# Check if the user wants to exit the program

if n == 0:

break

# Print statement to instruct the user to input cell values


print("Input cell value:")

# Initialize an empty list to store the matrix

x = []

# Loop to input the matrix values

for i in range(n):

x.append([int(num) for num in input().split()])

# Loop to calculate and append the row sums to each row

for i in range(n):

sum = 0

for j in range(n):

sum += x[i][j]

x[i].append(sum)

# Append an empty list to represent the additional row for column sums

x.append([])

# Loop to calculate and append the column sums to the additional row
for i in range(n + 1):

sum = 0

for j in range(n):

sum += x[j][i]

x[n].append(sum)

# Print statement to display the result

print("Result:")

# Loop to print the matrix with row and column sums

for i in range(n + 1):

for j in range(n + 1):

print('{0:>5}'.format(x[i][j]), end="")

print()

64. Given a list of numbers and a number k, write a Python program to check
whether the sum of any two numbers from the list is equal to k or not.
For example, given [1, 5, 11, 5] and k = 16, return true since 11 + 5 is 16.
Sample Input:
([12, 5, 0, 5], 10)
([20, 20, 4, 5], 40)
([1, -1], 0)
([1, 1, 0], 0)
Sample Output:
True
True
True
False

# Function to check if there exists a pair in the list whose sum is equal to the
given value 'k'

def check_sum(nums, k):

# Loop through each element in the list

for i in range(len(nums)):

# Nested loop to compare each element with subsequent elements

for j in range(i+1, len(nums)):

# Check if the sum of the current pair is equal to 'k'

if nums[i] + nums[j] == k:

return True # Return True if such a pair is found

return False # Return False if no such pair is found

# Test cases

print(check_sum([12, 5, 0, 5], 10))

print(check_sum([20, 20, 4, 5], 40))


print(check_sum([1, -1], 0))

print(check_sum([1, 1, 0], 0))

65. In mathematics, a subsequence is a sequence that can be derived from


another sequence by deleting some or no elements without changing the
order of the remaining elements. For example, the sequence (A,B,D) is a
subsequence of (A,B,C,D,E,F) obtained after removal of elements C, E, and
F. The relation of one sequence being the subsequence of another is a
preorder.
The subsequence should not be confused with substring (A,B,C,D) which can
be derived from the above string (A,B,C,D,E,F) by deleting substring (E,F).
The substring is a refinement of the subsequence.
The list of all subsequences for the word "apple" would be "a", "ap", "al", "ae",
"app", "apl", "ape", "ale", "appl", "appe", "aple", "apple", "p", "pp", "pl", "pe",
"ppl", "ppe", "ple", "pple", "l", "le", "e", "".
Write a Python program to find the longest word in a set of words which is a
subsequence of a given string.
Sample Input:
("Green", {"Gn", "Gren", "ree", "en"})
("pythonexercises", {" py", "ex", "exercises"})
Sample Output:
Gren
exercises

# Function to find the longest word sequence from a set of words in a given
string

def longest_word_sequence(s, d):


long_word = "" # Variable to store the longest word sequence

for word in d: # Iterate through each word in the set

temp_word = '' # Variable to store the current word sequence

j = 0 # Index to track the position in the string 's'

for letter in word: # Iterate through each letter in the current word

for i in range(j, len(s)): # Iterate through the string 's' starting from
index 'j'

if letter == s[i]: # If the letter is found in the string

temp_word += letter # Add the letter to the current word


sequence

j = i # Update the index to the position of the found letter

break

else:

continue # Continue searching for the letter if not found in the


current position

# Check if the current word sequence is equal to the word and longer
than the current longest word

if temp_word == word and len(long_word) < len(temp_word):


long_word = temp_word # Update the longest word sequence

return long_word # Return the longest word sequence found

# Test cases

print(longest_word_sequence("Green", {"Gn", "Gren", "ree", "en"}))

print(longest_word_sequence("pythonexercises", {"py", "ex", "exercises"}))

66. From Wikipedia, the free encyclopaedia:


A happy number is defined by the following process:
Starting with any positive integer, replace the number by the sum of the
squares of its digits, and repeat the process until the number equals 1 (where
it will stay), or it loops endlessly in a cycle which does not include 1. Those
numbers for which this process ends in 1 are happy numbers, while those that
do not end in 1 are unhappy numbers.
Write a Python program to check whether a number is "happy" or not.
Sample Input:
(7)
(932)
(6)
Sample Output:
True
True
False

# Function to check if a number is a Happy Number


def is_Happy_num(n):

past = set() # Set to store previously encountered numbers during the


process

while n != 1: # Continue the process until the number becomes 1 (a Happy


Number) or a cycle is detected

n = sum(int(i) ** 2 for i in str(n)) # Calculate the sum of squares of each


digit in the number

if n in past: # If the current number has been encountered before, it


forms a cycle

return False # The number is not a Happy Number

past.add(n) # Add the current number to the set of past numbers

return True # If the process reaches 1, the number is a Happy Number

# Test cases

print(is_Happy_num(7))

print(is_Happy_num(932))

print(is_Happy_num(6))

67. From Wikipedia,


A happy number is defined by the following process:
Starting with any positive integer, replace the number by the sum of the
squares of its digits, and repeat the process until the number equals 1 (where
it will stay), or it loops endlessly in a cycle which does not include 1. Those
numbers for which this process ends in 1 are happy numbers, while those that
do not end in 1 are unhappy numbers.
Write a Python program to find and print the first 10 happy numbers.
Sample Input:
[:10]
Sample Output:
[1, 7, 10, 13, 19, 23, 28, 31, 32, 44]

# Function to check if a number is a Happy Number

def happy_numbers(n):

past = set() # Set to store previously encountered numbers during the


process

while n != 1: # Continue the process until the number becomes 1 (a Happy


Number) or a cycle is detected

n = sum(int(i) ** 2 for i in str(n)) # Calculate the sum of squares of each


digit in the number

if n in past: # If the current number has been encountered before, it


forms a cycle

return False # The number is not a Happy Number

past.add(n) # Add the current number to the set of past numbers

return True # If the process reaches 1, the number is a Happy Number

# Print the first 10 Happy Numbers less than 500


print([x for x in range(500) if happy_numbers(x)][:10])

68. Write a Python program that counts the number of prime numbers that are less
than a given non-negative number.
Sample Input:
(10)
(100)
Sample Output:
4
25

# Function to count prime numbers up to a given limit 'n'

def count_Primes_nums(n):

ctr = 0 # Counter to store the number of prime numbers

# Iterate through numbers up to 'n'

for num in range(n):

if num <= 1: # Numbers less than or equal to 1 are not prime, so skip
them

continue

# Check for factors in the range from 2 to num-1

for i in range(2, num):


if (num % i) == 0: # If num is divisible by i, it's not prime

break

else:

ctr += 1 # If no factors are found, increment the counter (num is


prime)

return ctr # Return the count of prime numbers

# Print the count of prime numbers up to 10 and 100

print(count_Primes_nums(10))

print(count_Primes_nums(100))

69. In abstract algebra, a group isomorphism is a function between two groups


that sets up a one-to-one correspondence between the elements of the
groups in a way that respects the given group operations. If there exists an
isomorphism between two groups, then the groups are called isomorphic.
Two strings are isomorphic if the characters in string A can be replaced to get
string B
Given "foo", "bar", return false.
Given "paper", "title", return true.
Write a Python program to check if two given strings are isomorphic to each other
or not.
Sample Input:
("foo", "bar")
("bar", "foo")
("paper", "title")
("title", "paper")
("apple", "orange")
("aa", "ab")
("ab", "aa")
Sample Output:
False
False
True
True
False
False
False

# Function to check if two strings are isomorphic

def isIsomorphic(str1, str2):

dict_str1 = {} # Dictionary to store mapping for characters in str1

dict_str2 = {} # Dictionary to store mapping for characters in str2

# Enumerate through characters in str1 and store their positions in the


dictionary

for i, value in enumerate(str1):

dict_str1[value] = dict_str1.get(value, []) + [i]


# Enumerate through characters in str2 and store their positions in the
dictionary

for j, value in enumerate(str2):

dict_str2[value] = dict_str2.get(value, []) + [j]

# Check if the values (positions) in the dictionaries are the same after
sorting

if sorted(dict_str1.values()) == sorted(dict_str2.values()):

return True

else:

return False

# Test cases

print(isIsomorphic("foo", "bar"))

print(isIsomorphic("bar", "foo"))

print(isIsomorphic("paper", "title"))

print(isIsomorphic("title", "paper"))

print(isIsomorphic("apple", "orange"))

print(isIsomorphic("aa", "ab"))

print(isIsomorphic("ab", "aa"))
70. Write a Python program to find the longest common prefix string among a given
array of strings. Return false if there is no common prefix.
For Example, longest common prefix of "abcdefgh" and "abcefgh" is "abc".
Sample Input:
["abcdefgh","abcefgh"]
["w3r","w3resource"]
["Python","PHP", "Perl"]
["Python","PHP", "Java"]
Sample Output:
abc
w3r
P

# Function to find the longest common prefix among a list of strings

def longest_Common_Prefix(str1):

if not str1: # Check if the list is empty

return ""

short_str = min(str1, key=len) # Find the shortest string in the list

for i, char in enumerate(short_str): # Iterate through characters in the


shortest string

for other in str1: # Iterate through other strings in the list


if other[i] != char: # Check if the corresponding characters don't match

return short_str[:i] # Return the common prefix found so far

return short_str # Return the entire shortest string if it is a common prefix

# Test cases

print(longest_Common_Prefix(["abcdefgh", "abcefgh"])) # "abc"

print(longest_Common_Prefix(["w3r", "w3resource"])) # "w3r"

print(longest_Common_Prefix(["Python", "PHP", "Perl"])) # ""

print(longest_Common_Prefix(["Python", "PHP", "Java"])) # ""

71. Write a Python program to reverse only the vowels of a given string.
Sample Input:
("w3resource")
(" Python")
("Perl")
("USA")
Sample Output:
w3resuorce
Python
Perl
ASU

# Function to reverse the order of vowels in a string


def reverse_vowels(str1):

vowels = "" # Variable to store vowels in their original order

for char in str1:

if char in "aeiouAEIOU": # Check if the character is a vowel

vowels += char # Append the vowel to the vowels variable

result_string = "" # Variable to store the result string with reversed vowels

for char in str1:

if char in "aeiouAEIOU": # Check if the character is a vowel

result_string += vowels[-1] # Append the last vowel from the vowels


variable

vowels = vowels[:-1] # Remove the last vowel from the vowels


variable

else:

result_string += char # Append non-vowel characters as they are

return result_string

# Test cases

print(reverse_vowels("w3resource"))

print(reverse_vowels("Python"))

print(reverse_vowels("Perl"))
print(reverse_vowels("USA"))

72. Write a Python program to check whether a given integer is a palindrome or not.
Note: An integer is a palindrome when it reads the same backward as forward.
Negative numbers are not palindromic.
Sample Input:
(100)
(252)
(-838)
Sample Output:
False
True
False

# Define a function to check if a number is a palindrome

def is_Palindrome(n):

return str(n) == str(n)[::-1]

# Test cases

print(is_Palindrome(100)) # False

print(is_Palindrome(252)) # True

print(is_Palindrome(-838)) # False

73. Write a Python program that removes duplicate elements from a given array of
numbers so that each element appears only once and returns the new length of the
array.
Sample Input:
[0,0,1,1,2,2,3,3,4,4,4]
[1, 2, 2, 3, 4, 4]
Sample Output:
5
4

# Define a function to remove duplicates from a sorted list

def remove_duplicates(nums):

# Iterate through the list in reverse order

for i in range(len(nums)-1, 0, -1):

# Check if the current element is equal to the previous one

if nums[i] == nums[i-1]:

# If equal, delete the previous element to remove the duplicate

del nums[i-1]

# Return the length of the modified list

return len(nums)

# Test the function with two different lists and print the results

print(remove_duplicates([0,0,1,1,2,2,3,3,4,4,4])) # [0, 1, 2, 3, 4], Length: 5

print(remove_duplicates([1, 2, 2, 3, 4, 4])) # [1, 2, 3, 4], Length: 4


74. Write a Python program to calculate the maximum profit from selling and
buying values of stock. An array of numbers represent the stock prices in
chronological order.
For example, given [8, 10, 7, 5, 7, 15], the function will return 10, since the buying
value of the stock is 5 dollars and sell value is 15 dollars.
Sample Input:
([8, 10, 7, 5, 7, 15])
([1, 2, 8, 1])
([])
Sample Output:
10
7
0

# Define a function to calculate the maximum profit from buying and selling
stocks

def buy_and_sell(stock_price):

# Initialize variables to store the maximum profit and current maximum


value

max_profit_val, current_max_val = 0, 0

# Iterate through the reversed stock prices

for price in reversed(stock_price):

# Update the current maximum value with the maximum of the current
value and the previous maximum
current_max_val = max(current_max_val, price)

# Calculate the potential profit by subtracting the current price from the
current maximum value

potential_profit = current_max_val - price

# Update the maximum profit with the maximum of the potential profit and
the previous maximum profit

max_profit_val = max(potential_profit, max_profit_val)

# Return the maximum profit

return max_profit_val

# Test the function with different stock price lists and print the results

print(buy_and_sell([8, 10, 7, 5, 7, 15])) # Maximum Profit: 10

print(buy_and_sell([1, 2, 8, 1])) # Maximum Profit: 7

print(buy_and_sell([])) # Maximum Profit: 0

75. Write a Python program to remove all instances of a given value from a given
array of integers and find the length of the newly created array.
Sample Input:
([1, 2, 3, 4, 5, 6, 7, 5], 5)
([10,10,10,10,10], 10)
([10,10,10,10,10], 20)
([], 1)
Sample Output:
6
0
5
0

# Define a function to remove elements equal to a given value from a list

def remove_element(array_nums, val):

# Initialize a variable to iterate through the list

i=0

# Iterate through the list

while i < len(array_nums):

# Check if the current element is equal to the given value

if array_nums[i] == val:

# Remove the element if it matches the given value

array_nums.remove(array_nums[i])

else:

# Move to the next index if the elements do not match


i += 1

# Return the length of the modified list

return len(array_nums)

# Test the function with different lists and values, and print the results

print(remove_element([1, 2, 3, 4, 5, 6, 7, 5], 5))

print(remove_element([10, 10, 10, 10, 10], 10))

print(remove_element([10, 10, 10, 10, 10], 20))

print(remove_element([], 1))

You might also like