Python

 

Q: How to concatenate two strings in python?

Ans:

var1 = "Hello"

var2 = "World"

# format function is used here to combine the string

print("{} {}".format(var1, var2))

# + Operator is used to combine strings

var3 = var1 + var2

print(var3)


Q: How to check data type ?

Ans:
           d=5
           print(type(d))

Q: What are data types in python?

Ans:
        There are different types of data types in Python. Some built-in Python data types are:
  • Numeric data typesint, float, complex

  • String data typesstr

  • Sequence typeslist, tuple, range

  • Binary typesbytes, bytearray, memoryview

  • Mapping data typedict

  • Boolean typebool

  • Set data typesset, frozenset

Q:How List works in Python ?

Ans:
values = [1,2,"dheeraj"]

print(values[2])        #dheeraj
print(values[-1])       #dheeraj
print(values[0:2])     #[1,2]
values.insert(3,"mishra")
print(values)           #[1,2,'dheeraj','mishra']

Q: What is Dictionary in Python ?

Ans:
Dictionaries are used to store data values in key:value pairs.
A dictionary is a collection which is ordered*, changeable and do not allow duplicates.
dict = {
   "brand": "Ford",
   "model": "Mustang",
   "year": 1964
}
print(dict["brand"])  #output - Ford

#Dictionary
dict={}   //initialize
dict[1]="dj"
dict["a"]=2023

print(dict[1])           #dj
print(dict["a"])   #2023

Q: How if-else condition works in Python?

Ans:
#if else condition

A="Dheeraj mishra"

if A=="Dheeraj mishra":
    print("matches")
    print("second line")
else:
    print("else condition")
print("this is example for if else condition")


Q: How for loop works in Python?

Ans:
            obj=[2,3,4,9,1]

        for i in obj:
            if i%2==0:
                print("Even")
            else:
                print("Odd")

sum=0
for k in range(1,4):
sum=
sum+k
print("{},{}".format("Sum is:", sum))
print("Sum is:" + str(sum))

Q: How OOPs implemented in python ?

Ans:
class car:  

    def __init__(self,modelname, year):   # this is constructor this=self in py
        self.modelname = modelname  
        self.year = year  

    def display(self):  
        print(self.modelname,self.year)  
  
c1 = car("Toyota", 2016)  
c1.display()
  
Output: Toyota 2016


Q: WAP to add all int from array in python

Ans:

   list =[2,3,4,9,1]

   sum=0
 
   for k in list :
    sum = sum+k
   print("{},{}".format("Sum is",sum))
   print("Sum is:" + str(sum))           // 19

 
# Iterating the index
# same as 'for i in range(len(list))'
   length = len(list)
   for i in range(length):
    print(list[i])

Q: WAP to add all int from array in python

Ans:

1.  string_name = "Dheeraj"
 
  # string_name[start:end:step]
  for element in string_name[0:5:1]:
    print(element, end =' ') //Dheer

2 . string_name = "GEEKS"

# slicing the string in reverse fashion
for element in string_name[::-1]:
    print(element, end=' ')

3.
# Iterate over the string
for element in string_name:
    print(element, end=' ')
print("\n")
 
 4.
string_name = "Dheeraj"
 
# Iterate over index
for element in range(0, len(string_name)):
    print(string_name[element])



Q:How to implement OOPs concept in Python ?

Ans:
Python is an object-oriented programming language that supports various OOP concepts. Here are some ways to implement OOP concepts in Python:

Classes and Objects: Use classes to define objects with properties and methods. Classes define the blueprint for objects, while objects are instances of a class. Here's an example:

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

    def introduce(self):
        print("My name is " + self.name + " and I am " + str(self.age) + " years old.")

person1 = Person("John", 30)
person1.introduce()

Inheritance: Use inheritance to create new classes that inherit the properties and methods of existing classes. This allows you to reuse code and create more specialized classes. Here's an example:

class Employee(Person):
    def __init__(self, name, age, salary):
        super().__init__(name, age)
        self.salary = salary

    def introduce(self):
        super().introduce()
        print("My salary is " + str(self.salary))

employee1 = Employee("Jane", 25, 50000)
employee1.introduce()

Polymorphism: Use polymorphism to define methods with the same name in different classes. This allows you to use the same method name in different contexts. Here's an example:

class Shape:
    def area(self):
        pass

class Square(Shape):
    def __init__(self, side):
        self.side = side

    def area(self):
        return self.side * self.side

class Circle(Shape):
    def __init__(self, radius):
        self.radius = radius

    def area(self):
        return 3.14 * self.radius * self.radius

square1 = Square(5)
circle1 = Circle(3)
print("Area of square:", square1.area())
print("Area of circle:", circle1.area())

Encapsulation: Use encapsulation to restrict access to properties and methods of an object. This protects the object from unwanted changes or access from external code. Here's an example:

class BankAccount:
    def __init__(self, account_no, balance):
        self.__account_no = account_no
        self.__balance = balance

    def deposit(self, amount):
        self.__balance += amount

    def withdraw(self, amount):
        if self.__balance >= amount:
            self.__balance -= amount
        else:
            print("Insufficient balance")

    def get_balance(self):
        return self.__balance

account1 = BankAccount("123456789", 5000)
account1.deposit(1000)
account1.withdraw(2000)
print("Balance:", account1.get_balance())

These are some examples of implementing OOP concepts in Python. By using OOP concepts, you can create more organized, maintainable, and reusable code.

Q: Highlight key difference in java and python ? 

Ans:

1. Static Typing vs. Dynamic Typing
Java: Statically typed – You need to define the data type of variables at compile time.
Example:
java
int num = 10; // Type declared

Python: Dynamically typed – Variables don’t require an explicit data type declaration.
Example:

num = 10  # Type is inferred at runtime
Difference: Java enforces strict type declarations, leading to fewer runtime errors, while Python's flexibility allows faster development but may lead to more runtime errors if types are mismanaged.

2. Access Modifiers

Java: Provides access modifiers (private, protected, public) to control the scope of class members.
Example:
java
public class MyClass {
    private int id;
    protected String name;
    public void display() { }
}

Python: Does not have formal access modifiers. However, you can use naming conventions (_name for protected and __name for private).
Example:

class MyClass:
    def __init__(self):
        self._id = 1                  # Protected (convention)
        self.__name = "A"       # Private (name mangling)

Difference: Java explicitly enforces access control through keywords, while Python relies on conventions and name mangling.

3. Interfaces and Multiple Inheritance

Java: Supports interfaces (abstract types that only declare methods) but does not support multiple inheritance (a class cannot inherit from more than one class).
Example:
java
interface Drawable {
    void draw();
}

class Circle implements Drawable {
    public void draw() {
        System.out.println("Drawing a circle");
    }
}

Python: Supports multiple inheritance (a class can inherit from more than one class) and doesn’t require interfaces.
Example:
class A:
    def method_a(self):
        print("Method A")

class B:
    def method_b(self):
        print("Method B")

class C(A, B):
    pass

obj = C()
obj.method_a()  # Inherited from class A
obj.method_b()  # Inherited from class B

Difference: Java uses interfaces for enforcing method signatures, while Python supports multiple inheritance, making it more flexible but prone to complexity issues like the diamond problem.

4. Memory Management and Garbage Collection
Java: Handles automatic garbage collection using a managed heap, but you cannot control memory directly (e.g., no pointers).
Example:

System.gc(); // Suggests garbage collection

Python: Uses automatic memory management with reference counting and garbage collection. Memory management can be slightly more explicit with features like object reference counting and the gc module.
Example:

import gc
gc.collect()  # Forces garbage collection

Difference: Both use garbage collection, but Python provides a more transparent view of memory management (reference counting), while Java manages this behind the scenes.

5. Functional Programming Features

Java: Added functional programming features such as lambda expressions and the Stream API starting from Java 8.
Example:

List<Integer> numbers = Arrays.asList(1, 2, 3, 4);
numbers.stream().map(n -> n * 2).forEach(System.out::println);

Python: Natively supports functional programming from the beginning with features like lambdas, map(), filter(), reduce(), and list comprehensions.
Example:
numbers = [1, 2, 3, 4]
doubled = map(lambda n: n * 2, numbers)
print(list(doubled))

Difference: Python has more natural functional programming support, while Java incorporated functional programming features later (from Java 8 onwards).

6. Exception Handling

Java: Differentiates between checked and unchecked exceptions. Checked exceptions must be either handled using try-catch or declared in the method signature.
Example:
public void myMethod() throws IOException {
    throw new IOException("Checked exception");
}

Python: Only has unchecked exceptions. All exceptions are treated uniformly, and you don’t need to declare them in the function signature.
Example:
def my_method():
    raise IOError("Unchecked exception")
Difference: Java requires explicit handling of checked exceptions, ensuring that certain exceptions are handled during compile time, whereas Python’s exception system is simpler but entirely relies on the developer to handle exceptions.

7. Generics vs. Duck Typing

Java: Uses generics to enforce type safety, especially with collections (introduced in Java 5).
Example:
List<String> list = new ArrayList<>();
list.add("Hello");

Python: Relies on duck typing, meaning that if an object behaves like a type (has the required methods or attributes), it is considered that type.
Example:
def process(item):
    item.speak()  # Duck typing: as long as 'item' has a 'speak' method, it works
Difference: Java ensures type safety with generics, while Python emphasizes flexibility with duck typing, which can lead to potential runtime errors if used incorrectly.

8. Multithreading and Concurrency

Java: Provides native multithreading and concurrency support with threads and the java.util.concurrent package.
Example:
class MyThread extends Thread {
    public void run() {
        System.out.println("Thread is running");
    }
}

Python: Provides multithreading via the threading module but is limited by the Global Interpreter Lock (GIL), which restricts true parallelism in CPU-bound tasks. However, Python excels in I/O-bound tasks with multithreading.
Example:

import threading
def run():
    print("Thread is running")

t = threading.Thread(target=run)
t.start()
Difference: Java offers true parallelism for both CPU-bound and I/O-bound tasks, while Python’s GIL limits multithreading effectiveness in CPU-bound processes.

9. File I/O Handling

Java: Uses File and BufferedReader/Writer classes for file operations, requiring more boilerplate code.

try (BufferedReader br = new BufferedReader(new FileReader("file.txt"))) {
    String line;
    while ((line = br.readLine()) != null) {
        System.out.println(line);
    }
}

Python: Has simpler and more intuitive file I/O handling using the built-in open() function.
Example:
with open("file.txt", "r") as file:
    for line in file:
        print(line)
Difference: Python's file handling is more concise and readable compared to Java's more verbose approach.

10. Lambda Expressions and Anonymous Functions

Java: Supports lambda expressions (introduced in Java 8) but does not have full support for anonymous functions beyond that.
Example:
(int x, int y) -> x + y;

Python: Supports anonymous functions with the lambda keyword and uses it widely in functional programming.
Example:
add = lambda x, y: x + y
Difference: Python uses lambdas more freely, while Java uses them in a more restricted and specific manner, mostly for functional interfaces.


Q: List out all the operation related to List, tuple and dictionary .

List:

  • A list is a mutable (changeable) ordered sequence of elements.

List Creation

my_list = [1, 2, 3, 4, 5]

Operations on Lists

Operation/FunctionUseExample
append()Adds an element to the end of the list.my_list.append(6) => [1, 2, 3, 4, 5, 6]
insert(index, elem)Inserts an element at the specified index.my_list.insert(1, 10) => [1, 10, 2, 3, 4, 5]
extend(list)Extends the list by appending elements from another list.my_list.extend([7, 8]) => [1, 2, 3, 4, 5, 7, 8]
pop([index])Removes and returns the element at the specified index (or the last item if index is not given).my_list.pop() => [1, 2, 3, 4]
remove(elem)Removes the first occurrence of the element.my_list.remove(3) => [1, 2, 4, 5]
index(elem)Returns the index of the first occurrence of the element.my_list.index(3) => 2
count(elem)Returns the count of occurrences of the element.my_list.count(3) => 1
reverse()Reverses the list in place.my_list.reverse() => [5, 4, 3, 2, 1]
sort()Sorts the list in ascending order.my_list.sort() => [1, 2, 3, 4, 5]
len(list)Returns the length of the list.len(my_list) => 5
max(list)Returns the largest element.max(my_list) => 5
min(list)Returns the smallest element.min(my_list) => 1
sum(list)Returns the sum of all elements.sum(my_list) => 15
clear()Removes all elements from the list.my_list.clear() => []
copy()Returns a shallow copy of the list.new_list = my_list.copy() => new_list == my_list
list comprehensionEfficiently create a new list based on another list or condition.[x**2 for x in my_list] => [1, 4, 9, 16, 25]

2. Tuple Operations and Functions

Tuple:

  • A tuple is an immutable ordered sequence of elements.

Tuple Creation

my_tuple = (1, 2, 3, 4, 5)

Operations on Tuples

Operation/FunctionUseExample
count(elem)Returns the count of occurrences of the element.my_tuple.count(3) => 1
index(elem)Returns the index of the first occurrence of the element.my_tuple.index(4) => 3
len(tuple)Returns the length of the tuple.len(my_tuple) => 5
max(tuple)Returns the largest element in the tuple.max(my_tuple) => 5
min(tuple)Returns the smallest element in the tuple.min(my_tuple) => 1
sum(tuple)Returns the sum of all elements in the tuple.sum(my_tuple) => 15
tuple()Converts an iterable (e.g., list) to a tuple.tuple([1, 2, 3]) => (1, 2, 3)
in operatorChecks if an element exists in the tuple.3 in my_tuple => True
+ (Concatenation)Combines two tuples into one.(1, 2) + (3, 4) => (1, 2, 3, 4)
* (Repetition)Repeats the tuple n times.(1, 2) * 3 => (1, 2, 1, 2, 1, 2)
slicingRetrieves elements using start:stop
.
my_tuple[1:4] => (2, 3, 4)
tuple comprehensionEfficiently create new tuples (though immutable).tuple(x**2 for x in my_tuple) => (1, 4, 9, 16, 25)

3. Dictionary Operations and Functions

Dictionary:

  • A dictionary is an unordered collection of key-value pairs. Keys must be unique and immutable.

Dictionary Creation

my_dict = {"name": "Alice", "age": 25, "city": "New York"}

Operations on Dictionaries

Operation/FunctionUseExample
get(key, default)Returns the value for the specified key; returns default if key is not found.my_dict.get('age') => 25
items()Returns a view object of dictionary’s key-value pairs.my_dict.items() => dict_items([('name', 'Alice'), ...])
keys()Returns a view object of dictionary’s keys.my_dict.keys() => dict_keys(['name', 'age', 'city'])
values()Returns a view object of dictionary’s values.my_dict.values() => dict_values(['Alice', 25, 'New York'])
update(other_dict)Updates the dictionary with elements from another dictionary.my_dict.update({"country": "USA"}) => {'name': ..., 'country': 'USA'}
pop(key)Removes and returns the value associated with the key.my_dict.pop('age') => 25
popitem()Removes and returns the last key-value pair.my_dict.popitem() => ('city', 'New York')
clear()Removes all elements from the dictionary.my_dict.clear() => {}
copy()Returns a shallow copy of the dictionary.new_dict = my_dict.copy() => new_dict == my_dict
setdefault(key, value)Returns the value of the key if it exists; otherwise sets it to value.my_dict.setdefault('age', 30) => 25
in operatorChecks if a key exists in the dictionary.'age' in my_dict => True
delDeletes a key-value pair.del my_dict['name'] => {'age': 25, 'city': 'New York'}
dict comprehensionEfficiently create dictionaries based on existing ones.{k: v*2 for k, v in my_dict.items() if isinstance(v, int)} => {'age': 50}


Q: String related programs

Q: Reverse a String Without Using Built-In Functions
Write a function that takes a string and returns it reversed without using Python's built-in reverse functions.

def reverse_string(s):
    reversed_str = ""
    for char in s:
        reversed_str = char + reversed_str
    return reversed_str

# Example usage
print(reverse_string("hello"))  # Output: "olleh"

Q: Check if a String is a Palindrome
Write a function to check if a given string is a palindrome (a string that reads the same forwards and backwards).

def is_palindrome(s):
    return s == s[::-1]

# Example usage
print(is_palindrome("racecar"))  # Output: True
print(is_palindrome("hello"))    # Output: False

Q: Find the First Non-Repeated Character in a String
Given a string, find the first character that does not repeat.

def first_non_repeated_char(s):
    for char in s:
        if s.count(char) == 1:
            return char
    return None

# Example usage
print(first_non_repeated_char("swiss"))  # Output: "w"

Q: Count the Number of Vowels and Consonants in a String
Write a function that counts the number of vowels and consonants in a string.

def count_vowels_consonants(s):
    vowels = {'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'}
    v_count, c_count = 0, 0

    for char in s:
        if char in vowels:
            v_count += 1
        elif char.isalpha():  # Ensures only alphabetic consonants are counted
            c_count += 1

    return v_count, c_count

# Example usage
print(count_vowels_consonants("hello world"))  # Output: (3, 7)

Q: Remove Duplicate Characters from a String
Write a function that removes duplicate characters from a string while maintaining the original order.

def remove_duplicates(s):
    result = ""
    seen = set()
    for char in s:
        if char not in seen:
            result += char
            seen.add(char)
    return result

# Example usage
print(remove_duplicates("automation"))  # Output: "automin"

Q: Find the Most Frequent Character in a String
Write a function to find the most frequently occurring character in a string.

from collections import Counter

def most_frequent_char(s):
    counter = Counter(s)
    return counter.most_common(1)[0][0]

# Example usage
print(most_frequent_char("programming"))  # Output: "g"

Q: Check if Two Strings are Anagrams
Write a function that checks if two strings are anagrams (contain the same characters in the same frequency).

def are_anagrams(s1, s2):
    return sorted(s1) == sorted(s2)

# Example usage
print(are_anagrams("listen", "silent"))  # Output: True
print(are_anagrams("hello", "world"))    # Output: False

Q: Count Substring Occurrences in a String
Write a function to count occurrences of a substring within a string.

def count_substring(s, sub):
    return s.count(sub)

# Example usage
print(count_substring("hello hello hello", "hello"))  # Output: 3

Q: Replace All Spaces with a Specific Character
Write a function to replace all spaces in a string with a specific character.

def replace_spaces(s, char):
    return s.replace(" ", char)

# Example usage
print(replace_spaces("hello world", "_"))  # Output: "hello_world"

Q: Find All Permutations of a Given String
Write a function to return all permutations of a string.

from itertools import permutations

def string_permutations(s):
    return [''.join(p) for p in permutations(s)]

# Example usage
print(string_permutations("abc"))  
# Output: ['abc', 'acb', 'bac', 'bca', 'cab', 'cba']


Q: Perform some actions on Collections type

Ans:
===========LIST=================
list = ["Apple", "Banana", "Cherry"]
print("List:", list)
print("First element:", list[0])
list.remove("Banana")
print("After removal:", list)
for fruit in list:
    print(fruit)
===========MAP/Dictionary====================

map = {"Apple": 1, "Banana": 2, "Cherry": 3}
print("Dictionary:", map)
print("Value for Banana:", map["Banana"])

del map["Banana"]
print("After removal:", map)

for key in map:
    print("Key:", key, ", Value:", map[key])

==========SET====================

set_ = {"Apple", "Banana", "Cherry"}
print("Set:", set_)
set_.remove("Banana")
print("After removal:", set_)

if "Apple" in set_:
    print("Set contains Apple")

for fruit in set_:
    print(fruit)



  • For lists, use append().
  • For tuples, you cannot use append(), but you can create a new tuple by concatenating elements.
  • For dictionaries, you can't use append(), but you can add new key-value pairs directly.



  • Comments