gpt4 book ai didi

python - 如何返回包含数字和字母的字符串中的最大整数?

转载 作者:太空宇宙 更新时间:2023-11-04 08:24:54 24 4
gpt4 key购买 nike

对于这道题,我想返回与其他整数和字符串混合时最大的整数。当我测试我的代码时,我得到的答案是 319,而不是 51。谁能帮我解决这个问题?

测试用例:

>>>biggestBuried('abcd51kkk3kk19ghi')
319


def biggestBuried(s):
new_string = ''
biggest = 0
for num in s:
if num >= '0' and num <= '9':
new_string += num
else:
if not(num >= '0') and not(num <= '9'):
return 0
if new_string and int(new_string) > biggest:
biggest = int(new_string)
new_string = ''
if new_string and int(new_string) > biggest:
biggest = int(new_string)
return biggest

最佳答案

您的循环的问题在于,您仅在找到更大的数字时才设置 new_string = ''。每当您到达数字的末尾时,您都需要将其清空,即使它并不更大。

此外,当你到达结尾时,你需要检查 new_string 是否更大,以防字符串以数字结尾。我认为您正试图这样做,但缩进是错误的——它需要在 for 循环之外。

def biggestBuried(s):
new_string = ''
biggest = 0
for num in s:
if num.isnumeric():
new_string += num
else: # We're at the end of a number
if new_string and int(new_string) > biggest: # Check if it's a bigger number
biggest = int(new_string)
new_string = '' # Start a new number
if new_string and int(new_string) > biggest: # Check if the final number is biggest
biggest = int(new_string)

return biggest

关于python - 如何返回包含数字和字母的字符串中的最大整数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58314288/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com