0% found this document useful (0 votes)
26 views9 pages

Class 12 Python Programs Collection

Uploaded by

TECHNICAL GAMER
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)
26 views9 pages

Class 12 Python Programs Collection

Uploaded by

TECHNICAL GAMER
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

Introduction

This document contains a collection of 20+ Python programs based on the concepts taught in Class

12.

These programs cover various topics such as basic algorithms, object-oriented programming (OOP),

data structures,

file handling, and libraries such as NumPy, Pandas, and Matplotlib.

The programs are numbered for easy reference and demonstrate the core concepts required in

Class 12 computer science and informatics practices.


Certificate

This is to certify that Pranjal Agarwal, a student of Class 12, has successfully completed the

development

of 20+ Python programs based on the curriculum for Class 12 Computer Science and Informatics

Practices.

The programs have been created to demonstrate proficiency in various programming concepts.
Acknowledgement

I would like to express my sincere gratitude to my teachers and mentors who guided me throughout

the process of learning Python programming. Their support and encouragement were instrumental

in completing this project.

Special thanks to my classmates and family members for their constant motivation.
Program 1: Prime Number Check

def is_prime(n):

if n <= 1:

return False

for i in range(2, int(n ** 0.5) + 1):

if n % i == 0:

return False

return True

print(is_prime(29))

Program 2: Fibonacci Series

def fibonacci(n):

fib_series = [0, 1]

for i in range(2, n):

fib_series.append(fib_series[-1] + fib_series[-2])

return fib_series

print(fibonacci(10))

Program 3: Sum of Digits

def sum_of_digits(n):

if n == 0:

return 0

return n % 10 + sum_of_digits(n // 10)

print(sum_of_digits(1234))

Program 4: Factorial Using Recursion

def factorial(n):

if n == 0:
return 1

return n * factorial(n - 1)

print(factorial(5))

Program 5: Simple Calculator

def calculator(a, b, operation):

if operation == '+':

return a + b

elif operation == '-':

return a - b

elif operation == '*':

return a * b

elif operation == '/':

return a / b

print(calculator(10, 5, '+'))

Program 6: Count Vowels and Consonants

def count_vowels_consonants(string):

vowels = "aeiouAEIOU"

v_count = sum(1 for char in string if char in vowels)

c_count = len([char for char in string if [Link]() and char not in vowels])

return v_count, c_count

print(count_vowels_consonants("Hello World"))

Program 7: Reverse a String

def reverse_string(s):

return s[::-1]

print(reverse_string("hello"))
Program 8: Palindrome Checker

def is_palindrome(s):

return s == s[::-1]

print(is_palindrome("radar"))

Program 9: Sorting a List

def sort_list(lst):

return sorted(lst)

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

Program 10: Remove Duplicates from List

def remove_duplicates(lst):

return list(set(lst))

print(remove_duplicates([1, 2, 2, 3, 4, 4, 5]))

Program 11: Frequency Counter in List

from collections import Counter

def frequency_counter(lst):

return Counter(lst)

print(frequency_counter([1, 2, 2, 3, 4, 4, 5]))

Program 12: File Read and Write

def read_write_file():

with open('[Link]', 'r') as infile, open('[Link]', 'w') as outfile:

data = [Link]()

[Link](data)

# Note: Ensure '[Link]' file is present.

Program 13: Word and Line Count in File


def count_words_lines(filename):

with open(filename, 'r') as file:

lines = [Link]()

word_count = sum(len([Link]()) for line in lines)

return len(lines), word_count

print(count_words_lines("[Link]")) # Note: Ensure '[Link]' file is present.

Program 14: Student Class

class Student:

def __init__(self, name, age, grade):

[Link] = name

[Link] = age

[Link] = grade

student1 = Student("John", 16, 'A')

print([Link], [Link], [Link])

Program 15: Bank Account Class

class BankAccount:

def __init__(self, owner, balance=0):

[Link] = owner

[Link] = balance

def deposit(self, amount):

[Link] += amount

def withdraw(self, amount):

if amount > [Link]:

return "Insufficient funds"

[Link] -= amount
account1 = BankAccount("Alice", 1000)

[Link](500)

print([Link])

Program 16: Stack Implementation

class Stack:

def __init__(self):

[Link] = []

def push(self, item):

[Link](item)

def pop(self):

return [Link]()

stack = Stack()

[Link](1)

[Link](2)

print([Link]())

Program 17: Binary Search

def binary_search(arr, target):

left, right = 0, len(arr) - 1

while left <= right:

mid = (left + right) // 2

if arr[mid] == target:

return mid

elif arr[mid] < target:

left = mid + 1

else:
right = mid - 1

return -1

print(binary_search([1, 2, 3, 4, 5], 3))

Program 18: Array Creation and Manipulation

import numpy as np

array = [Link]([1, 2, 3])

print(array * 2)

Program 19: Line Plot Example

import [Link] as plt

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

y = [2, 4, 6, 8, 10]

[Link](x, y)

[Link]('X-axis')

[Link]('Y-axis')

[Link]('Line Plot')

[Link]()

Program 20: Matrix Multiplication in NumPy

import numpy as np

def matrix_multiplication():

A = [Link]([[1, 2], [3, 4]])

B = [Link]([[5, 6], [7, 8]])

result = [Link](A, B)

return result

print(matrix_multiplication())

Common questions

Powered by AI

The `factorial` function employs recursion by defining `factorial(n)` to call itself with the argument `n-1` until `n` is zero, at which point it returns 1. While this recursion is conceptually simple and elegant, it can impact computational efficiency negatively by consuming more memory through call stack usage compared to an iterative approach, especially for large values of `n`. Thus, it may not be optimal for factorial calculations without tail call optimization, which is not present in Python.

The `calculator` function performs basic arithmetic operations between two numbers `a` and `b` based on the specified `operation`. It can add, subtract, multiply, or divide depending on whether the `operation` parameter is '+', '-', '*', or '/' respectively. It returns the result of the operation.

NumPy's `dot` function performs matrix multiplication, which involves taking the dot product of rows of the first matrix with columns of the second. This method is computationally efficient due to NumPy's implementation in C and its ability to handle large arrays in memory efficiently. Matrix multiplication is fundamental in scientific computing, including computer graphics, simulations, and solving linear equations.

The `binary_search` function enhances search efficiency by using a divide-and-conquer approach that reduces the search interval by half with each step. It starts with the middle element of a sorted array. If this matches the target, it returns the index. If the target is smaller, the search continues in the left subarray; if larger, in the right subarray. This method significantly reduces the number of elements compared to a linear search, operating in logarithmic time complexity, O(log n)

The `Student` class illustrates key object-oriented programming concepts such as encapsulation and data abstraction. By defining attributes like `name`, `age`, and `grade` within a class, it encapsulates student data and methods related to them, creating a clear interface for object manipulation. This approach allows for managing complexity through modular programming and provides a blueprint to instantiate multiple student objects consistently.

The Python program demonstrates file handling by using context managers (`with` statement) to open and manage file resources efficiently. It opens 'input.txt' for reading and 'output.txt' for writing. The context manager ensures the files are properly closed after operations, reducing resource leakage risks. The program reads the data from the input file and writes it to the output file, showcasing basic file manipulation techniques.

The `is_prime` function checks if a number `n` is less than or equal to 1; if so, it returns `False` as such numbers are not prime. For numbers greater than 1, it iteratively checks divisibility of `n` by any number from 2 up to the square root of `n`. If `n` is divisible by any of these numbers, the function returns `False`, indicating `n` is not a prime number. Otherwise, it returns `True` for prime numbers.

The `remove_duplicates` function uses a set to eliminate duplicates from a list, taking advantage of the set's property of allowing only unique elements. It converts the list into a set to remove duplicates and then back to a list to maintain the original data structure type. This approach is efficient due to the constant time complexity of element insertion in sets.

The `Stack` class implements a basic stack data structure with two main operations: `push`, which adds an item to the end of the list representing the stack, and `pop`, which removes and returns the last item from the stack. This LIFO (Last In, First Out) structure is significant in data manipulation as it is used extensively in algorithms involving history mechanisms, recursive function management, and syntax parsing.

The `count_vowels_consonants` function uses list comprehensions and string membership tests to count vowels by checking each character against a predefined set of vowels and similarly counting consonants by ensuring characters are alphabetic and not vowels. This operation is significant in text analysis as it helps in evaluating linguistic data characteristics, such as readability and phonetic content distribution, which can be crucial in fields like linguistics and natural language processing.

You might also like