ÔN TẬP FINAL NGÔN NGỮ LẬP TRÌNH
ÔN TẬP FINAL NGÔN NGỮ LẬP TRÌNH
ÔN TẬP FINAL NGÔN NGỮ LẬP TRÌNH
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 random
random.shuffle(char_list)
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
len_list = len(int_list)
# Calculate the new index based on the starting position and current
index.
print(int_list.pop(idx))
len_list -= 1
nums = [10, 20, 30, 40, 50, 60, 70, 80, 90]
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):
result = []
nums.sort()
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.
l += 1
r -= 1
l += 1
r -= 1
# Return the final result containing unique triplets.
return result
# Call the 'three_sum' function with the list and print the result.
print(three_sum(x))
numbers = []
# 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.
Europe and Latin America, as well as Africa (Liberia) and Oceania (New
Zealand) during the first half of the
19th century.'''
word_list = string_words.split()
print("String:\n {} \n".format(string_words))
print("List:\n {} \n".format(str(word_list)))
# Open the file in read mode using a 'with' statement to ensure proper
handling of resources.
# 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(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
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.
# 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.
print(news.title.text)
print(news.link.text)
print(news.pubDate.text)
print("-" * 60)
import pkg_resources
installed_packages = pkg_resources.working_set
# Create a sorted list of strings representing installed packages and their
versions.
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
os_profile = [
'architecture',
'linux_distribution',
'mac_ver',
'machine',
'node',
'platform',
'processor',
'python_build',
'python_compiler',
'python_version',
'release',
'system',
'uname',
'version',
if hasattr(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
T = 70
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.
result = set()
for s in sums:
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):
result_perms = [[]]
for n in nums:
new_perms = []
for i in range(len(perm)+1):
result_perms = new_perms
return result_perms
my_nums = [1, 2, 3]
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):
if digits == "":
return []
string_maps = {
"1": "abc",
"2": "def",
"3": "ghi",
"4": "jkl",
"5": "mno",
"6": "pqrs",
"7": "tuv",
"8": "wxy",
"9": "z"
result = [""]
temp = []
for an in result:
temp.append(an + char)
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.
while b != 0:
data = a & b
# XOR 'a' and 'b' to get the sum without considering carry.
a=a^b
b = data << 1
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.
import re
__operators__ = "+-/*"
__parenthesis__ = "()"
__priority__ = {
'+': 0,
'-': 0,
'*': 1,
'/': 1,
# 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.
if opposite_side == str("x"):
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']
def gen_strobogrammatic(n):
"""
:type n: int
:rtype: List[str]
"""
result = helper(n, n)
return result
if n == 0:
return [""]
# Base case: when 'n' is 1, return the strobogrammatic digits for length 1.
if n == 1:
result = []
# If 'n' is not equal to the original length, add "0" on both sides.
if n != length:
# Add strobogrammatic numbers with "9" in the first half and "6" in the
second half.
# Add strobogrammatic numbers with "6" in the first half and "9" in the
second half.
return result
# Test the function with different values of 'n' and print the results.
18. Write a Python program to find the median among three given numbers.
# Input the first number from the user
# Print a message indicating that the program will calculate the median
print(x)
print(x)
print(y)
print(y)
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):
while ans:
if str(tempn) in num:
i += 1 # Increment 'i'.
else:
# 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
def factendzero(n):
x = n // 5
y=x
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):
x=0
# Iterate over each denomination in the list.
for i in range(6):
if a > 0:
# 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.
# 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):
n_str = str(n)
while n > 0:
n_str = list(str(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.
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):
# Find the symmetric difference between the set of all_nums and the set 'n'.
n = n.symmetric_difference(all_nums)
n = sorted(n)
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
⇒
def sum_distinct_pairs(arr):
result = 0
i=0
i += 1
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.
⇒
def ap_gp_sequence(arr):
return "Wrong Numbers" # If all three are zero, it's not a valid sequence.
else:
n = 2 * arr[2] - arr[1]
return "AP sequence, " + 'Next number of the sequence: ' + str(n)
else:
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
⇒
# Calculate the length of the series using the formula for the sum of an
arithmetic 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("Series:")
a += d
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
i += 1
return gcd
# Calculate the greatest common divisor (GCD) using the ngcd function
n = ngcd(x, y)
result = 0
i=1
if(n % i == 0):
i += 1
return result
# Test cases
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.
⇒
def rev_number(n):
while True:
else:
# Test cases
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.
ctr = 0
# Check if both numbers are zero, in which case there are no carry
operations.
if x == 0 and y == 0:
return 0
z=0
for i in reversed(range(10)):
z = x % 10 + y % 10 + z
if z > 9:
else:
z = 0 # Reset the carry digit to 0.
ctr += z
# Move to the next digit by removing the last digit of each number.
x //= 10
y //= 10
if ctr == 0:
elif ctr == 1:
else:
# Test cases
# Print statement to prompt the user to input the heights of eight buildings
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
⇒
# 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
# 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)
else:
# 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())
n=a*e-b*d
if n != 0:
x = (c * e - b * f) / n
y = (a * f - c * d) / n
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
⇒
def round_n(n):
if n % 1000:
else:
return n
def compute_debt(n):
if n == 0:
return 100000
# Calling the compute_debt function with user input, calculating the debt
amount, and printing the result
result = compute_debt(int(input()))
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'
n = int(input())
result = 0
# Iterate over all combinations of (i, j, k) where i, j, k are in the range [0, 9]
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
⇒
if primes[i // 2]:
n = int(input())
# Check and print the number of primes less than or equal to 'n'
if n < 4:
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
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
ar = a**0.5
br = b**0.5
cr = c**0.5
print("{:>.3f}".format(r))
print("{:>.3f}".format(px), "{:>.3f}".format(py))
# 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
# Calculate the cross products (c1, c2, c3) for the point relative to each edge
of the triangle
# 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):
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
⇒
x = int(input())
y = int(input())
# Check if any of the integers or their sum exceeds 10^80
else:
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
⇒
# Take user input, split it into a list of integers, and assign it to the variable
'nums'
nums = list(map(int, input().split()))
nums.sort()
nums.reverse()
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
# Check if PQ and RS are parallel using the cross product of their direction
vectors
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')
while True:
n = int(input())
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:")
for i in range(n):
A.append(int(input()))
Wa = 0
Wa += A[i]
Sum.append(Wa)
Sum.append(Num)
# Print the maximum sum of the 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).
● "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:
542392
5 4 3 5 10 3
6 4 3 10 4 2
543542
C2 is in C1
542543
C1 is in C2
import math
# Check and print the relationship between the two circles based on their radii and
distance
if d <= r1 - r2:
print("C2 is in C1")
print("C1 is in C2")
elif d == r1 + r2:
else:
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
⇒
# Take user input for month and date, and convert them to integers
m, d = map(int, input().split())
# Calculate the ISO weekday for the given date using 'date.isoweekday'
method
w = date.isoweekday(date(2016, m, d))
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:
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.
import collections
# Take user input, split it into a list of words, and convert each word to a string
common_word = sc.most_common()[0][0]
# Initialize an empty string to store the word with the maximum number of letters
max_char = ""
for s in text_list:
# Check if the length of the current word is greater than the length of 'max_char'
# 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 itertools
# Prompt the user to input the number of combinations and sum, input 0 0 to
exit
while True:
# Take user input for the number of combinations and sum, and convert to
integers
x, y = map(int, input().split())
break
s = list(itertools.combinations(range(10), x))
ctr = 0
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(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)
a, b, c = map(int, input().split(","))
print("This is a rectangle.")
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'")
text = input().split()
for i in range(len(text)):
if "Python" in text[i]:
n = text[i].index("Python")
n = text[i].index("Java")
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
⇒
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
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
⇒
MAX = 105000
# Print statement to prompt the user to input a number (n≤10000) to compute the sum
(0 to exit)
if is_prime[i]:
is_prime[j] = False
while True:
n = int(input())
if not n:
break
# 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 sys
ub = 50000
append = primes.append
if is_prime[n]:
append(n)
is_prime[n*3::n*2] = [0]*((ub-n)//(n*2))
primes.sort()
if not n:
break
if n % 2:
print(is_prime[n-2])
else:
print("Number of combinations:")
# Print the number of combinations using the count of prime pairs that
sum to n
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
⇒
while True:
# Print statement to prompt the user to input the number of straight lines (0
to exit)
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("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!.
⇒
while True:
try:
# Print statement to prompt the user to input coordinates of points 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())
else:
# 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
import re
def test(stri):
# Print statement to instruct the user to input text and numeric values
(terminate with )
# Use regex to find all numeric values in the input string and sum them
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
# Check conditions for valid coordinates and if the square is part of the
island ('1')
x[z][y] = '0'
for dy, dz in [[-1, 0], [1, 0], [0, -1], [0, 1]]:
try:
# If 'c' is not 0, prompt the user to input (used for multiple test cases)
if c:
input()
except:
break
c=1
b=0
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':
b += 1
# Call the recursive function 'f' to mark the connected island squares
f(x, i, j)
print("Number of islands:")
print(b)
def restore_original_str(a1):
result = ""
ind = 0
end = len(a1)
# Start a while loop until 'ind' reaches the end of the input string
if a1[ind] == "#":
ind += 3
else:
ind += 1
return result
# Print a statement indicating the original text and the input string
# Call the 'restore_original_str' function with the input string and print the result
print(restore_original_str("XY#6Z1#4023"))
# Call the 'restore_original_str' function with the second input string and print
the result
print(restore_original_str("#39+1=1#30"))
def poly_area(c):
add = []
# Calculate and append the cross product of the last and first coordinate
pairs
# Return the absolute value of half of the sum of all cross products
return abs(sum(add) / 2)
cord_data = []
for z in range(no_sides):
print("Side:", z+1)
# Input x-coordinate
# Input y-coordinate
cord_data.append(x)
cord_data.append(y)
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
⇒
yy = input()
# Print the words with lengths between 3 and 6 characters using list
comprehension
import sys
# Read lines from the standard input and create a list of lists of integers
# 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
rvv = [0] * (i + 1)
for j in range(i):
rvv[j] = max(rvv[j], mvv[j] + nums[i][j])
mvv = rvv
for j in range(len(rvv)):
mvv = rvv
# Print the maximum value of the sum of integers passing according to the
rule
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
# Print statement to instruct the user to input a positive integer (ctrl+d to exit)
pair_dict = Counter()
for i in range(2001):
while True:
try:
n = int(input())
# Initialize a variable to store the number of combinations
ans = 0
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:
n = int(input())
if n == 0:
break
x = []
for i in range(n):
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("Result:")
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'
for i in range(len(nums)):
if nums[i] + nums[j] == k:
# Test cases
# Function to find the longest word sequence from a set of words in a given
string
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'
break
else:
# Check if the current word sequence is equal to the word and longer
than the current longest word
# Test cases
# Test cases
print(is_Happy_num(7))
print(is_Happy_num(932))
print(is_Happy_num(6))
def happy_numbers(n):
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
⇒
def count_Primes_nums(n):
if num <= 1: # Numbers less than or equal to 1 are not prime, so skip
them
continue
break
else:
print(count_Primes_nums(10))
print(count_Primes_nums(100))
# 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
⇒
def longest_Common_Prefix(str1):
return ""
# Test cases
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
⇒
result_string = "" # Variable to store the result string with reversed vowels
else:
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
⇒
def is_Palindrome(n):
# 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
⇒
def remove_duplicates(nums):
if nums[i] == nums[i-1]:
del nums[i-1]
return len(nums)
# Test the function with two different lists and print the results
# Define a function to calculate the maximum profit from buying and selling
stocks
def buy_and_sell(stock_price):
max_profit_val, current_max_val = 0, 0
# 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
# Update the maximum profit with the maximum of the potential profit and
the previous maximum profit
return max_profit_val
# Test the function with different stock price lists and print the results
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
⇒
i=0
if array_nums[i] == val:
array_nums.remove(array_nums[i])
else:
return len(array_nums)
# Test the function with different lists and values, and print the results
print(remove_element([], 1))