博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Codewars第六天--Where my anagrams at?
阅读量:4302 次
发布时间:2019-05-27

本文共 1187 字,大约阅读时间需要 3 分钟。

Codewars第六天–Where my anagrams at?

题目描述:

What is an anagram? Well, two words are anagrams of each other if they both contain the same letters. For example:

'abba' & 'baab' == true'abba' & 'bbaa' == true'abba' & 'abbba' == false

Write a function that will find all the anagrams of a word from a list. You will be given two inputs a word and an array with words. You should return an array of all the anagrams or an empty array if there are none. For example:

anagrams('abba', ['aabb', 'abcd', 'bbaa', 'dada']) => ['aabb', 'bbaa']anagrams('racer', ['crazer', 'carer', 'racar', 'caers', 'racer']) => ['carer', 'racer']anagrams('laser', ['lazing', 'lazy',  'lacer']) => []

该题目是需要我们找到同给定字符串有着相同数目的字母的字符串,并返回这些字符串的列表。如果没有则返回空列表。

代码如下,使用了比较笨的方法,但也通过了所以的用例,在这里需要分别对比字符串之间的字符和字符个数情况。
使用set 可以对字符串去重,并返回一个去重过后的对象。使用count 可以对字符串中相应的字符进行统计个数。

def anagrams(word, words):    w = set(word)    a = [word.count(j) for j in w]    result = []    for i in words:        ws = set(i)        b=[i.count(j) for j in ws]        if ws == w:            if a == b:                result.append(i)    return result

最佳做法一句话就可以搞定:

def anagrams(word, words): return [item for item in words if sorted(item)==sorted(word)]

转载地址:http://rmmws.baihongyu.com/

你可能感兴趣的文章
git 提示:error: unable to rewind rpc post data - try increasing http.postBuffer
查看>>
php 解决json_encode中文UNICODE转码问题
查看>>
LNMP 安装 thinkcmf提示404not found
查看>>
PHP empty、isset、innull的区别
查看>>
apache+nginx 实现动静分离
查看>>
通过Navicat远程连接MySQL配置
查看>>
phpstorm开发工具的设置用法
查看>>
Linux 系统挂载数据盘
查看>>
Git基础(三)--常见错误及解决方案
查看>>
Git(四) - 分支管理
查看>>
PHP Curl发送数据
查看>>
HTTP协议
查看>>
HTTPS
查看>>
git add . git add -u git add -A区别
查看>>
apache下虚拟域名配置
查看>>
session和cookie区别与联系
查看>>
PHP 实现笛卡尔积
查看>>
Laravel中的$loop
查看>>
CentOS7 重置root密码
查看>>
Centos安装Python3
查看>>