Python Assignment– 3

Data Structures

Basic Questions

  1. Read a string ‘s’ and print its first and last characters using indexing: ‘s[0]’ and ‘s[-1]’.
  2. Read a string ‘s’ and print the slices ‘s[:3]’, ‘s[3:]’, and ‘s[::2]’.
  3. Show string immutability: read ‘s’, try to set ‘s[0] = “X”‘ inside a ‘try/except’, and print the caught exception type.
  4. Read a string ‘s’ and print ‘s.lower()’, ‘s.upper()’, and ‘s.title()’ on separate lines.
  5. Read a string ‘s’ and print ‘s.strip()’, ‘s.lstrip()’, and ‘s.rstrip()’ results.
  6. Read a string ‘s’ and a substring ‘sub’; print ‘s.find(sub)’ and ‘s.count(sub)’.
  7. Read a string ‘s’ and replace all spaces with dashes using ‘s.replace(” “, “-“)’; print the result.
  8. Read space-separated words and join them with commas using ‘”,”.join(words_list)’; print the result.
  9. Create a list ‘nums’ from input using ‘split()’ and ‘int’ casting; print ‘nums[0]’, ‘nums[-1]’, and ‘nums[1:4]’.
  10. Start with list ‘a = [1, 2, 3]’; apply ‘append(4)’, ‘extend([5, 6])’, ‘insert(0, 0)’, then print ‘a’.
  11. From list ‘a’, call ‘remove(3)’, ‘pop()’, and ‘reverse()’; print ‘a’ after each operation.
  12. Read numbers into list ‘a’; print ‘sorted(a)’ and then sort in-place with ‘a.sort()’; print ‘a’.
  13. Read a list ‘a’ and build ‘squares = [x * x for x in a]’; print ‘squares’.
  14. Read a tuple literal like ‘(1, 2, 3)’; print its length and ‘t[0]’, ‘t[-1]’.
  15. Demonstrate tuple immutability by catching the exception for ‘t[0] = 99’ and printing the exception type.
  16. Perform tuple packing/unpacking: read three values, pack to ‘t = (x, y, z)’, unpack to ‘a, b, c’, and print ‘a, b, c’.
  17. Create a set ‘s’ from input items; print ‘s’ to show uniqueness and print ‘len(s)’.
  18. Read two sets ‘s1’ and ‘s2’; print ‘s1 | s2’, ‘s1 & s2’, ‘s1 – s2’, and ‘s1 ^ s2’.
  19. Convert a set ‘s’ to ‘fs = frozenset(s)’; print ‘fs’ and demonstrate that ‘fs.add(…)’ raises an exception by catching and printing its type.
  20. Create a dictionary ‘d’ from pairs like ‘key:value’ read from input; print ‘d’, ‘d.keys()’, ‘d.values()’, and ‘d.items()’.

Intermediate Questions

  1. Read a string ‘s’ and print: middle slice ‘s[len(s)//2 – 1 : len(s)//2 + 2]’ (handle short strings with bounds checks).
  2. Read ‘s’ and a character ‘ch’; print indices of all occurrences using a list comprehension with ‘enumerate’.
  3. Read ‘s’ and print a new string with every second character removed using slicing and concatenation: ‘s[::2]’.
  4. Read a sentence ‘s’; split with ‘s.split()’, then rejoin with single spaces using ‘” “.join(…)’; print the result.
  5. Read a list of numbers ‘a’; build ‘evens = [x for x in a if x % 2 == 0]’ and ‘odds = [x for x in a if x % 2 != 0]’; print both.
  6. Read list ‘a’; demonstrate slicing assignment by replacing ‘a[1:3]’ with ‘[999, 1000]’; print ‘a’.
  7. Read tuple ‘t’ and another tuple ‘u’; print ‘t + u’ and ‘u * 2’.
  8. Read three variables and swap them cyclically using tuple unpacking: ‘x, y, z = y, z, x’; print the result.
  9. Read two sets ‘s1’, ‘s2’; print ‘s1.issubset(s2)’, ‘s1.issuperset(s2)’, and ‘s1.isdisjoint(s2)’.
  10. Read a set ‘s’; show set algebra using methods: print ‘s.union({1})’, ‘s.intersection({1,2})’, ‘s.difference({1})’, ‘s.symmetric_difference({1,2})’.
  11. Build a dictionary ‘d’ from space-separated ‘key:value’ pairs; use ‘d.get(key, default)’ for a missing key and print the returned value.
  12. Update dictionary ‘d’ with another dictionary ‘u’ using ‘d.update(u)’; print ‘d’ before and after.
  13. Demonstrate ‘pop’ and ‘setdefault’: from ‘d’, print ‘d.pop(some_key, “NA”)’ and then ‘d.setdefault(new_key, 0)’; print final ‘d’.
  14. Create a nested dictionary ‘students’ like ‘{id: {“name”: n, “marks”: m}}’ for three entries from input; print all names using iteration over ‘students.values()’.
  15. Iterate over ‘d.items()’ and print formatted lines ‘key=value’ for each pair.
  16. Word counter: read a line ‘s’, split into words, build ‘freq’ dictionary by counting; print ‘freq’.
  17. Frequency analyzer: read ‘s’, count character frequencies using a dictionary, and print the top 3 characters by frequency (break ties by character order).
  18. Use ‘zip’ to pair two equal-length lists ‘names’ and ‘scores’ from input and produce dictionary ‘report = dict(zip(names, scores))’; print ‘report’.
  19. Flatten a nested list like ‘[[1,2],[3,4],[5]]’ into ‘flat = [x for sub in nested for x in sub]’; print ‘flat’.
  20. Iterate over mixed data structures: given ‘s’ (string), ‘a’ (list), ‘t’ (tuple), ‘d’ (dict), print lengths using a single loop that iterates over ‘[s, a, t, d]’.

Advanced Questions

  1. Build a robust word counter: read text ‘s’, normalize with ‘s.lower().strip()’, remove punctuation using a simple ‘replace’ chain, split into words, count to ‘freq’, and print the 5 most common words with counts.
  2. N-gram frequency analyzer: read text ‘s’ and integer ‘n’; build a dictionary of substring frequencies for all slices ‘s[i:i+n]’ (skip spaces), then print the top 5 n-grams.
  3. Build an anagram grouper: read a list of words, group by sorted letters using a dictionary with keys ‘tuple(sorted(word))’, and print the groups.
  4. List comprehension toolbox: from list ‘a’ build in one statement ‘result = [x * x if x % 2 == 0 else -x for x in a if x != 0]’; print ‘result’.
  5. Tuple-based leaderboard: read ‘(name, score)’ pairs into a list of tuples; sort by ‘score’ descending using ‘sorted(pairs, key=lambda p: p[1], reverse=True)’; print top 3.
  6. Set-based de-duplication pipeline: read a list with duplicates, convert to ‘set’ to deduplicate, then back to a sorted list; print before/after and the count of removed items.
  7. Frozen membership map: create ‘fs = frozenset’ from a list of allowed tokens; read queries and print ‘token in fs’ for each; demonstrate that ‘fs.add’ is invalid by catching and printing the exception type.
  8. Nested dictionary updater: read ‘users’ as ‘{id: {“name”: …, “skills”: […]}}’; append a new skill to one user using ‘dict’ access and ‘list.append’; print the updated entry.
  9. Build an index across structures: read list ‘titles’, list ‘authors’, and list ‘years’; create ‘catalog = [ {“title”: t, “author”: a, “year”: y} for t, a, y in zip(titles, authors, years) ]’; print ‘catalog’ and then all titles from year >= a given threshold.
  10. Sliding-window frequency: read list ‘nums’ and window size ‘k’; for i from 0 to ‘len(nums)-k’, compute frequency dictionary for ‘nums[i:i+k]’ and print the most frequent value per window (break ties by smallest value).