【发布时间】:2016-12-19 08:07:31
【问题描述】:
这是一个自我思考的测验,与我面临的现实生活中的问题非常相似。
假设我有一个字符串列表(比如说它称为stringlist),其中一些在末尾附加了两位数字。例如,“foo”、“foo01”、“foo24”。
我想将具有相同字母(但末尾有不同的两位数字)的那些分组。
因此,“foo”、“foo01”和“foo24”将在“foo”组下。
但是,我不能只检查任何以“foo”开头的字符串,因为我们也可以有“food”、“food08”、“food42”。
没有重复。
中间可以有数字。例如)“foo543food43”在组“foo543food”下
或者甚至是多个数字然后结束。例如)“foo1234”在组“foo12”下
我能想到的最明显的解决方案是有一个数字列表。
numbers = ["0", "1", "2", ... "9"]
那么,我会这样做
grouplist = [[]] //Of the form: [[group_name1, word_index1, word_index2, ...], [group_name2, ...]]
for(word_index=0; word_index < len(stringlist); word_index++) //loop through stringlist
for(char_index=0; char_index < len(stringlist[word_index]); char_index++) //loop through the word
if(char_index == len(stringlist[word_index])-1) //Reached the end
for(number1 in numbers)
if(char_index == number1) //Found a number at the end
for(number2 in numbers)
if(char_index-1 == number2) //Found another number one before the end
group_name = stringlist[word_index].substring(0,char_index-1)
for(group_element in grouplist)
if(group_element[0] == group_name) //Does that group name exist already? If so, add the index to the end. If not, add the group name and the index.
group_element.append(word_index)
else
group_element.append([stringlist[word_index].substring(0,char_index-1), word_index])
break //If you found the first number, stop looping through numbers
break //If you found the second number, stop looping through numbers
现在这看起来很混乱。你们有什么更清洁的方法吗? 包括最终结果在内的任何数据结构都可以是您想要的。
【问题讨论】:
-
我会阅读更多关于regular expressions 以及如何将它们翻译成finite state machines 的信息。另请阅读lexical analysis 和parsing。
标签: algorithm data-structures language-agnostic