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

Code on python

some Basic question on python

Uploaded by

Harsh Raj
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)
5 views

Code on python

some Basic question on python

Uploaded by

Harsh Raj
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/ 18

WEEK-5

Question 1:
Extract Elements with Frequency Greater than K

Code:
from collections import Counter
# Input from user
test_list = list(map(int, input("Enter the list of numbers: ").split()))
K = int(input("Enter the value of K: "))
# Count frequency of elements
frequency = Counter(test_list)
# Extract elements with frequency greater than K

result = [key for key, value in frequency.items() if value > K]


# Output
print("Elements with frequency greater than K:", result)

Output:
Question 2:
Check for Three Consecutive Common Numbers

Code:
# Input from user

test_list = list(map(int, input("Enter the list of numbers: ").split()))

# Find three consecutive common numbers


result = []
for i in range(len(test_list) - 2):

if test_list[i] == test_list[i+1] == test_list[i+2]:


result.append(test_list[i])

# Output
print("Numbers occurring 3 consecutive times:", result)

Output:
Question 3:
Character Position of Kth Word in a List of Strings

Code:
# Input from user
test_list = input("Enter the list of strings: ").split(", ")
K = int(input("Enter the character position (K): "))

# Finding the word and character position


current_pos = 0 for word in test_list:

if current_pos + len(word) >= K:


char_pos = K - current_pos - 1
print(f"The character at position {K} is '{word[char_pos]}' in the word '{word}'")
break

current_pos += len(word)

Output:
Question 4:
Extract Words Starting with a Specific Character (K)

Code:
# Input from user
test_list = input("Enter the list of phrases: ").split(", ")
K = input("Enter the character to check for: ").lower()

# Extract words starting with K

result = []
for phrase in test_list:

words = phrase.split()
result.extend([word for word in words if word.lower().startswith(K)])

# Output

print("Words starting with", K, ":", result)

Output:
Question 5:
Replace All Characters of a List Except Given Character

Code:
# Input from user

test_list = input("Enter the list of characters: ").split()


repl_chr = input("Enter the character to replace others with: ")
ret_chr = input("Enter the character to retain: ")

# Replace characters

result = [repl_chr if char != ret_chr else ret_chr for char in test_list]

# Output

print("Modified list:", result)


Output:
Question 6:
Add Space Between Capital Letters in a String List
Code: import re
# Input from user

test_list = input("Enter the list of strings: ").split(", ")

# Add space between capital letters


result = [re.sub(r'([a-z])([A-Z])', r'\1 \2', phrase) for phrase in test_list]

# Output
print("Modified list:", result)
Output:
Question 7:
Filter List Based on Substring in Corresponding Index of Second List

Code:
# Input from user

test_list1 = input("Enter the first list: ").split(", ")


test_list2 = input("Enter the second list: ").split(", ")
sub_str = input("Enter the substring to check for: ")

# Filter list

result = [test_list1[i] for i in range(len(test_list2)) if sub_str in test_list2[i]]

# Output
print("Filtered list:", result)

Output:
Question 8:
Convert Character Matrix to Single String

Code:
# Input from user

test_list = [list(input(f"Enter row {i+1} elements separated by spaces: ").split()) for i in range(3)]

# Convert matrix to single string

result = ''.join(''.join(row) for row in test_list)

# Output

print("Single string:", result)

Output:
WEEK-6

Question 1:
Sorting Dictionary By Key Using sort()

Code:

# Input

input_dict = {'ravi': '10', 'rajnish':'9','abc': '15'}

# Sorting the dictionary by keys

from collections import OrderedDict


sorted_dict = OrderedDict(sorted(input_dict.items()))

# Output
print("Sorted dictionary:", sorted_dict)

Output:
Question 2:
Merging or Concatenating Two Dictionaries in Python

Code:
# Input
d1 = {'x': 10, 'y': 8} d2
= {'a': 6, 'b': 4}

# Merging dictionaries

merged_dict = {**d1, **d2}

# Output

print("Merged dictionary:", merged_dict)

Output:
Question 3:
Find Common Elements in Three Sorted Arrays by Dictionary Intersection

Code: # Input
ar1 = [1, 5, 10, 20, 40, 80]

ar2 = [6, 7, 20, 80, 100]

ar3 = [3, 4, 15, 20, 30, 70, 80, 120]

# Finding common elements

common_elements = list(set(ar1) & set(ar2) & set(ar3))

# Output

print("Common elements:", common_elements)

Output:
Question 4:
Dictionary and Counter in Python to Find Winner of Election

Code: # Input
votes = ["john", "johnny", "jackie", "johnny", "john", "jackie", "jamie", "jamie",
"john","johnny","jamie","johnny", "john"]

# Counting votes

from collections import Counter


vote_count = Counter(votes)

# Finding the candidate with maximum votes


winner = min([name for name, count in vote_count.items() if count == max(vote_count.values())])

# Output

print("Winner:", winner)

Output:
Question 5:
Python Dictionary to Find Mirror Characters in a String

Code:
# Input

N=3

string = "paradox"

# Mirroring characters

mirrored_string = string[:N] + ''.join(chr(219 - ord(c)) for c in string[N:])

# Output

print("Mirrored string:", mirrored_string)

Output:
Question 6:
Count Distinct Substrings of a String Using Rabin Karp Algorithm

Code:
# Input

s ="aba"

# Finding distinct substrings


distinct_substrings = set()
for i in range(len(s)):

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


distinct_substrings.add(s[i:j])

# Output

print("Number of distinct substrings:", len(distinct_substrings))

Output:
Question 7:
Print Anagrams Together in Python Using List and Dictionary

Code:
#Input

arr = ['cat', 'dog', 'tac', 'god', 'act']

# Grouping anagrams

from collections import defaultdict


anagrams = defaultdict(list)

for word in arr:


anagrams[tuple(sorted(word))].append(word)

# Output

print("Anagrams together:", ' '.join([word for group in anagrams.values() for word in group]))

Output:
Question 8:
Similar Characters Strings Comparison

Code: # Input
test_str1 = 'e!e!k!s!g'
test_str2 = 'g!e!e!k!s'
delim = '!'

# Checking if both contain same characters

same_chars = set(test_str1.split(delim)) == set(test_str2.split(delim))

# Output
print("Same characters:", same_chars)

Output:
Question 9:
Longest Substring Length of K
Code: #
Input

test_str = 'abcaaaacbbaa'
K = 'b'

# Finding longest substring length


longest_length = test_str.count(K)

# Output
print("Longest substring length of", K, ":", longest_length)

Output:
Question 10:
Find Minimum Number of Rotations to Obtain Actual String
Code: # Input
s1 = 'eeksg'
s2 = 'geeks'
# Finding minimum rotations

n = len(s1)

rotations = s1 + s1
min_rotations = next((i for i in range(n) if rotations[i:i+n] == s2), -1)

# Output
print("Minimum number of rotations:", min_rotations)
Output:

You might also like