Tuesday, 12 December 2023

Python OOP's concept , Writing Classes

# Init method is used to declare variables to the main method
# Self is for after initialising variables self is used to use that variables in another menthods
class Mobile:
  def __init__(self,brand,battery,ram,camera,price):
    self.brand=brand
    self.battery=battery
    self.ram=ram
    self.camera=camera
    self.price=price
  def display(self):
    print("Brand is :",self.brand)
    print("Battery is :",self.battery)
    print("Ram is :",self.ram)
    print("Camera is :",self.camera)
    print("Price is :",self.price)
    print("-------------------")
obj=Mobile('apple','400mah','8gb','84mp','40000')
obj.display()
obj2=Mobile('Motorola','400mah','8gb','84mp','40000')
obj2.display()




 # Difference between Class and a function

Defining a Function

def add_numbers(x, y):
    return x + y
--------------------------------------------------------------
Defining a Class

above function we can also write in the format of class.

 class Adder:
    def __init__(self, x, y):
        self.x = x
        self.y = y
    def add_numbers(self):
        return self.x + self.y


###################################################################################


The __init__ method initializes the instance variables self.x and self.y with the values passed when creating an object of the class.

Calling function and Class

# Using the original function
result_function = add_numbers(3, 4)
print("Result using function:", result_function)

# Using the class
adder_instance = Adder(3, 4)
result_class = adder_instance.add_numbers()
print("Result using class:", result_class)


__init__() method is used to declare the Global variables . Whenever we initialize a instance Object then global variables will get assigned with those values .
The variables which are declared inside the methods are called local varialbes 

Global Variable --- Scope is Global
Instance Variables -- Scope is for that particular Class 
Local Variables --- Scope is for a particular method or Function .

1)Package --->  Module(fileName)  ----> Method or functions(Methods or Funtions),variables
2)from mainpackage(create__init__.py).subpackage,module.(create__init__.py).module(fileName)  

import variable,method

module.Function()
module.variable



here mainpackage is Folder In this  - Folder create __init__.py
here subpackage is also a Folder -  In this Folder create __init__.py

__init__ ----- These __ variables are built in functions and Built in Variables .

##################################################################################

Dunder or Special Methods 
---------------------------------

A functional difference between special methods and common methods is that special methods can be called indirectly when we use a special syntax (such as arithmetic operations, subscripting, and slicing).

##################################################################################
Static Method:
A static method is a method that belongs to a class rather than an instance of the class. This means that a static method can be called on the class itself, without the need to create an object of the class.

Class method:
A class method is a method that belongs to a class rather than an instance of the class, but unlike a static method, it can access and modify the class variables.

Instance method:
Instance methods are used for operations that require object-specific data.


class Person:
    """
    A simple class representing a person.
    """

    # Static method to validate a person's age
    @staticmethod
    def is_valid_age(age):
        return age >= 0 and age <= 120

    # Class method to create a new person object with default values
    @classmethod
    def new_person(cls, name="John Doe", age=25):
        return cls(name, age)

    def __init__(self, name, age):
        self.name = name
        self.age = age

    # Instance method to introduce the person
    def introduce(self):
        return f"Hi, I'm {self.name} and I'm {self.age} years old."

# Usage example
person1 = Person.new_person("Alice", 30)
person2 = Person("Bob", 45)

# Static method usage
print(f"Is 20 a valid age? {Person.is_valid_age(20)}")
print(f"Is -10 a valid age? {Person.is_valid_age(-10)}")

# Instance method usage
print(person1.introduce())
print(person2.introduce())

The @staticmethod and @classmethod decorators are powerful features in Python that allow us to define methods that are associated with a class rather than an instance of the class.

##################################################################################


Monday, 11 December 2023

Lambda Functions


# Lambda function to add three Numbers 

>>> add = lambda a, b, c: a + b + c

>>> print(add(10, 10, 10))

30

List and Dictionary Comprehensions


# List Comprehensions

List Comprehensions execute from Right to Left , here first it will execute this for loop  for x in [1,2,3] and assign to variable same as for y variable it follows where x!=y

 >>> [(x, y) for x in [1,2,3] for y in [3,1,4] if x != y]

[(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]

Above statement is equal to below statement 

combs = []
for x in [1,2,3]:
    for y in [3,1,4]:
        if x != y:
            combs.append((x, y))


combs

[(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]

#########################################################################

You can use a function in a list comprehension to apply a transformation or filter elements based on a condition

>>> # Example 1: Using a function to square each element in a list
>>> def square(x):
...     return x ** 2
...
>>> numbers = [1, 2, 3, 4, 5]
>>> squared_numbers = [square(num) for num in numbers]
>>> print(squared_numbers)
[1, 4, 9, 16, 25]
>>> # Output: [1, 4, 9, 16, 25]
>>>

#################################################################################
Dictionary comprehensions in Python allow you to create dictionaries in a concise and readable way

>>> number = [1,2,3,4,6,7,8,6]
>>> dc={i:i*i for k in number}

>>> dc={i:i*i for i in number}
>>> print(dc)
{1: 1, 2: 4, 3: 9, 4: 16, 6: 36, 7: 49, 8: 64}
>>>
#################################################################################

Python Collection -- LISTS


# Converting String to List and List to records.

>>> pkeys="ECD,ENAME"

>>> pklist=pkeys.split(",")

 >>> for k in range(0,len(pklist)):

...     print('SRC.'+ pklist[k])

...

SRC.ECD

SRC.ENAME


# Converting TUPLE to List

>>> my_tuple = ('item_1', 'item_2', 'item_3', ...)

>>> my_list = []

>>> for i in my_tuple:

...     my_list.append(i)

...

>>> print(my_list)

['item_1', 'item_2', 'item_3', Ellipsis]


# Converting Dictionary to List

>>> d = {"name": "python", "version": 3.9}

>>> new_list = []

>>> for key, val in d.items():

...     new_list.append([key, val])

...

>>> print(new_list)

[['name', 'python'], ['version', 3.9]]


# Automating Lists in Python

>>> supplies = ['pens', 'staplers', 'flamethrowers', 'binders']

>>> for i in range(len(supplies)):

...      print('Index ' + str(i) + ' in supplies is: ' + supplies[i])

...

Index 0 in supplies is: pens

Index 1 in supplies is: staplers

Index 2 in supplies is: flamethrowers

Index 3 in supplies is: binders


# Iterating TUPLES inside a LIST

>>> name = [('sravan',7058,98.45),

... ('ojaswi',7059,90.67),

... ('bobby',7060,78.90),

... ('rohith',7081,67.89),

... ('gnanesh',7084,98.01)]

>>> # iterate using for loop

>>> for x in name:

... # iterate in each tuple element

...      for y in x:

...          print(y)

...

sravan

7058

98.45

ojaswi

7059

90.67

bobby

7060

78.9

rohith

7081

67.89

gnanesh

7084

98.01

# Finding the largest number in the List

my_list=[3,4,5,7,8,88,99,33,56,46]

largest = 0

for i in range(0,len(my_list)):

    if my_list[i] > largest:

       largest = my_list[i]


print(largest)

99

# Printing ID for an Object

Python id() FunctionThe id() function returns a unique id for the specified object. All objects in Python has its own unique id. The id is assigned to the object when it is created. The id is the object's memory address, and will be different for each time you run the program. shopping_list = ["milk",                 "pasta",                 "eggs",                 "spam",                 "bread",                 "rice"                 ]another_list = shopping_listprint(id(shopping_list))print(id(another_list))################################################################################### Converting Dictionary to List of Tuples # Converting Dictionary to List of Tuples >>> my_dict = {'a': 1}>>> items_list = []>>> for key, value in my_dict.items():...     items_list.append((key, value))...>>> print(items_list)[('a', 1)]
# Converting List of tuples to Records.k=[('a', 1)]for i in k:    for y in i:      print(y)a1
################################################################################### Using pop() to remove and return the last elementmy_list = [1, 2, 3, 4, 5]popped_element = my_list.pop()print("Popped element:", popped_element)print("Updated list:", my_list)
# Using remove() to remove a specific elementmy_list = [1, 2, 3, 4, 3, 5]my_list.remove(3)print("Updated list:", my_list)################################################################################### Iterating over List of dictionarieslist_of_dicts = [    {'name': 'Alice', 'age': 25, 'city': 'New York'},    {'name': 'Bob', 'age': 30, 'city': 'San Francisco'},    {'name': 'Charlie', 'age': 22, 'city': 'Los Angeles'}]# Iterating over the list of dictionariesfor my_dict in list_of_dicts:    # Accessing key-value pairs within each dictionary    for key, value in my_dict.items():        print(f"{key}: {value}")    print()  # Print an empty line between dictionaries for clarity##################################################################################Remove duplicate data from the list # Create a list with duplicatesdata = [1, 3, 45, 3, 1, 6, 7, 8, 9]
# Create an empty list to store unique elementsunique_data = []
# Iterate through the original listfor item in data:    # Check if the item is not already present in the unique_data list    if item not in unique_data:        # Add the item to the unique_data list        unique_data.append(item)
# Print the original list and the list without duplicatesprint(f"Original list: {data}")print(f"List without duplicates: {unique_data}")##################################################################################Retrieve the highest value in the List # Create a list with duplicatesdata = [1, 3, 45, 3, 1, 6, 7, 8, 9]
# Initialize a variable to store the highest valuehighest_value = data[0]
# Iterate through the listfor item in data:    # Compare the current item with the highest value    if item > highest_value:        # Update the highest value if the current item is greater        highest_value = item
# Print the highest valueprint(f"Highest value in the list: {highest_value}##################################################################################Flatten the Nested List list1 = [[1, 2, 3],[4, 5, 6]]newlist = []for list2 in list1: for j in list2:      newlist.append(j)print(newlist)##################################################################################





SQL -

 Window Functions -  Window function: pySpark window functions are useful when you want to examine relationships within group of data rather...