Skip to content
🤔prompts chat🧠
🔍
question:Write a function that takes an array of integers and an integer `k`, and returns the length of the longest subarray that contains exactly `k` different integers. If there is no such subarray, return 0. The function should handle edge cases where the array is empty or where `k` is zero or exceeds the number of unique integers in the array. The solution should aim to have an optimal time complexity, ideally O(n).

answer:def longest_subarray_with_k_distinct(nums, k): Returns the length of the longest subarray with exactly k distinct integers. from collections import defaultdict if not nums or k == 0 or k > len(set(nums)): return 0 max_length = 0 left = 0 freq = defaultdict(int) distinct_count = 0 for right in range(len(nums)): if freq[nums[right]] == 0: distinct_count += 1 freq[nums[right]] += 1 while distinct_count > k: freq[nums[left]] -= 1 if freq[nums[left]] == 0: distinct_count -= 1 left += 1 if distinct_count == k: max_length = max(max_length, right - left + 1) return max_length

question:設計一個函數,用於反轉文本字符串列表中的每個單詞,同時保持整體字符串的順序不變。例如,給定列表 ["這是", "一次編程", "測試"],函數應返回 ["是這", "程編次一", "試測"]。請注意,不能使用內建的反轉函數。

answer:def reverse_words_in_list(str_list): Reverses each word in the list of strings, keeping the overall string order unchanged. Parameters: str_list (list of str): List of strings to be processed. Returns: list of str: List with each word reversed. def reverse_word(word): # Create a new reversed word manually reversed_word = "" for char in word: reversed_word = char + reversed_word return reversed_word return [reverse_word(word) for word in str_list]

question:You are working on a Python project where you need to manage a collection of books in a library. Each book has attributes such as title, author, and year of publication. You are already familiar with creating classes and instance methods, but you are not sure when and how to use class methods in Python effectively. Create a class `LibraryBook` that uses class methods to keep track of all the books created. Additionally, implement a method to get the total number of books and a method to find a book by its title. Requirements: 1. Implement a `LibraryBook` class with the following attributes: title, author, year. 2. Include a class attribute to store all the book instances. 3. Create a class method to add a new book to the collection. 4. Implement a class method to get the total number of books in the collection. 5. Create a class method to find a book by its title. Demonstrate the usage of the `LibraryBook` class by adding a few book instances and calling the created class methods. Example usage: ```python book1 = LibraryBook.add_book('1984', 'George Orwell', 1949) book2 = LibraryBook.add_book('To Kill a Mockingbird', 'Harper Lee', 1960) print(LibraryBook.get_total_books()) # Output: 2 found_book = LibraryBook.find_book_by_title('1984') if found_book: print(f'Found book: {found_book.title} by {found_book.author}') ``` Ensure your implementation correctly follows the concept of class methods and proper Python conventions.

answer:class LibraryBook: A class to represent a book in a library. all_books = [] def __init__(self, title, author, year): self.title = title self.author = author self.year = year @classmethod def add_book(cls, title, author, year): Class method to add a new book to the collection. new_book = cls(title, author, year) cls.all_books.append(new_book) return new_book @classmethod def get_total_books(cls): Class method to get the total number of books in the collection. return len(cls.all_books) @classmethod def find_book_by_title(cls, title): Class method to find a book by its title from the collection. for book in cls.all_books: if book.title == title: return book return None # Demonstrate the usage of the LibraryBook class book1 = LibraryBook.add_book('1984', 'George Orwell', 1949) book2 = LibraryBook.add_book('To Kill a Mockingbird', 'Harper Lee', 1960) print(LibraryBook.get_total_books()) # Output: 2 found_book = LibraryBook.find_book_by_title('1984') if found_book: print(f'Found book: {found_book.title} by {found_book.author}') # Output: Found book: 1984 by George Orwell

question:Write a program that takes a list of integers and returns a new list where each element is the square of the original list element if it is even, and the cube if it is odd. Your solution should handle edge cases like empty lists gracefully and ensure that the output list maintains the same order as the input list. Provide code and a brief explanation of your approach.

answer:def transform_list(numbers): Takes a list of integers and returns a new list where: - each even number is squared - each odd number is cubed return [x**2 if x % 2 == 0 else x**3 for x in numbers]

Released under the chat License.

has loaded