今日已更新 412 条资讯 | 累计 19972 条内容
关于我们

Weekly Challenge: Existence

Simon Green 2026年06月14日 20:28 1 次阅读 来源:Dev.to

Weekly Challenge 377 Each week Mohammad S. Anwar sends out The Weekly Challenge , a chance for all of us to come up with solutions to two weekly tasks. My solutions are written in Python first, and then converted to Perl. Unless otherwise stated, Copilot (and other AI tools) have NOT been used to generate the solution. It's a great way for us all to practice some coding. Challenge , My solutions Task 1: Reverse Existence Task You are given a string. Write a script to find whether any substring of length 2 is also present in the reverse of the given string. My solution This is relatively straight forward. I create a variable reversed_string which is the string reversed. I then have a loop called start_pos that goes from 0 to 2 less than the length of the string. At each position, I check if the two letters at that position are in the original string. def reverse_existence ( input_string : str ) -> bool : reversed_string = input_string [:: - 1 ] for start_pos in range ( len ( input_string ) - 1 ): if reversed_string [ start_pos : start_pos + 2 ] in input_string : return True return False The Perl solution follows the same logic. sub main ($input_string) { my $reversed_string = reverse ( $input_string ); foreach my $start_pos ( 0 .. length ( $input_string ) - 2 ) { if ( index ( $input_string , substr ( $reversed_string , $start_pos , 2 ) ) != - 1 ) { say " true "; return ; } } say " false "; } Examples $ ./ch-1.py abcba true $ ./ch-1.py racecar true $ ./ch-1.py abcd false $ ./ch-1.py banana true $ ./ch-1.py hello true Task 2: Prefix Suffix Task You are given an array of strings. Write a script to find if the two strings ( str1 , str2 ) in the given array such that str1 is prefix and suffix of str2. Return the total count of such pairs. My solution In Python, this is a one line solution. I use the combinations function from the itertools module to produce all combinations of pairs of str1 and str2 . For each pair, I use the startwith and endswith function on the strings

本文内容来源于互联网,版权归原作者所有
查看原文