2 回答

TA貢獻1786條經驗 獲得超13個贊
由于歧義,以 0 開頭的整數文字在 python 中是非法的(顯然除了零本身)。以 0 開頭的整數文字具有以下字符,用于確定它屬于哪個數字系統:0x十六進制、0o八進制、0b二進制。
至于整數本身,它們只是數字,數字永遠不會從零開始。如果你有一個表示為字符串的整數,并且它恰好有一個前導零,那么當你將它轉換為整數時它會被忽略:
>>> print(int('014'))
14
考慮到你在這里要做的事情,我只是重寫列表的初始定義:
lst = ['129', '831', '014']
...
while i < length:
a = lst[i]
print(permute_string(a)) # a is already a string, so no need to cast to str()
或者,如果您需要lst成為一個整數列表,那么您可以使用格式字符串文字而不是調用來更改將它們轉換為字符串的方式str(),這允許您用零填充數字:
lst = [129, 831, 14]
...
while i < length:
a = lst[i]
print(permute_string(f'{a:03}')) # three characters wide, add leading 0 if necessary
在這個答案中,我使用lst作為變量名,而不是list你問題中的。你不應該使用list作為變量名,因為它也是代表內置列表數據結構的關鍵字,如果你命名一個變量那么你就不能再使用關鍵字。

TA貢獻1909條經驗 獲得超7個贊
最后,我得到了答案。下面是工作代碼。
def permute_string(str):
if len(str) == 0:
return ['']
prev_list = permute_string(str[1:len(str)])
next_list = []
for i in range(0,len(prev_list)):
for j in range(0,len(str)):
new_str = prev_list[i][0:j]+str[0]+prev_list[i][j:len(str)-1]
if new_str not in next_list:
next_list.append(new_str)
return next_list
#Number should not be with leading Zero
actual_list = '129, 831 ,054, 845,376,970,074,345,175,965,068,287,164,230,250,983,064'
list = actual_list.split(',')
length = len(list)
i = 0
# Iterating using while loop
while i < length:
a = list[i]
print(permute_string(str(a)))
i += 1;
添加回答
舉報