看读序列
题目:将一组数据用python呈现其看读序列。例:‘1211’ =》【‘1’‘2’,‘1’‘2’,‘2’‘1’】读作一个1, 一个2,两个1。代码:
def parse_string (term):
final_list = []
current_streak = ]
for i in term :
if i in current_streak:
current_streak.append(i)
else:
final_list.append(])
print (final_list)
current_streak =
final_list.append(])
return final_list
term_n = '1211'
parse_string(term_n)
问题:当我把current_streak = ]写作current_streak = term时,1211可以成功跑出来,1121则不可以。请问是哪里出问题了?
本帖最后由 jackz007 于 2022-10-9 00:03 编辑
看看这个代码和结果是否符合要求:
def parse_string(term):
final_list , i , x , c = [] , 1 , term , 1
for i in range(1 , len(term)):
if term == x :
c += 1
else:
final_list . append()
x , c = term , 1
final_list . append()
return final_list
print(parse_string('1211'))
print(parse_string('1121'))
运行实况:
D:\\Python>python x.py
[['1', '1'], ['1', '2'], ['2', '1']]
[['2', '1'], ['1', '2'], ['1', '1']]
D:\\Python> 666 jackz007 发表于 2022-10-9 00:01
看看这个代码和结果是否符合要求:
运行实况:
谢谢,不过我是对于我给出的这个代码中中括号为什么加与不加有不同的结果,不知道您可否解答一下 def foo(string):
res, c, n = '', string, 1
for char in string:
if char == c:
n += 1
else:
res += f"{n}{c}"
c, n = char, 1
res += f"{n}{c}"
return res
def f():
res = '1'
while True:
yield res
res = foo(res)
for n, each in enumerate(f()):
if n > 15:
break
print(each)1
11
21
1211
111221
312211
13112221
1113213211
31131211131221
13211311123113112211
11131221133112132113212221
3113112221232112111312211312113211
1321132132111213122112311311222113111221131221
11131221131211131231121113112221121321132132211331222113112211
311311222113111231131112132112311321322112111312211312111322212311322113212221
132113213221133112132113311211131221121321131211132221123113112221131112311332111213211322211312113211 本帖最后由 jackz007 于 2022-10-9 11:06 编辑
1900342703 发表于 2022-10-9 08:43
谢谢,不过我是对于我给出的这个代码中中括号为什么加与不加有不同的结果,不知道您可否解答一下
不加中括号,你指的是哪个中括号?
另:你的代码也是对的:
def parse_string (term):
final_list = []
current_streak = ]
for i in term :
if i in current_streak:
current_streak . append(i)
else:
final_list . append(])
print (final_list)
current_streak =
final_list . append(])
return final_list
print(parse_string('1211'))
print(parse_string('1121'))
运行实况:
D:\\Python>python x.py
[['1', '1']]
[['1', '1'], ['1', '2']]
[['1', '1'], ['1', '2'], ['2', '1']]
[['2', '1']]
[['2', '1'], ['1', '2']]
[['2', '1'], ['1', '2'], ['1', '1']]
D:\\Python>
这个结果(第4、7行)有何问题? 看不懂 {:5_102:}
页:
[1]