Appearance
question:Develop a Python function to calculate the total size of a directory including all subdirectories and files. This function should use the `os` and `os.path` modules. The function should return the total size in bytes.
answer:import os def get_directory_size(directory): Returns the total size of the directory including all subdirectories and files in bytes. :param directory: str, path of the directory :return: int, total size in bytes total_size = 0 for dirpath, dirnames, filenames in os.walk(directory): for filename in filenames: filepath = os.path.join(dirpath, filename) if os.path.isfile(filepath): total_size += os.path.getsize(filepath) return total_size
question:Design a Python function that calculates the sum of two numbers. How can I ensure that this function handles different data types, such as integers, floats, and strings that represent numbers?
answer:def sum_numbers(a, b): Returns the sum of a and b. Handles integers, floats, and strings representing numbers. try: # Convert input to float if they aren't already a = float(a) b = float(b) return a + b except ValueError: raise ValueError("Both inputs must be numeric or strings representing numbers.")
question:How can I develop a simple artificial neural network (ANN) for a classification task using PyTorch?
answer:import torch import torch.nn as nn import torch.optim as optim import torch.nn.functional as F class SimpleANN(nn.Module): def __init__(self, input_size, hidden_size, output_size): super(SimpleANN, self).__init__() self.fc1 = nn.Linear(input_size, hidden_size) self.fc2 = nn.Linear(hidden_size, output_size) def forward(self, x): x = F.relu(self.fc1(x)) x = self.fc2(x) return x def train_model(model, criterion, optimizer, data_loader, num_epochs): for epoch in range(num_epochs): for inputs, labels in data_loader: optimizer.zero_grad() outputs = model(inputs) loss = criterion(outputs, labels) loss.backward() optimizer.step() def predict(model, inputs): with torch.no_grad(): outputs = model(inputs) _, predicted = torch.max(outputs, 1) return predicted
question:How can I write a Python script to process a text file and count the occurrences of each unique word, ignoring case sensitivity?
answer:def count_word_occurrences(file_path): Counts the occurrences of each unique word in a text file, ignoring case sensitivity. Args: file_path (str): Path to the text file to be processed. Returns: dict: A dictionary where the keys are words and the values are the counts of occurrences. word_count = {} with open(file_path, 'r', encoding='utf-8') as file: for line in file: words = line.strip().lower().split() for word in words: word = word.strip(".,!?"'()[]{}<>:;") if word: if word in word_count: word_count[word] += 1 else: word_count[word] = 1 return word_count