Skip to content
🤔prompts chat🧠
🔍
question:# Coding Assessment Question Scenario As part of a data validation system, you need to implement a function that verifies if a given string is a valid identifier. A valid identifier must start with a letter (either uppercase or lowercase) or an underscore (`_`), and the remaining characters may be letters, digits (`0-9`), or underscores. Identifiers can't be empty, and they must be no longer than 100 characters. Task Implement a function `is_valid_identifier` that checks if the given input string `s` is a valid identifier according to the rules specified. Input - A single string `s` (length between 0 and 100). Output - A boolean `True` if the string `s` is a valid identifier and `False` otherwise. Constraints - The input string can contain uppercase letters (`A-Z`), lowercase letters (`a-z`), digits (`0-9`), and underscores (`_`). Examples ```python >>> is_valid_identifier("variable1") True >>> is_valid_identifier("_value") True >>> is_valid_identifier("1stValue") False >>> is_valid_identifier("Var_123") True >>> is_valid_identifier("invalid-char!") False >>> is_valid_identifier("") False ``` Implementation ```python def is_valid_identifier(s: str) -> bool: Check if the given string is a valid identifier. if not s or len(s) > 100: return False if not (s[0].isalpha() or s[0] == '_'): return False for char in s[1:]: if not (char.isalnum() or char == '_'): return False return True # Sample test cases to validate your function assert is_valid_identifier("variable1") == True assert is_valid_identifier("_value") == True assert is_valid_identifier("1stValue") == False assert is_valid_identifier("Var_123") == True assert is_valid_identifier("invalid-char!") == False assert is_valid_identifier("") == False print("All tests passed!") ```

answer:def is_valid_identifier(s: str) -> bool: Check if the given string is a valid identifier. if not s or len(s) > 100: return False if not (s[0].isalpha() or s[0] == '_'): return False for char in s[1:]: if not (char.isalnum() or char == '_'): return False return True

question:# Keyword Count in Paragraph You are provided with a text file `paragraph.txt`, containing a single paragraph of text. Your task is to find the frequency of a pre-defined set of keywords within this paragraph. # Instructions 1. Read `paragraph.txt` and extract the text. 2. Normalize the text by converting it to lowercase and removing any punctuation. 3. Define a set of keywords to search for within the paragraph. 4. Count the occurrence of each keyword in the paragraph. # Example Consider the following content in `paragraph.txt`: ``` "Python is a widely used high-level programming language for general-purpose programming. Created by Guido van Rossum and first released in 1991, Python has a design philosophy that emphasizes code readability." ``` If the set of keywords is `{"python", "programming", "design", "readability"}`: - "python" occurs 2 times - "programming" occurs 2 times - "design" occurs 1 time - "readability" occurs 1 time # Objective Write a Python function `count_keywords_in_paragraph` that takes the file path and a set of keywords as input, processes the paragraph, and returns a dictionary with the count of each keyword. ```python def count_keywords_in_paragraph(file_path: str, keywords: set) -> dict: Counts the occurrences of each keyword in the given file. :param file_path: Path to the text file containing the paragraph. :param keywords: A set of keywords to count. :return: A dictionary with keywords as keys and their counts as values. # Your implementation goes here. pass # Example usage: # result = count_keywords_in_paragraph("path_to_your_paragraph.txt", {"python", "programming", "design", "readability"}) # print(result) # Expected output: {'python': 2, 'programming': 2, 'design': 1, 'readability': 1} ``` # Constraints 1. The function should handle textual input efficiently. 2. Assume the file contains a single text paragraph. 3. The text only consists of English alphabet letters, spaces, and standard punctuation. 4. Keyword matching should be case-insensitive.

answer:import string def count_keywords_in_paragraph(file_path: str, keywords: set) -> dict: Counts the occurrences of each keyword in the given file. :param file_path: Path to the text file containing the paragraph. :param keywords: A set of keywords to count. :return: A dictionary with keywords as keys and their counts as values. # Initialize a dictionary to keep count of each keyword keyword_counts = {keyword: 0 for keyword in keywords} # Read and process the paragraph text with open(file_path, 'r') as file: paragraph = file.read().strip().lower() # Remove punctuation from the text translator = str.maketrans('', '', string.punctuation) normalized_text = paragraph.translate(translator) # Split the text into words words = normalized_text.split() # Count occurrences of each keyword for word in words: if word in keyword_counts: keyword_counts[word] += 1 return keyword_counts

question:# Coding Assessment Question **Title**: Longest Harmonious Subsequence **Context**: You are developing a feature for a data analysis tool that helps identify patterns within numerical datasets. One of the features requires finding the longest harmonious subsequence in a list of integers. A harmonious subsequence is defined as a subsequence where the difference between its maximum and minimum values is exactly 1. **Task**: Write a function `findLHS` that takes a list of integers and returns the length of the longest harmonious subsequence. **Input**: - `nums`: a list of integers. **Output**: - An integer representing the length of the longest harmonious subsequence. **Constraints**: - All integers in the list are within the range of [-10^9, 10^9]. - The length of the list is at most 10^4. **Example**: ```python nums = [1,3,2,2,5,2,3,7] print(findLHS(nums)) ``` **Expected Output**: ``` 5 ``` **Explanation**: The longest harmonious subsequence is [3, 2, 2, 2, 3]. **Notes**: - A subsequence is derived from the list by deleting some or no elements without changing the order of the remaining elements. - Consider edge cases, such as when the list is empty or has only one element. **Hint**: - You may find it helpful to use a frequency counter or dictionary to track occurrences of each number, and then look for pairs of consecutive numbers to determine the length of the potential harmonious subsequences.

answer:def findLHS(nums): Returns the length of the longest harmonious subsequence in the list of integers. if not nums: return 0 num_count = {} for num in nums: num_count[num] = num_count.get(num, 0) + 1 max_length = 0 for num in num_count: if num + 1 in num_count: current_length = num_count[num] + num_count[num + 1] max_length = max(max_length, current_length) return max_length

question:# Task Implement a function `flatten_and_filter(lst: list, threshold: int) -> list` that flattens a nested list of integers and filters out any integers that are less than or equal to a given threshold. # Input - `lst`: A list of integers, which might also contain other lists of integers nested to an arbitrary depth. - `threshold`: An integer to filter out numbers less than or equal to it. # Output - Return a flat list of integers that are greater than the threshold. # Constraints - The function should handle lists nested to arbitrary depths. - Aim for O(n) time complexity where n is the number of elements in the list. - Ensure the approach utilizes O(n) additional space, where n is the total number of elements, given that they need to be stored in the output list. # Example ```python >>> flatten_and_filter([1, [2, [3, 4], 5], 6, [7, 8]], 4) [5, 6, 7, 8] >>> flatten_and_filter([[-1, 2, [3]], 0, 4], 0) [2, 3, 4] >>> flatten_and_filter([[10, 20, [30]], [5]], 25) [30] >>> flatten_and_filter([], 3) [] ``` # Notes - Your solution should effectively traverse the nested list structure and apply the threshold filter simultaneously. - Consider edge cases such as deeply nested empty lists or lists containing only elements below the threshold.

answer:def flatten_and_filter(lst, threshold): def flatten(lst): for item in lst: if isinstance(item, list): yield from flatten(item) else: yield item return [item for item in flatten(lst) if item > threshold]

Released under the chat License.

has loaded