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

Weekly Challenge: Uncommon parentheses

Simon Green 2026年08月09日 11:56 2 次阅读 来源:Dev.to

Weekly Challenge 385 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: Uncommon Words Task You are given two sentences. Write a script to return list of all uncommon words, order is not important. My solution This is relatively straight forward. I start with a Counter called word_freq which is a special type of dictionary which is ideal for counting frequencies. I take one or more sentences as input. I loop through each sentence, separate them by spaces and increment the word_freq counter. I then return all words that have a frequency of 1 . Since Python 3.6, dictionaries maintain their order. Therefore the words in the output will maintain their order from the supplied sentences. from collections import Counter def uncommon_word ( * sentences : str ) -> list : word_freq = Counter () for sentence in sentences : word_freq . update ( sentence . split ()) return [ word for word in word_freq if word_freq [ word ] == 1 ] Perl does not maintain order of hashes. For the Perl solution, I sort the unique words alphabetically. This is an example of stacking sort , map (to quote strings) and grep (to filter duplicated words) in a single function. sub main (@sentences) { my %word_freq = (); foreach my $sentence ( @sentences ) { foreach my $word ( split /\s+/ , $sentence ) { $word_freq { $word } ++ ; } } say " ( " . join ( " , ", sort map { qq{"$_"} } grep { $word_freq { $_ } == 1 } keys %word_freq ) . " ) "; } Examples $ ./ch-1.py "apple banana apple" "banana orange" ( "orange" ) $ ./ch-1.py "cat dog" "bird fish" ( "cat" , "dog" , "bird" , "fish" ) $ ./ch-1.py "the quick brown fox" "the quick" ( "brown" , "fox" ) $ ./ch-1.py "hello" "hello" () $ ./

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