[英]How can I arrange a string by its alphabetical order using only While loop and conditions?
Given the String "aaababababab"
(Only 'a'
or 'b'
allowed): How do I order the string alphabetically to be like "aaaaaaabbbbb"
by only using a while loop?给定字符串
"aaababababab"
(仅允许使用'a'
或'b'
):如何仅使用 while 循环将字符串按字母顺序排列为"aaaaaaabbbbb"
?
This is my current attempt:这是我目前的尝试:
word = "ababababaabab"
wordfixed = ""
i = 0
while i < len(word):
if word[i] == "a":
wordfixed += "a"
i += 1
elif word[i] == "b":
wordfixed += (word[i])
i += 1
print(wordfixed)
But it simply prints the original word back.但它只是简单地打印回原始单词。 How can I get it to print the desired output?
我怎样才能让它打印所需的输出?
Using your current idea, you could just append to one end or the other depending on the value of the letter.使用您当前的想法,您可以根据字母的值将其附加到一端或另一端。 This would allow
a
to accumulate at the start and b
to build off the end.这将允许
a
在开始时积累,而b
在结束时建立。
word = "ababababaabab"
wordfixed = ""
i = 0
while i < len(word):
if word[i] == "a":
wordfixed = word[i] + wordfixed
elif word[i] == "b":
wordfixed = wordfixed + word[i]
i += 1
print(wordfixed)
# aaaaaaabbbbbb
You can create two "helper" variables: one to accumulate the a
s, and one for the b
s.您可以创建两个“辅助”变量:一个用于累积
a
,另一个用于b
。 Then in the end just concatenate them in the right order:然后最后只需按正确的顺序连接它们:
word = "ababababaabab"
wordfixed = ""
wordfixed2 = ""
wordfixed3 = ""
i = 0
while i < len(word):
if word[i] == "a":
wordfixed2 += "a"
elif word[i] == "b":
wordfixed3 += "b"
i += 1
wordfixed = wordfixed2 + wordfixed3
print(wordfixed)
I think that's the right way to do it.我认为这是正确的做法。
Your code does not work because you add the letter that you currently have at the end - so it will be the same afterwards.您的代码不起作用,因为您在末尾添加了您当前拥有的字母 - 所以之后它会相同。
You can instead count amount of 'a'
's while looping through the string once (for loop would be better suited but while can be used as well) - then print the remaining 'b'
:您可以改为在循环遍历字符串时计算
'a'
的数量(for 循环更适合,但也可以使用 while )-然后打印剩余的'b'
:
word = "ababababaabab"
lw = len(word)
i = 0
a_s= 0
while i < lw:
if word[i] == 'a':
print("a", end="") # dont end the line quite yet
a_s += 1
i += 1
# print b's for remaining wordlength minus printed a's
print('b' * (lw-a_s))
or better with for loop:或更好的 for 循环:
a_s = 0
for letter in word:
if letter == "a":
a_s +=1
print(letter, end="")
print('b' * (lw-a_s))
I'll go with @Mark_Meyer solution but if you don't really need to use only the while loop, here is an easy way to go :我将使用@Mark_Meyer 解决方案,但如果您真的不需要只使用 while 循环,这里有一个简单的方法:
word = "ababababaabab"
print(word.count('a')*'a' + word.count('b')*'b')
# aaaaaaabbbbbb
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.