我正在为面试而练习,过去问面试者的一个问题是--“写一个程序来增加字母表,使A变成B,Z变成AA,ABZ变成ACA。”
我需要帮助,了解我如何才能达到预期的结果。我尝试使用一个简单的函数,它增加了Ascii值,当然可以使用if循环获得结果,chracter "z“作为特例。
def give_string(random_string):
word = ""
for i in range(len(random_string)):
if(random_string[i] == 'z' or random_string[i] == 'Z'):
#if "z or Z" is at the begining of the string
if(random_string[0] == 'z' or 'Z' and i == 0):
if(i == 'z'):
word = word + 'aa'
else:
word = word + 'AA'
if(len(random_string) == 1):
return word
# if the last character is "z or Z", we also need to change the first character to a or A
# i.e., BCZ = ADA not CDAA
elif(random_string[-1] == 'z' or 'Z' and i == (len(random_string) - 1)):
if(random_string[-1] == 'z'):
word = word + 'a'
word = word[:0] + 'a' + word[0+1:]
else:
word = word + 'A'
word = word[:0] + 'A' + word[0+1:]
return word
#if "z or Z" is somewhere in the middle of the string
else:
print("going to the middle")
if(random_string[i] == 'z'):
word = word + 'aa'
else:
word = word + 'AA'
#if it is any character other than "z or Z"
else:
word = word + chr(ord(random_string[i])+1)
return word
if __name__ == '__main__':
my_string = "ZbgsGD"
print(my_string)
print(give_string(my_string))但是,我想知道的是,还有什么办法可以解决我错过的这个问题,
如您所见,代码确实完成了获得正确结果的工作。我只想知道是否还有其他更简单的方法来达到我所缺少的预期结果,因为使用所有这些循环似乎不是最好的方法。
发布于 2022-11-02 16:55:32
显示类似于Potential interview question: building a pseudocode string incrementer similar to Excel columns
本质上,它要求构建一个字符串增量器,以便A+1=B.Z+1= AA,AA +1=AB.ZZ +1=AAA以此类推。
码
def incr(s):
'''
Incremental for string s
'''
def incr_chr(c):
'''
Helper function that provides single character incrementer
carry and next character for character incrment
'''
if c in ('z', 'Z'):
return 1, 'a' if c.islower() else 'A' # with carry one
else:
return 0, chr(ord(c) + 1) # with carry zero
lst = list(s) # string to list since string immutable
result = []
while lst:
carry, next_ = incr_chr(lst.pop()) # increment last letter in list
result.append(next_) # add last incremented character to result
if not carry: # break if no carry
break
if not lst:
result.append('a' if next_.islower() else 'A') # empty lst but remaining carry
result += lst[::-1] # add remainder of string list to result
return ''.join(result[::-1]) # list to string in reverse order测试
for t in ['a', 'A', 'b', 'z', 'Z', 'ABZ', 'abz', 'abcdz', 'ZbgsGD', 'zzz', 'ZZ']:
print(f'{t} -> {incr(t)}')输出
a -> b
A -> B
b -> c
z -> aa
Z -> AA
ABZ -> ACA
abz -> aca
abcdz -> abcea
ZbgsGD -> ZbgsGE
zzz -> aaaa
ZZ -> AAA
https://stackoverflow.com/questions/74292052
复制相似问题