我正在学习python而我正在做these exercises,特别是this one在回文产品上。
我有两个数字,我想减少1但是以交替方式:
999, 999
998, 999
998, 998
997, 998
997, 997
...
我用4 if语句解决了它,但我认为这有点草率。有没有更好的办法?贝娄是代码:
palN1 = 999
palN2 = 999
def palin(palN1, palN2):
pal = palN1 * palN2
while str(pal)[::-1] != str(pal):
if palN1%2 == 0 and palN2%2 == 0:
palN1 += -1
pal = palN1 * palN2
elif palN1%2 != 0 and palN2%2 == 0:
palN2 += -1
pal = palN1 * palN2
elif palN1%2 != 0 and palN2%2 != 0:
palN1 += -1
pal = palN1 * palN2
elif palN1%2 == 0 and palN2%2 != 0:
palN2 += -1
pal = palN1 * palN2
print [palN1, palN2]
print str(pal)
if __name__=="__main__":
palin(palN1, palN2)
BTW我得到的结果是[836,836],它的产品是698896。 这是我的第一篇文章,对不起,如果我做错了。
答案 0 :(得分:4)
您可以使用itertools.cycle
:
def solve(*args):
args = list(args)
le = len(args)
c = cycle(range(le))
print ("{} "*le).format(*args)
for _ in xrange( le*args[0] ):
i = next(c)
args[i] -= 1;
print ("{} "*le).format(*args)
...
>>> solve(999,999)
999 999
998 999
998 998
997 998
997 997
996 997
...
...
>>> solve(999,999,999)
999 999 999
998 999 999
998 998 999
998 998 998
997 998 998
997 997 998
...
...
答案 1 :(得分:2)
从两个数字中减去整数除以2的当前步数,如果步数为奇数,则从第一个数字中减去1:
>>> p = [999,999]
>>> for i in range(9):
... print( [p[0]-(i//2)-(i&1), p[1]-(i//2)] )
结果:
[999, 999]
[998, 999]
[998, 998]
[997, 998]
[997, 997]
[996, 997]
[996, 996]
[995, 996]
[995, 995]
答案 2 :(得分:1)
使用itertools.count()
创建两个计数器,并在生成器函数中交替显示:
from itertools import count
def count_two_alternate(start):
count1, count2 = count(start, -1), count(start, -1)
count_val1, count_val2 = next(count1), next(count2)
while count_val1 or count_val2:
yield count_val1, count_val2
count_val1 = next(count1)
yield count_val1, count_val2
count_val2 = next(count2)
yield count_val1, count_val2
或,具有可变数量的计数器的版本:
from itertools import cycle, counter
def count_alternate(start, counters=2):
counts = [count(start, -1) for _ in xrange(counters)]
values = [next(c) for c in counts]
indices = cycle(range(counters))
while any(values):
yield tuple(values)
index = next(indices)
values[index] = next(counts[index])
yield tuple(values)
简短演示:
>>> for c1, c2 in count_two_alternate(5):
... print c1, c2
...
5 5
4 5
4 4
3 4
3 3
2 3
2 2
1 2
1 1
0 1
0 0
或可变数字版本:
>>> for counts in count_alternate(5, 5):
... print ' '.join(map(str, counts))
...
5 5 5 5 5
4 5 5 5 5
4 4 5 5 5
4 4 4 5 5
4 4 4 4 5
4 4 4 4 4
3 4 4 4 4
3 3 4 4 4
3 3 3 4 4
3 3 3 3 4
3 3 3 3 3
2 3 3 3 3
2 2 3 3 3
2 2 2 3 3
2 2 2 2 3
2 2 2 2 2
1 2 2 2 2
1 1 2 2 2
1 1 1 2 2
1 1 1 1 2
1 1 1 1 1
0 1 1 1 1
0 0 1 1 1
0 0 0 1 1
0 0 0 0 1
0 0 0 0 0
答案 3 :(得分:0)
你可以减少最大的项目:
palN1 = 999
palN2 = 999
while palN1 and palN2:
if palN1 > palN2:
palN1 -= 1
else:
palN2 -= 1