Lci2022028 Lab
Lci2022028 Lab
Adavanced
Programming Language
(April 16, 2024)
SOLUTION:
def spiral_print(matrix):
if not matrix:
return
top = 0
bottom = len(matrix) - 1
left = 0
right = len(matrix[0]) - 1
direction = 0
# Example usage:
matrix = [
[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12],
[13, 14, 15, 16]
]
spiral_print(matrix)
OUTPUT:
Problem 2: Given a number n, find the smallest number that has same set
of digits as n and is greater than n.
If n is the greatest possible number with its set of digits, then print “not
possible”.
Example –
Input: n = "218765"
Output: "251678"
Input: n = "1234"
Output: "1243"
Input: n = "4321"
Output: "Not Possible"
Input: n = "534976"
Output: "536479"
SOLUTION:
def next_permutation(n):
# Convert the number to a list of digits
digits = list(n)
# Find the first digit from the right which is smaller than the digit next
to it
i = len(digits) - 2
while i >= 0 and digits[i] >= digits[i + 1]:
i -= 1
# Find the smallest digit on the right side of digits[i] that is greater
than digits[i]
j = len(digits) - 1
while digits[j] <= digits[i]:
j -= 1
# Example usage:
inputs = ["218765", "1234", "4321", "534976"]
for n in inputs:
print("Input:", n)
print("Output:", next_permutation(n))
OUTPUT-
3. Given an array of integers nums sorted in non-decreasing order, find
the starting and ending
position of a given target value.
If target is not found in the array, return [-1, -1].
Example -
Input: nums = [5,7,7,8,8,10], target = 8
Output: [3,4]
Input: nums = [5,7,7,8,8,10], target = 6
Output: [-1,-1]
Input: nums = [], target = 0
Output: [-1,-1]
SOLUTION -
# Example usage:
nums = [5, 7, 7, 8, 8, 10]
targets = [8, 6, 0]
for target in targets:
print("Input: nums =", nums, "target =", target)
print("Output:", search_range(nums, target))