Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
171 views

Litcoder Final Modules Only

Overall the document showcases a variety of algorithmic coding problems

Uploaded by

naveen kumar
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
171 views

Litcoder Final Modules Only

Overall the document showcases a variety of algorithmic coding problems

Uploaded by

naveen kumar
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 9

Non-CS Module -1 Lab -1-

*Time conversion*

import sys
def doSomething(inval):
if inval[-2:]=="AM":
outval=inval[:-2]
check=int(inval[0:2])
if check ==12:
outval="00"+outval[2:]
else:
outval=inval[:-2]
check=int(inval[0:2])
if check<12:
check+=12
outval=str(check)+outval[2:]
return outval
inputVal = str(input())
outputVal = doSomething(inputVal)
print (outputVal)

*Reverse a string*

def is_alphabet(c):
return c.isalpha()

def reverse_alphabets_with_case_preservation(input_str):
alphabets = [char for char in input_str if is_alphabet(char)]
reversed_alphabets = ''.join(reversed(alphabets))
result = []

j = 0
for char in input_str:
if is_alphabet(char):
result.append(reversed_alphabets[j])
j += 1
else:
result.append(char)

return ''.join(result)

def main():
input_str = input()
reversed_str = reverse_alphabets_with_case_preservation(input_str)
print(reversed_str)

if __name__ == "__main__":
main()

Non-CS Module-1 Lab-2

*Sort colors*
def sortColors(nums):
counts={0:0,1:0,2:0}
for color in nums:
counts[color]+=1
index=0
for color in [0,1,2]:
count=counts[color]
for _ in range(count):
nums[index]=color
index+=1
nums=list(map(int,input().split()))
sortColors(nums)
sorted_colors=' '.join(map(str,nums))
print(sorted_colors)

*Restore IP address:*

def is_valid(ip):

# Splitting by "."
ip = ip.split(".")

# Checking for the corner cases


for i in ip:
if (len(i) > 3 or int(i) < 0 or int(i) > 255):
return False
if len(i) > 1 and int(i) == 0:
return False
if (len(i) > 1 and int(i) != 0 and i[0] == '0'):
return False

return True

# Function converts string to IP address


def convert(s):

sz = len(s)

# Check for string size


if sz > 12:
return []
snew = s
l = []

# Generating different combinations.


for i in range(1, sz - 2):
for j in range(i + 1, sz - 1):
for k in range(j + 1, sz):
snew = snew[:k] + "." + snew[k:]
snew = snew[:j] + "." + snew[j:]
snew = snew[:i] + "." + snew[i:]

# Check for the validity of combination


if is_valid(snew):
l.append(snew)
snew = s

return l
inputVal = input()
outputVal = convert(inputVal)
print (outputVal)

Non-CS Module-2 Lab-1

*Generate Brackets:*

import sys
def doSomething(str,n):
if n>0:
printpara(str,0,n,0,0)
return
def printpara(str,pos,n,open,close):
if(close==n):
for i in str:
print(i,end = " ")
print()
return
else:
if(open>close):
str[pos] = ')'
printpara(str,pos+1,n,open,close+1)
if(open<n):
str[pos] = '('
printpara(str,pos+1,n,open+1,close)
inputVal = int(input())
str = [""]*2*inputVal
doSomething(str,inputVal)

*INTEGER TO ROMAN*

def R_to_I(inval):
dict1 = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}
count = 0
i = 0

while i < len(inval):


# Check if the current character and the next character form a valid Roman
numeral
if i + 1 < len(inval) and inval[i:i+2] in dict1:
count += dict1[inval[i:i+2]]
i += 2
else:
count += dict1[inval[i]]
i += 1

return count

inputVal = input("Enter a Roman numeral:\n ")


result = R_to_I(inputVal)
print(f"The integer representation of {inputVal} is: {result}")
outputVal = R_to_I(inputVal)
print (outputVal)

Non CS Module -2 Lab-2

*Closest Triples:*

def threeSumClosest(nums, target):


nums.sort()
closest_sum = float('inf')

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


left, right = i + 1, len(nums) - 1

while left < right:


curr_sum = nums[i] + nums[left] + nums[right]

if abs(curr_sum - target) < abs(closest_sum - target):


closest_sum = curr_sum

if curr_sum < target:


left += 1
elif curr_sum > target:
right -= 1
else:
return curr_sum

return closest_sum

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


target = int(input())
result = threeSumClosest(numbers, target)
print(result)

Combination Sum:

def doSomething(arr, target_sum):


outval = []
temp = []
arr = sorted(list(set(arr)))
num(outval, arr, temp, target_sum, 0)
return outval

def num(outval, arr, temp, target_sum, index):


if target_sum == 0:
outval.append(list(temp))
return
for i in range(index, len(arr)):
if target_sum - arr[i] >= 0:
temp.append(arr[i])
num(outval, arr, temp, target_sum - arr[i], i)
temp.remove(arr[i])
# Take user input for the array
arr_input = input()
arr = [int(x) for x in arr_input.split(" ")]

# Take user input for the target sum


target_sum = int(input())

# Call the function and print the result


outputVal = doSomething(arr, target_sum)

# Format the output


output_str = '\n'.join([' '.join(map(str, sublist)) for sublist in outputVal])
print(output_str)

Non-CS Module-3 Lab-1 Dipesh

*Word Game:*

def exist(board, word):


def dfs(i, j, k):
if not (0<= i<len(board)) or not(0<=j<len(board[0])) or board[i][j]!
=word[k]:
return False
if k==len(word)-1:
return True
tmp, board[i][j]= board[i][j],'/'
found=dfs(i+1,j,k+1) or dfs(i-1,j,k+1) or dfs(i,j+1,k+1) or dfs(i,j-1,k+1)
board[i][j]=tmp
return found
for i in range(len(board)):
for j in range(len(board[0])):
if dfs(i, j, 0):
return True
return False
rows= int(input())
columns= int(input())
word=input()
Input=input()
rows_input = Input.strip().split(" ")
if columns == 0:
coumns =len(rows_input)
board = [list(row) for row in rows_input]

output= exist(board,word)

if output==True:
print('Yes')
else:
print('No')

*Jump Game:*

def can_jump(nums):
n = len(nums)
max_reach = 0

for i in range(n):
if i > max_reach:
# If the current index is not reachable, return False
return False

max_reach = max(max_reach, i + nums[i])

if max_reach >= n - 1:
# If the maximum reachable index is greater than or equal to the last
index, return True
return True

return False

# Take user input for the array


nums = input()
nums = [int(x) for x in nums.split(" ")]

# Call the function and print the result


result = can_jump(nums)
if result==True:
print('true')
else:
print('false')

Non CS Module-3 Lab-2 ABHI

*Longest Substring Containing Vowels in Even Counts*

def longest_substring_with_even_vowels(s):
vowels = {'a', 'e', 'i', 'o', 'u'}
count = {vowel: 0 for vowel in vowels}
count_tuple = tuple(count.values())
seen = {count_tuple: -1}
max_length = 0

for i, char in enumerate(s):


if char in vowels:
count[char] += 1

count_tuple = tuple(count[vowel] % 2 for vowel in vowels)

if count_tuple in seen:
max_length = max(max_length, i - seen[count_tuple])
else:
seen[count_tuple] = i

return max_length

input_string = input()
result = longest_substring_with_even_vowels(input_string)
print(result)

Mini Max

from itertools import combinations

def find_min_max_sums(numbers):
# Ensure the input list has at least 6 elements
if len(numbers) < 6:
print("Error: Input list must have at least 6 elements.")
return

# Find all combinations of 4 numbers


all_sums = [sum(combination) for combination in combinations(numbers, 4)]

# Find the minimum and maximum sums


min_sum = min(all_sums)
max_sum = max(all_sums)

print(f"{min_sum} {max_sum}")

input_string = input()
numbers = list(map(int, input_string.split()))

find_min_max_sums(numbers)

Non-CS Module-4 Lab-1 Gaya3

*Counting Sort 1*

def frequency_count(arr):
# Find the minimum and maximum elements in the array
min_element = min(arr)
max_element = max(arr)

# Iterate through the range of elements and count frequencies


for element in range(0, max_element + 1):
frequency = arr.count(element)
print(frequency, end=" ")

no_of_inputs = int(input()) # Convert to integer


input_str = input()
input_arr = list(map(int, input_str.split()))
frequency_count(input_arr)

*000G Cipher PY*

def encrypt(word, key, operation, cipher):


# Check if the word is in capitals
if not word.isupper():
print("Word should be in capitals.")
return

# Check if the key is not a number


if not key.isdigit():
print("Enter valid key.")
return

key = int(key)

# Check if the operation is either addition or subtraction


if operation not in ['addition', 'subtraction']:
print("Invalid Operation.")
return
# Substitution cipher
encrypted_word = ''.join(cipher[char] if char in cipher else char for char in
word)

# Apply mathematical operation


if operation == 'addition':
encrypted_word = ''.join(chr((ord(char) + key - ord('A')) % 26 + ord('A'))
for char in encrypted_word)
elif operation == 'subtraction':
encrypted_word = ''.join(chr((ord(char) - key - ord('A')) % 26 + ord('A'))
for char in encrypted_word)

return encrypted_word

cipher =
{'A':'Z','B':'Y','C':'X','D':'W','E':'V','F':'U','G':'T','H':'S','I':'R','J':'Q','K
':'P','L':'O','M':'N','N':'M','O':'L','P':'K','Q':'J','R':'I','S':'H','T':'G','U':'
F','V':'E','W':'D','X':'C','Y':'B','Z':'A'}

key = input()
operation = input()
word = input()

encrypted_word = encrypt(word, key, operation, cipher)


print(encrypted_word)

Non-CS Module-4 Lab-2

*Tower breakers*

def tower_game_winner(n, m):


# If there is only one tower, Player 1 wins
if n == 1:
return 1

# If the height of any tower is 1, Player 1 wins


if m == 1:
return 1

# If the height of any tower is even, Player 2 wins


if m % 2 == 0:
return 2

# Otherwise, Player 1 wins


return 1

# Example usage:
n, m = map(int, input().split())

winner = tower_game_winner(n, m)
print( winner)

*Grid Challenge*

import sys
def grid_challenge(grid):
# Rearrange element in each row in ascending alphabetical order
sorted_rows = [''.join(sorted(row)) for row in grid]

#check if columns are in ascending alphabetical order


columns_sorted = all(''.join(col) == ''.join(sorted(col)) for col in
zip(*sorted_rows))

# Sort the columns of the grid


sorted_columns = [sorted(column) for column in zip(*grid)]

# Check if the columns are sorted in non-decreasing order


columns_sorted = all(all(sorted_column[i] <= sorted_column[i + 1] for i in
range(len(sorted_column) - 1)) for sorted_column in sorted_columns)

return "YES" if columns_sorted else "NO"

grid_example = input()
result = grid_challenge(grid_example)
print(result)

You might also like