Could use some help with this soundex coding

那年仲夏 提交于 2019-12-01 11:13:14

Here are some small hints on general Python stuff.

0) You can use a for loop to loop over any sequence, and a string counts as a sequence. So you can write:

for nextletter in surname[1:]:
    # do stuff

This is easier to write and easier to understand than computing an index and indexing the surname.

1) You can use the += operator to append strings. Instead of

x = x + 'a'

you can write

x += 'a'

As for help with your specific problem, you will want to keep track of the previous letter. If your assignment had a rule that said "two 'z' characters in a row should be coded as 99" you could add code like this:

def rule_two_z(prevletter, curletter):
    if prevletter.lower() == 'z' and curletter.lower() == 'z':
        return 99
    else:
        return -1


prevletter = surname[0]
for curletter in surname[1:]:
    code = rule_two_z(prevletter, curletter)
    if code < 0:
        # do something else here
    outstring += str(code)
    prevletter = curletter

Hmmm, you were writing your code to return string integers like '3', while I wrote my code to return an actual integer and then call str() on it before adding it to the string. Either way is probably fine.

Good luck!

A few hints:

  • By using an array where each Soundex code is stored and indexed by the ASCII value (or a value in a shorter numeric range derived thereof) of the letter it corresponds to, you will both make the code for efficient and more readable. This is a very common technique: understand, use and reuse ;-)

  • As you parse the input string, you need keep track of (or compare with) the letter previously handled to ignore repeating letters, and handle other the rules. (implement each of these these in a separate function as hinted in the write-up). The idea could be to introduce a function in charge of -maybe- adding the soundex code for the current letter of the input being processed. This function would in turn call each of the "rules" functions, possibly quiting early based on the return values of some rules. In other words, replace the systematic...

    outstring = outstring + c    # btw could be +=
...with
    outstring += AppendCodeIfNeeded(c)
  • beware that this multi-function structure is overkill for such trivial logic, but it is not a bad idea to do it for practice.
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!