Selective Divisor Extraction
Identify integers within a specified range that are divisible by either 5 or 6, but exclude those divisible by both (30).
def find_special_divisors(limit=10000):
results = []
for num in range(1, limit + 1):
if (num % 5 == 0 or num % 6 == 0) and num % 30 != 0:
results.append(num)
return results
divisors = find_special_divisors(10000)
Summing Even-Indexed Elements
Compute the aggregate sum of elements situated at even indices within a given sequence.
def sum_even_index_elements(data_list):
total = 0
for idx, val in enumerate(data_list):
if idx % 2 == 0:
total += val
return total
sample_data = [10, 20, 30, 40, 50, 60]
result = sum_even_index_elements(sample_data)
Path Component Separation
Isolate the directory structure and the file designation from an absolute file path.
import os
file_path = r'C:\Projects\data\report.csv'
dir_name = os.path.dirname(file_path)
base_name = os.path.basename(file_path)
String Delimiter Splitting
Partition a text block into multiple segments based on a user-defined delimiter.
def split_by_delimiter(text, delimiter):
return text.split(delimiter)
raw_text = "apple;banana;cherry;date"
separator = ";"
fragments = split_by_delimiter(raw_text, separator)
for fragment in fragments:
print(fragment)
Whitespace Elimination
Construct a new string from an input string by entirely removing any whitespace characters.
def strip_all_spaces(input_str):
return "".join(ch for ch in input_str if not ch.isspace())
text = " Hello World Python "
cleaned_text = strip_all_spaces(text)
Case-Insensitive Preference Comparison
Determine if two user inputs represent identical choices, ignoring case discrepancies.
def compare_preferences(pref_a, pref_b):
if pref_a.casefold() == pref_b.casefold():
return "The preferences match."
else:
return "The preferences differ."
choice_one = "LOL"
choice_two = "lol"
outcome = compare_preferences(choice_one, choice_two)
Date Format Transformation
Parse a date string formatted with slashes and reformat it to utilize hyphens and localized date terminology.
from datetime import datetime
def format_date_string(date_str):
parsed_date = datetime.strptime(date_str, "%Y/%m/%d")
return parsed_date.strftime("%Y年-%m月-%d日")
original_format = "2008/08/08"
transformed_format = format_date_string(original_format)
Character Sorting and Reversal
Sort the characters of a string alphabetically, then reverse the sorted sequence.
def sort_and_reverse_chars(word):
sorted_chars = sorted(word)
reversed_sorted = sorted_chars[::-1]
return "".join(reversed_sorted)
input_word = "cabed"
result_word = sort_and_reverse_chars(input_word)
Sentence Word Reversal
Invert the order of words within a sentence while maintaining the characters within each word.
def reverse_sentence_words(sentence):
words = sentence.split()
words.reverse()
return " ".join(words)
phrase = "hello c java python"
reversed_phrase = reverse_sentence_words(phrase)
URL Query Parameter Extraction
Separate a web address into its base domain and its appended query parameters.
import re
def parse_url_components(url):
match = re.search(r'([^?]+)\?(.*)', url)
if match:
base_url = match.group(1)
query_string = match.group(2)
return base_url, query_string
return url, ""
target_url = "http://www.example.com?userName=admin&pwd=123456"
domain, params = parse_url_components(target_url)
Title Truncation with Author Annotation
Standardize a collection of book titles by abbreviating entries exceeding a length threshold, appending an ellipsis, and affixing the author.
def format_titles(book_data, max_length=10, truncate_length=8):
formatted_list = []
for title, author in book_data:
if len(title) > max_length:
truncated_title = title[:truncate_length] + "... | " + author
formatted_list.append(truncated_title)
else:
formatted_list.append(f"{title} | {author}")
return formatted_list
books = [("Dream of the Red Chamber", "Cao Xueqin"), ("A very long story about 108 heroes", "Shi Nai'an")]
processed_books = format_titles(books)
Target Character Position Tracking
Identify and record all index positions where a specific character appears within a text sequence.
def find_character_positions(text, target_char):
indices = [idx for idx, ch in enumerate(text) if ch == target_char]
return indices
sample_sentence = "This is a test sentence with some s characters."
positions = find_character_positions(sample_sentence, 's')
Prohibited Word Censorship
Substitute any occurrences of a designated forbidden word within a text with alternative masking characters.
import re
def censor_text(content, prohibited_word, replacement="**"):
pattern = re.compile(prohibited_word)
return pattern.sub(replacement, content)
raw_content = "The villain was very wicked"
censored_content = censor_text(raw_content, "wicked", "***")
Palindrome Verification
Evaluate whether a given string reads identically forwards and backwards.
def check_palindrome(text):
return text == text[::-1]
test_strings = ["1234567654321", "rotor", "hello"]
for s in test_strings:
is_palindrome = check_palindrome(s)