Python Functions: Handling Duplicates and Dictionary Inversion

Aim: Write a function called has_duplicates that takes a list and returns True if there is any element that appears more than once. It should not modify the original list.

i). Write a function called remove_duplicates that takes a list and returns a new list with only the unique elements from the original. Hint: they don’t have to be in the same order.

Program:

def is_duplicate(anylist):
    if type(anylist) != 'list':
        return("Error. Passed parameter is Not a list")
    if len(anylist) != len(set(anylist)):
        return True
    else:
        return False

mylist = [5, 3, 5, 2, 1, 6, 6, 4] # you can see some repeated number in the list.
if is_duplicate(mylist):
    print("True,duplicates found in list")
else:
    print("False,no duplicates found in list")

Output:

True, duplicates found in list

Aim: ii)The wordlist I provided, words.txt, doesn’t contain single letter words. So you might want to add “I”, “a”, and the empty string.

Program:

# the given list contains duplicates
mylist = [5, 3, 5, 2, 1, 6, 6, 4] # the original list of integers with duplicates

newlist = [] # empty list to hold unique elements from the list
duplist = [] # empty list to hold the duplicate elements from the list
for i in mylist:
    if i not in newlist:
        newlist.append(i)
    else:
        duplist.append(i) # this method catches the first duplicate entries, and appends them to the list

# The next step is to print the duplicate entries, and the unique entries
print("List of duplicates", duplist)
print("Unique Item List", newlist) # prints the final list of unique items

Output:

List of duplicates [5, 6]
Unique Item List [5, 3, 2, 1, 6, 4]

Aim: iii)Write a python code to read dictionary values from the user. Construct a function to invert its content. i.e., keys should be values and values should be keys.

Program:

d = {'student1': 1201, 'student2': 1202, 'student3': 1203}
print("The original  dictionary is:",d)
def invert_its_content(d):
    return {v: k for k, v in d.items()}

d_invert = invert_its_content(d)
print("After Inverting dictionary",d_invert)
# {'val1': 'key1', 'val2': 'key2', 'val3': 'key3'}

Output:

The original dictionary is: {‘student1’: 1201, ‘student2’: 1202, ‘student3’: 1203}
After Inverting dictionary {1201: ‘student1’, 1202: ‘student2’, 1203: ‘student3’}

Sample Viva Questions and Answers

1. What is the purpose of the is_duplicate function?
The purpose of the is_duplicate function is to check if there are any duplicate elements in a given list and return True if duplicates are found, otherwise return False.

2. How does the function determine if the input is a list?
The function checks the type of the input using type(anylist) != 'list'. However, this check is incorrect; it should use type(anylist) != list without quotes.

3. What method is used to check for duplicates in the list?
The function compares the length of the original list with the length of the set created from the list. Since sets do not allow duplicates, if the lengths differ, duplicates exist.

4. What will be the output of the is_duplicate function when called with the list [5, 3, 5, 2, 1, 6, 6, 4]?
The output will be True, indicating that duplicates are found in the list.

5. What is the purpose of the remove_duplicates section of the program?
The purpose is to create a new list containing only the unique elements from the original list, effectively removing duplicates.

6. How does the program identify and store duplicate elements?
The program iterates through the original list and checks if each element is already in the newlist. If it is not, it adds it to newlist; if it is, it adds it to duplist.

7. What is the purpose of the invert_its_content function?
The purpose of the invert_its_content function is to invert a dictionary, swapping its keys and values.

8. How does the invert_its_content function achieve the inversion of the dictionary?
The function uses a dictionary comprehension to create a new dictionary where the keys and values are swapped: {v: k for k, v in d.items()}.

📌 Python Programming Lab – Complete Guide

Welcome to the Python Programming Lab! This comprehensive lab series is designed to provide a solid foundation in Python programming through practical exercises and hands-on learning. From basic calculations to advanced concepts like file handling, modules, and GUI programming, this lab covers it all. Let’s dive into what you’ll be learning throughout this lab course.


🔍 Week 1: Introduction to Python Basics

In the first week, you will explore fundamental Python concepts aimed at building a strong foundation for your programming journey.

  • Getting Started with Python: Visit the Python Official Website to explore documentation and use the help() function in the interpreter.
  • Python as a Calculator: Learn how to perform basic arithmetic operations like addition, subtraction, multiplication, and division.
  • Calculating Compound Interest: Write a program to calculate compound interest using the formula with given principal, rate, and time.
  • Distance Calculation: Compute the distance between two points using the distance formula.
  • Reading User Details: Write a program to collect and print user details like name, address, email, and phone number.

🔍 Week 2: Python Loops and Conditional Statements

This week focuses on using loops and conditional statements effectively.

  • Pattern Generation: Print a triangle pattern using nested loops.
  • Character Identification: Write a program to identify whether the input is a digit, lowercase, uppercase, or special character.
  • Fibonacci Sequence Generation: Use a while loop to generate the Fibonacci series.
  • Prime Numbers Identification: Find all prime numbers within a specified range using the break statement.

🔍 Week 3: Data Structures and Functions

Dive into data structures and creating functions to enhance your programming skills.

  • Converting Lists and Tuples to Arrays: Understand how to convert different data structures.
  • Finding Common Values: Compare two arrays to find common values.
  • Calculating GCD: Create a function to calculate the greatest common divisor (GCD) of two numbers.
  • Palindrome Checker: Write a function that checks if a given string is a palindrome.

🔍 Week 4: Advanced Functions and String Manipulation

This week emphasizes sorting, handling duplicate elements, and manipulating strings effectively.

  • Checking Sorted Lists: Write a function to check if a list is sorted.
  • Handling Duplicates: Create functions to detect and remove duplicates from lists.
  • Dictionary Inversion: Write a program to swap keys and values in a dictionary.
  • String Manipulation: Add commas between characters, remove words from strings, and convert sentences to title case without using built-in functions.
  • Binary String Generation: Use recursion to generate all binary strings of a specified length.

🔍 Week 5: Working with Matrices and Modules

Learn to work with matrices and create custom modules for various applications.

  • Matrix Operations: Define, print, add, and multiply square matrices using Python.
  • Creating Modules: Build modules using geometrical shapes and their operations.
  • Exception Handling: Implement exception handling for robust error management.

🔍 Week 6: Object-Oriented Programming and Validation

This week focuses on using classes, inheritance, and validation techniques.

  • Drawing Shapes with Classes:
    • Create classes for rectangles, points, and circles, and draw them on a canvas.
    • Add colors and attributes to these shapes to enhance visualization.
  • Method Resolution Order (MRO): Demonstrate MRO in multiple inheritance scenarios.
  • Data Validation: Write programs to validate phone numbers and email addresses.

🔍 Week 7: File Handling and Text Processing

Master file handling techniques and analyzing text data.

  • File Merging: Combine the contents of two files into a new file.
  • Word Search: Create a function to find specific words in a file.
  • Word Frequency Analysis: Identify the most frequent words in a text file.
  • Text Statistics: Count words, vowels, blank spaces, lowercase, and uppercase letters in a file.

🔍 Week 8: Python Libraries and GUI Programming

Explore advanced Python libraries and build simple graphical user interfaces.

  • NumPy, Plotly, and Scipy: Learn how to install and use these powerful libraries for data analysis and visualization.
  • Digital Logic Gates: Implement logic gate operations such as AND, OR, NOT, and EX-OR.
  • Adder Circuits: Create programs for Half Adders, Full Adders, and Parallel Adders.
  • GUI Programming: Build a simple window wizard with text labels, input fields, and buttons using Python’s GUI tools.

🌟 Conclusion:

The Python Programming Lab R23 provides you with a strong foundation in Python programming through a wide range of exercises, from basic concepts to advanced topics. By the end of this lab, you will have gained valuable skills in data processing, file handling, OOP, modules, and GUI development. Start coding and enhance your Python skills! 🚀


;