字串翻轉,素數問題 Python解決
阿新 • • 發佈:2018-11-08
# 字串翻轉 strr=" i love china! " print(strr) str1=list(strr) def reverse(str,L,R): while L<R: t=str[L] str[L]=str[R] str[R]=t L+=1 R-=1 return str str1=reverse(str1,0,len(str1)-1) R=0 L=0 while R<len(str1): if str1[R]==' ': R+=1 continue L=R while R<len(str1): if str1[R]==' ': break R+=1 if R<len(str1): reverse(str1,L,R-1) else: reverse(str1,L,len(str1)-1) str1=''.join(str1) print(str1) #方法二 翻轉字串 new_str1=strr.split(' ') print(new_str1) # i love china! new_str1=' '.join(new_str1[::-1]) print(new_str1) # china! love i import math ###列印所有的素數 for i in range(2,1000): flag=True for j in range(2,int(math.sqrt(i)+1)): if i%j==0: flag=False break if flag: print(i,end=" ")