python怎么修改while循环类型_python 的for与while 的i改变
最近使用實驗樓擼代碼 http://www.shiyanlou.com/register?inviter=NTY0MzE5NDE2NjM5
做一道count and say 的算法題的時候,有c++語法的解題答案,我改成用python
題目:
The count-and-say sequence is the sequence of integers beginning as follows:
1, 11, 21, 1211, 111221, ...
1 is read off as "one 1" or 11.
11 is read off as "two 1s" or 21.
21 is read off as "one 2, then one 1" or 1211.
Given an integer n, generate the nth sequence.
Example
Given n = 5, return "111221".
Note
The sequence of integers will be represented as a string.
在用python寫的時候 我用了for中有while循環,想在while中改變i的值,也能影響外層的for中的i,但是我發現改變里層的i與外層for的i沒有影響,導致程序出錯
這是c++解法:
string countAndSay(int n) {
if (n == 0) return "";
string res = "1";
while (--n) {
string cur = "";
for (int i = 0; i < res.size(); i++) {
int count = 1;
while ((i + 1 < res.size()) && (res[i] == res[i + 1])){
count++;
i++;
}
cur += to_string(count) + res[i];
}
res = cur;
}
return res;
}
python也使用for和while時,內層的while修改了i值并不會傳遞到外層, 使重復數據被加入結果集
class Solution:
def countAndSay(self,n):
if n==0 :
return ""
res="1"
n=n-1
while n:
print ('n:',n)
print('res length',len(res))
cur=""
i=0
for i in range(len(res)):
count=1
print 'i in for:',i
while((i+1
print "i in while,before +1",i,'count',count
count=count+1
i=i+1
print 'i in while:',i,'count:',count
cur =cur+ str(count)+res[i]
print ('cur:',cur)
res=cur
print 'res:',res
n=n-1
return res
aa=Solution()
print (aa.countAndSay(4))
結果是:
shiyanlou:Code/ $ python countAndSay.py [12:35:02]
('n:', 3)
('res length', 1)
i in for: 0
('cur:', '11')
res: 11
('n:', 2)
('res length', 2)
i in for: 0
i in while,before +1 0 count 1
i in while: 1 count: 2
('cur:', '21')
i in for: 1
('cur:', '2111')
res: 2111
('n:', 1)
('res length', 4)
i in for: 0
('cur:', '12')
i in for: 1
i in while,before +1 1 count 1
i in while: 2 count: 2
i in while,before +1 2 count 2
i in while: 3 count: 3
('cur:', '1231')
i in for: 2
i in while,before +1 2 count 1
i in while: 3 count: 2
('cur:', '123121')
i in for: 3
('cur:', '12312111')
res: 12312111
12312111
python 改成while嵌套while時,程序就沒有問題了,因為內層修改的i會傳遞到上一層
class Solution:
def countAndSay(self,n):
if n==0 :
return ""
res="1"
n=n-1
while n:
print ('n:',n)
print('res length',len(res))
cur=""
i=0
while i < len(res):
count=1
print 'i in for:',i
while((i+1
print "i in while,before +1",i,'count',count
count=count+1
i=i+1
print 'i in while:',i,'count:',count
cur =cur+ str(count)+res[i]
print ('cur:',cur)
i=i+1
res=cur
print 'res:',res
n=n-1
return res
aa=Solution()
print (aa.countAndSay(4))
結果是:
shiyanlou:Code/ $ python countAndSay.py [11:13:53]
('n:', 3)
('res length', 1)
i in for: 0
('cur:', '11')
res: 11
('n:', 2)
('res length', 2)
i in for: 0
i in while,before +1 0 count 1
i in while: 1 count: 2
('cur:', '21')
res: 21
('n:', 1)
('res length', 2)
i in for: 0
('cur:', '12')
i in for: 1
('cur:', '1211')
res: 1211
1211
總結
以上是生活随笔為你收集整理的python怎么修改while循环类型_python 的for与while 的i改变的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 易语言网盘服务器源码_使用使用rclon
- 下一篇: django language_Djan