小编Dat*_*eer的帖子

为ordered_vowel_words实现一个方法

我一直在讨论一些编码面试问题.我想知道实现ordered_vowel单词方法.我正在研究算法问题以实现此方法以用于理解算法.我有以下内容:

此方法采用一串小写单词并返回一个字符串,其中只包含按字母顺序排列所有元音(不包括"y")的单词.元音可能会重复("afoot"是一个有序的元音词)

def ordered_vowel_words(str)
  words = str.split(" ")

  ordered_vowel_words = words.select do |word|
    ordered_vowel_word?(word)
  end

  ordered_vowel_words.join(" ")
end

def ordered_vowel_word?(word)
  vowels = ["a", "e", "i", "o", "u"]

  letters_arr = word.split("")
  vowels_arr = letters_arr.select { |l| vowels.include?(l) }

  (0...(vowels_arr.length - 1)).all? do |i|
    vowels_arr[i] <= vowels_arr[i + 1]
  end
end
Run Code Online (Sandbox Code Playgroud)

我添加了以下测试用例:

puts("\nTests for #ordered_vowel_words")
puts("===============================================")
    puts "ordered_vowel_words(\"amends\") == \"amends\": "  + (ordered_vowel_words("amends") == "amends").to_s
    puts "ordered_vowel_words(\"complicated\") == \"\": "  + (ordered_vowel_words("complicated") == "").to_s
    puts "ordered_vowel_words(\"afoot\") == \"afoot\": "  + …
Run Code Online (Sandbox Code Playgroud)

ruby algorithm

5
推荐指数
1
解决办法
121
查看次数

Python优化:在字典或列表列表之间进行选择

我是python3的新手,我对解决这个问题的不同方法提出了疑问.关于使用不同数据结构的问题.我的问题是如何比较不同采样技术的权衡

我在程序中使用字典数据结构来首先解决这个问题.然后我尝试仅使用列表数据结构重写它.我试着考虑排序的好处,我不知道这两种方法之间有什么区别.它似乎没有在两种方法之间产生那么大的差异.

方法1.我使用字典在直方图中创建直方图键和值对

方法2以字符串格式接收源文本并返回列表列表,其中每个子列表中的第一个元素是单词,第二个元素是源文本中的频率

# This program Analyze word frequency in a histogram
# sample words according to their observed frequencies
# takes in a source text in string format and returns a dictionary
# in which each key is a unique word and its value is that word's
# frequency in the source text
import sys
import re
import random
import time

def histogram(source_text):
    histogram = {}
    # removing any sort of string, removing any other special character
    for …
Run Code Online (Sandbox Code Playgroud)

python dictionary list python-3.x

3
推荐指数
1
解决办法
112
查看次数

标签 统计

algorithm ×1

dictionary ×1

list ×1

python ×1

python-3.x ×1

ruby ×1