任务:请编写一个程序,将用户输入的字符串重新格式化,使得字母和数字相互分隔(即一个字母一个数字相互间隔)
reboot = input("输入:")
i = 0
j = 0
alpha = []
number = []
for each in reboot:
if each.isalpha():
i += 1
alpha.append(each)
elif each.isdigit():
j += 1
number.append(each)
l = 0
if i == j + 1:
sort = alpha[0]
for k in range(1,i):
if l < j:
sort = sort + number[l] + alpha[k]
l += 1
print("输出:", sort)
elif i == j - 1:
sort = number[0]
for k in range(1,j):
if l < i:
sort = sort + alpha[l] + number[k]
l += 1
print("输出:", sort)
elif i == j :
sort = alpha[0]
for k in range(1,i):
if l < j :
sort = sort + number[l] + alpha[k]
print("输出:", sort)
else:
print("输出:字符串中数字和字母的数量不满足重新格式化的条件")
s = input("请输入测试字符串:")
str09 = []
strAZ = []
# 将数字和字母进行归类存放
for each in s:
if each.isdecimal():
str09.append(each)
else:
strAZ.append(each)
len09 = len(str09)
lenAZ = len(strAZ)
# 如果两个容器的元素个数相差 1 个以上,则不满足重新格式化的条件
if abs(len09 - lenAZ) > 1:
print("字符串中数字和字母的数量不满足重新格式化的条件。")
else:
if len09 > lenAZ:
shorter = strAZ
longer = str09
else:
shorter = str09
longer = strAZ
result = []
for i in range(len(shorter)):
result.append(longer[i])
result.append(shorter[i])
# 由于 longer 是有可能等于 shorter 的,就不必执行下面这一步
if len(longer) > len(shorter):
result.append(longer[-1])
print("".join(result))
提问:
1.第一个代码是我自己写的,请问可以满足这个任务吗,是否会有bug?(我自己测试了几组没啥问题)
2.如果没有bug请问可以怎么优化?
3. 第二个代码是答案的,请问和我的相比哪个好些?
逻辑上没啥问题,可以减少代码 reboot = input("输入:")
i = 0
j = 0
alpha = []
number = []
for each in reboot: # 分组
if each.isalpha():
i += 1
alpha.append(each)
elif each.isdigit():
j += 1
number.append(each)
l = 0
sort = alpha[0]
if i == j + 1:
for k in range(1, i):
if l < j:
sort = sort + number[l] + alpha[k]
l += 1
elif i == j - 1:
sort = number[0]
for k in range(1, j):
if l < i:
sort = sort + alpha[l] + number[k]
l += 1
elif i == j:
for k in range(1, i):
if l < j:
sort = sort + number[l] + alpha[k]
else:
sort = "输出:字符串中数字和字母的数量不满足重新格式化的条件"
print(sort)
时间复杂度和答案一样,不过我更偏好答案的风格
|