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

codingAssignment2(B58)

The document contains Python code snippets demonstrating various algorithms. It includes functions for generating permutations of a string, checking for permutations within another string, validating parentheses, and identifying an odd occurring balloon color. Each section is accompanied by example outputs illustrating the functionality of the code.

Uploaded by

regularuse0001
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
0 views

codingAssignment2(B58)

The document contains Python code snippets demonstrating various algorithms. It includes functions for generating permutations of a string, checking for permutations within another string, validating parentheses, and identifying an odd occurring balloon color. Each section is accompanied by example outputs illustrating the functionality of the code.

Uploaded by

regularuse0001
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

from itertools import permutations

# 1) Permutations of a Given String


def string_permutations(s):
return [''.join(p) for p in permutations(s)]
print("Permutations of 'ABC':", string_permutations("ABC"))

Permutations of 'ABC': ['ABC', 'ACB', 'BAC', 'BCA', 'CAB', 'CBA']

# 2) LeetCode - 567. Permutation in String


class Solution:
def checkInclusion(self, s1: str, s2: str) -> bool:
if len(s1) > len(s2):
return False

s1_count = Counter(s1)
window_count = Counter(s2[:len(s1)])

if s1_count == window_count:
return True

for i in range(len(s1), len(s2)):


window_count[s2[i]] += 1
window_count[s2[i - len(s1)]] -= 1

if window_count[s2[i - len(s1)]] == 0:
del window_count[s2[i - len(s1)]]

if s1_count == window_count:
return True

return False
sol_perm = Solution()
print("Permutation in String:", sol_perm.checkInclusion("ab",
"eidbaooo"))

Permutation in String: True

# 3) LeetCode - 20. Valid Parentheses


class Solution:
def isValid(self, s: str) -> bool:
stack = []
mapping = {')': '(', '}': '{', ']': '['}

for char in s:
if char in mapping:
top_element = stack.pop() if stack else '#'
if mapping[char] != top_element:
return False
else:
stack.append(char)
return not stack
sol_valid = Solution()
print("Valid Parentheses:", sol_valid.isValid("()[]{}"))

Valid Parentheses: True

from collections import Counter


# 4) Odd Occurring Balloon Color
def odd_occurring_balloon(B):
color_count = Counter(B)

for color in B:
if color_count[color] % 2 == 1:
return color

return "All are even"


print("Odd Occurring Balloon Color:", odd_occurring_balloon(['r', 'g',
'b', 'b', 'g', 'y', 'y']))

Odd Occurring Balloon Color: r

You might also like