python如何生成乙個序列,是隨機仍20次骰子組合的序列,並把連續相同的打上括號?

時間 2021-05-29 23:44:50

1樓:

python如何生成乙個序列,是隨機仍20次骰子組合的序列,並把連續相同的打上括號?

比如這樣

1 2 (5 5) 3 1 2 4 3 (2 2 2 2) 3 6 (5 5) 6 3 1

解答的思路:

核心思想是先生成二十次結果,然後遍歷一遍這個結果陣列,找到重複數字的下標範圍。

把每一次遍歷中的結果都儲存到乙個結果陣列裡,

如果遇到重複的數字範圍,則在這一小段範圍存入結果陣列前,加「(」和「)」。

'''import

random

defmain

():# 骰子陣列,使用字串是為了列印的技巧

dice=[

'1',

'2',

'3',

'4',

'5',

'6']

# 隨機次數

range_count=20

# 隨機的二十次結果

dice_random_list=[

random

.sample

(dice,1

)[0]for_in

range

(range_count

)]# print(dice_random_list)

# Exp: ['4', '2', '6', '2', '4', '4', '3', '5', '5', '1', '3', '2', '2', '4', '4', '2', '3', '6', '1', '4']

# Answer: 4 2 6 2 ( 4 4 ) 3 ( 5 5 ) 1 3 ( 2 2 ) ( 4 4 ) 2 3 6 1 4

results_list=

find_repeat_index=0

while

find_repeat_index

dice_random_list

):# print(find_repeat_index)_=

dice_random_list

[find_repeat_index

:]repeat_from

,repeat_end

=find_repeat(_

)ifrepeat_from

==repeat_endor(

repeat_from+1

)==repeat_end

:results_list.(

_[repeat_from

])find_repeat_index

=find_repeat_index+1

else

:results_list.(

'(')

# print(' find: repeat_from=, repeat_end='.format(

# repeat_from, repeat_end)

# )results_list

.extend(_

[repeat_from

:repeat_end

])results_list.(

')')

find_repeat_index

=find_repeat_index

+repeat_end

return

results_list

deffind_repeat

(list

):# print(list)

repeat_from=0

repeat_end=0

repeat_num

=list[0

]# print('start: repeat_from=, repeat_end=, repeat_num='.format(

# repeat_from,

# repeat_end,

# repeat_num)

# )for

item

inlist

[repeat_from

:]:if

repeat_num

==item

:repeat_end

=repeat_end+1

else

:break

# print(' end: repeat_from=, repeat_end=, repeat_num='.format(

# repeat_from,

# repeat_end,

# repeat_num)

# )return

(repeat_from

,repeat_end)if

__name__

=='__main__'

:results_list

=main

()print

(' '

.join

(results_list

))裡面被我注釋掉的Print是中間過程值,你可以取消注釋看一下過程。

如何快速掌握乙個python模組?

皮卡丘 初學者就別想快了。我自己是這樣的。先上網看看一些基礎的教程,非常快的過一下,十幾分鐘,主要是了解這個module能幹什麼,特別是一些基本的功能,頭腦中建立起初步對映。然後就是用了,不用看了也白搭。我假設你的專案是需要經常用到這個module的,不然你為啥想掌握它?因為頭腦中有對映,codin...

Python 中如何同時 import 乙個包的兩個版本?

意群 續樓上,假設當前目錄為 zhangbin from a import c as a cfrom b import c as b c然後分別呼叫 a c.hello b c.hello IAMSK 比如 Users zhangbin a 和 Users zhangbin b 下各有乙個 lib ...

如何用乙個1 8隨機生成器製作乙個1 7隨機數生成器?

草如花 先找 rand1 0 1 rand1rand8 1 8 1 rand7 rand1 7 1 1。擴充套件開來。已知randN L N 求 randM K,M 方法 先找 rand1 0 1 rand1 randN L N L randM rand1 M K KrandM randN L N ...