學習內容:把數字轉成字串
1.
defis_palindrome(n):
n=str(n)
m=n[::-1]
return n==m
2.
tmp_str =str(n)i = len(tmp_str) - 1j =0
while i >j :
if tmp_str[i] ==tmp_str[j] :
i = i - 1j = j + 1
pass
else
:
return
false
return true
如果要直接接收鍵盤輸入的話,可以直接用raw_input()即可,這樣獲得的就是字串。
學習內容:如何一行輸出多個數字
1.
s=[1,2,3,4,5,]s1='
%d %d %d %d %d
' %(s[0],s[1], s[2], s[3], s[4])
print s1
2.轉換成字串輸出:
s=[1,2,3,4,5]s2='
%s' %('
'.join(map(str,s)))
print s2
1.利用列表的count函式
mylist = [1,2,2,2,2,3,3,3,4,4,4,4]myset = set(mylist) #
myset是另外乙個列表,裡面的內容是mylist裡面的無重複項
for item in
myset:
print("
the %d has found %d
" %(item,mylist.count(item)))
2.利用字典
list=[1,2,2,2,2,3,3,3,4,4,4,4]a ={}
for i in
list:
#i是元素,不是索引,所以a[i]表示key
a[i] =list.count(i)
print (a)
3.利用counter類,counter類的學習:
from collections importcounter
counter([1,2,2,2,2,3,3,3,4,4,4,4])
#輸出:counter()
輸入乙個正整數陣列,把陣列裡所有數字拼接起來排成乙個數,列印能拼接出的所有數字中最小的乙個。例如輸入陣列,則列印出這三個數字能排成的最小數字為321323。
#-*- coding:utf-8 -*-
class
solution:
defprintminnumber(self, numbers):
#write code here
num_str=map(str,numbers)
ifnot
num_str:
return
''num_str.sort(
lambda x,y:cmp(x+y,y+x))
return
''.join(num_str)
思路:用lambda表示式寫乙個比較規則。
自定義比較函式:
輸入乙個字串,按字典序列印出該字串中字元的所有排列。例如輸入字串abc,則列印出由字元a,b,c所能排列出來的所有字串abc,acb,bac,bca,cab和cba。
使用遞迴方法:假如n-1個字串都已經有了,那麼加入第n個字元的時候,可以讓n依次和前邊n-1個字元進行交換。
例項**:假如字串strap=['a','b','c','d']
#-*- coding:utf-8 -*-
defswap(i, j):
temp =strap[i]
strap[i] =strap[j]
strap[j] =temp
strap = ['
a', '
b', '
c', 'd'
]result =
defcalallp1(first, num):
if first == num - 1: #
到達最後乙個元素,則退出
pass
else
:
for i in
range(first, num):
if i != first: #
輸出時去掉重複
swap(i, first)
temp = ''
.join(strap)
calallp1(first + 1, num) #
遞迴呼叫,全排列後面的元素
swap(i, first)#
用來復位的(前邊你交換了,這裡再交換回來)。
temp = ''
.join(strap)
calallp1(0, len(strap))
print result
完整的**:
#-*- coding:utf-8 -*-
class
solution:
def__init__
(self):
self.strap=
self.result=
defpermutation(self, ss):
#write code here
ifnot
ss:
return
self.strap=list(ss)
temp = ''
.join(self.strap)
self.calallp1(0, len(self.strap))
self.result=sorted(list(set(self.result)))#
用set去除重複,然後再轉化成list,然後再排序
return
self.result
defswap(self, i, j):
temp =self.strap[i]
self.strap[i] =self.strap[j]
self.strap[j] =temp
defcalallp1(self, first, num):
if first == num - 1: #
到達最後乙個元素,則退出
pass
else
:
for i in
range(first, num):
if i != first: #
輸出時去掉重複
self.swap(i, first)
temp = ''
.join(self.strap)
self.calallp1(first + 1, num) #
遞迴呼叫,全排列後面的元素
self.swap(i, first)#
用來復位的
Python3必備刷題基礎
list.insert index,obj 在index處插入物件 list.index obj,start,end 找出與obj第乙個匹配項的索引位置,start和end可選。list.remove obj 移除列表中某個物件的第乙個匹配項 list.pop index 1 obj移除乙個元素並返...
python刷題題庫 python題庫刷題訓練
python 標準庫 math 中用來計算平方根的函式是.a sqrt b pow c power d abs c python 源 程式編譯後的擴充套件名為 a py b pdf c.python基礎100練習題 其它 工作范文 實用文件。例項 001 數字組合 python 期末試題題庫 c t...
python刷題寶 高效刷題貼
持續更 此貼只記錄需要掌握的知識點,不貼 jz1 旋轉陣列中的最小元素 根據旋轉陣列的性質,問題可以轉化為對兩個順序陣列分界點的尋找 暴力法 1.從下標為0的元素開始遍歷 2.每次進行比較,如果當前元素比相鄰的下乙個元素小,則對應的下乙個元素為最小值 一般情況 3.如果查詢到最後乙個元素都沒有出現2...