Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
18 views

Python FAT2

Uploaded by

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

Python FAT2

Uploaded by

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

Python FAT-2 Questions

Note: In order to submit the assignment, make a pdf with the code and output
screen.

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

def extract_columns(input_file, output_file, columns):


with open(input_file, 'r', newline='') as infile, open(output_file, 'w',
newline='') as outfile:
reader = csv.DictReader(infile)
writer = csv.DictWriter(outfile, fieldnames=columns)
writer.writeheader()
for row in reader:
extracted_row = {col: row[col] for col in columns}
writer.writerow(extracted_row)

# Example usage:
input_file = 'industry.csv'
output_file = 'output.csv'
columns_to_extract = [‘industry’]

extract_columns(input_file, output_file, columns_to_extract)


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

# Example usage:
json_file = 'Downloads/example_1.json'
result = json_to_dict(json_file)
print(result) # This will print the converted Python dictionary

3. Develop a function that takes a list of integers and returns a new list containing
only the unique elements, preserving their order.
Solution ->
def unique_elements(input_list):
unique_list = []
seen = set() # To keep track of elements seen so far
for item in input_list:
if item not in seen:
unique_list.append(item)
seen.add(item)
return unique_list

# Example usage:
input_list = [1, 2, 3, 4, 2, 3, 5, 1]
result = unique_elements(input_list)
print(result)

4. Develop a program to find the factorial of a given number using recursion.


Solution ->
def factorial(n):
# Base case: factorial of 0 or 1 is 1
if n == 0 or n == 1:
return 1
# Recursive case: factorial of n is n * factorial(n-1)
else:
return n * factorial(n - 1)

# Example usage:
num = 5
print("Factorial of", num, "is:", factorial(num))

5. Write a Python program to count the number of lines, words, and characters in
a text file.
Solution ->
def count_file_stats(file_path):
line_count = 0
word_count = 0
char_count = 0

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


for line in file:
# Counting lines
line_count += 1
# Counting words
words = line.split()
word_count += len(words)
# Counting characters
char_count += len(line)

return line_count, word_count, char_count

# Example usage:
file_path = 'sample.txt'
lines, words, characters = count_file_stats(file_path)
print("Number of lines:", lines)
print("Number of words:", words)
print("Number of characters:", characters)
6. Implement a stack and use it to check if a given string of parentheses is
balanced.
Solution ->
class Stack:
def __init__(self):
self.items = []

def is_empty(self):
return self.items == []

def push(self, item):


self.items.append(item)

def pop(self):
if not self.is_empty():
return self.items.pop()
else:
return None

def peek(self):
if not self.is_empty():
return self.items[-1]
else:
return None

def is_balanced(parentheses):
stack = Stack()
for char in parentheses:
if char in '([{':
stack.push(char)
elif char in ')]}':
if stack.is_empty():
return False
elif (char == ')' and stack.peek() == '(') or \
(char == ']' and stack.peek() == '[') or \
(char == '}' and stack.peek() == '{'):
stack.pop()
else:
return False
return stack.is_empty()

# Example usage:
parentheses_str = "[{()}]"
if is_balanced(parentheses_str):
print("The parentheses are balanced.")
else:
print("The parentheses are not balanced.")

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


Solution- >
def longest_consecutive_sequence(nums):
if not nums:
return []

nums.sort()
longest_sequence = [nums[0]]
current_sequence = [nums[0]]

for i in range(1, len(nums)):


if nums[i] == nums[i - 1] + 1:
current_sequence.append(nums[i])
else:
if len(current_sequence) > len(longest_sequence):
longest_sequence = current_sequence
current_sequence = [nums[i]]

if len(current_sequence) > len(longest_sequence):


longest_sequence = current_sequence

return longest_sequence

# Example usage:
nums = [100, 4, 200, 1, 3, 2, 5, 6, 7, 8, 9]
result = longest_consecutive_sequence(nums)
print("Longest consecutive sequence:", result)
8. Create a program that reads an integer from the user and handles the ValueError
if the input is not an integer.
def read_integer_from_user():
while True:
try:
user_input = input("Please enter an integer: ")
user_integer = int(user_input)
return user_integer
except ValueError:
print("Invalid input! Please enter an integer.")

# Example usage:
user_integer = read_integer_from_user()
print("You entered:", user_integer)

9. Write a function that divides two numbers and handles the ZeroDivisionError.
Solution ->
def safe_divide(a, b):
try:
result = a / b
return result
except ZeroDivisionError:
print("Error: Division by zero is not allowed.")
return None

# Example usage:
numerator = 10
denominator = 0
result = safe_divide(numerator, denominator)
if result is not None:
print("Result of division:", result)
10. Develop a program that opens a file and handles FileNotFoundError if the file
does not exist.
Solution ->
def open_file(file_path):
try:
with open(file_path, 'r') as file:
contents = file.read()
print("File contents:")
print(contents)
except FileNotFoundError:
print("Error: File not found.")

# Example usage:
file_path = 'nonexistent_file.txt'
open_file(file_path)

You might also like