0% found this document useful (0 votes)
7 views

Pythonass

Uploaded by

gta579035
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

Pythonass

Uploaded by

gta579035
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 8

PYTHON ASSIGNMENT

Name=Dhruvin J Soni

PRN=1062212146

Q.1 Create a program that reads a CSV file and extracts specific columns, then writes
the extracted data to a new CSV file.
import csv

def extract_columns(input_file, output_file, columns):

# Open files

with open(input_file, 'r') as infile, open(output_file, 'w') as outfile:

reader = csv.reader(infile)

writer = csv.writer(outfile)

# Write header (assuming your input file has a header row)

writer.writerow(columns)

# Extract and write data

for row in reader:

# Filter row based on column names

extracted_row = [row[i] for i in range(len(columns)) if columns[i] in row]

writer.writerow(extracted_row)

# Example usage (replace with your file paths and columns)

input_file = "your_data.csv"

output_file = "extracted_data.csv"
columns_to_extract = ["col1", "col3"]

extract_columns(input_file, output_file, columns_to_extract)

print("Extracted data written to extracted_data.csv")

input_file = 'sample.csv'

output_file = 'output.csv'

columns_to_extract = [‘industry’]

extract_columns(input_file, output_file, columns_to_extract)

OUTPUT

2. Develop a program that reads a JSON file and converts it to a Python dictionary. Solution
-> import json

def json_to_dict(json_file):

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

data = json.load(file)

return data

json_to_dict(data.json)
OUTPUT

Develop a function that takes a list of integers and returns a new list containing only
the unique elements, preserving their order.

def unique_elements(nums):

seen = set()

unique_list = []

for num in nums:

if num not in seen:

seen.add(num)

unique_list.append(num)

return unique_list

# Example usage
numbers = [1, 2, 3, 1, 4, 5, 2]
unique_numbers = unique_elements(numbers)
print(f"Original list: {numbers}")
print(f"Unique elements: {unique_numbers}")

OUTPUT
Develop a program to find the factorial of a given number using recursion
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n-1)

# Example usage
number = 5
result = factorial(number)
print(f"The factorial of {number} is: {result}")

OUTPUT

Write a Python program to count the number of lines, words, and characters in a text
file.

def count_lines_words_chars(filename):

try:
with open(filename, 'r') as f:
lines = sum(1 for _ in f) # Count lines using generator expression
f.seek(0) # Reset file pointer to beginning
words = len(f.read().split())
chars = len(f.read())
return lines, words, chars
except FileNotFoundError:
print(f"Error: File '{filename}' not found.")
return 0, 0, 0

# Example usage
filename = "sample.txt" # Replace with your file name
num_lines, num_words, num_chars = count_lines_words_chars(filename)

if num_lines > 0:
print(f"File: {filename}")
print(f"Number of lines: {num_lines}")
print(f"Number of words: {num_words}")
print(f"Number of characters: {num_chars}")

OUTPUT

Q.6 Implement a stack and use it to check if a given string of parentheses is balanced.

def is_balanced(expr):
stack = []
for char in expr:
if char in "([{":
stack.append(char)
elif char in ")]}":
if not stack:
return False
top = stack.pop()
if not matches(top, char):
return False
return not stack

def matches(opening, closing):


return (opening == "(" and closing == ")") or \
(opening == "[" and closing == "]") or \
(opening == "{" and closing == "}")

# Test cases
print(is_balanced("((()))")) # True
print(is_balanced("(()))")) # False
print(is_balanced("()")) # True
print(is_balanced(")(")) # False
OUTPUT

Q.7Write a program to find the longest consecutive sequence of numbers in a list.


def longest_consecutive(nums):
nums.sort()
curr_length = 1
max_length = 0
for i in range(1, len(nums)):
if nums[i] == nums[i-1] + 1:
curr_length += 1
else:
max_length = max(max_length, curr_length)
curr_length = 1
return max(max_length, curr_length)

# Example usage
nums = [5, 4, 200, 1, 3, 2]
length = longest_consecutive(nums)
print(f"Length of longest consecutive sequence: {length}")
Q.8 Create a program that reads an integer from the user and handles the ValueError if
the input is not an integer
try:
a=int(input("Enter an integer:"))
except ValueError:
print("Invalid Input")

Write a function that divides two numbers and handles the ZeroDivisionError.
def div(a,b):
try:
c=a/b
except ZeroDivisionError:
print("Division by zero not possible")
else:
print(c)

div(10,0)

Q 10 Develop a program that opens a file and handles FileNotFoundError if the file
does not exist
def open_file(filename):
try:
# Attempt to open the specified file in read mode ('r').
file = open(filename, 'r')
# Read the contents of the file and store them in the 'contents' variable.
contents = file.read()
# Print a message to indicate that the file contents will be displayed.
print("File contents:")
# Print the contents of the file.
print(contents)
# Close the file to release system resources.
file.close()
except FileNotFoundError:
# Handle the exception if the specified file is not found.
print("Error: File not found.")

# Usage
# Prompt the user to input a file name and store it in the 'file_name' variable.
file_name = input("Input a file name: ")
# Call the open_file function with the provided file name.
open_file(file_name)

OUTPUT

You might also like