我的递归代码继续循环大约1个额外时间(4次),而不是任何解决方案的3次

时间:2019-06-08 16:37:18

标签: python

我的问题是我的子例程多了大约1次(4次),我不确定该怎么办。我不希望它自身重复4次。我只希望它自身重复3次。

if尝试和带if语句的elif语句,而我尝试用最终的if语句交换while循环的位置。

import random

cards =['Ah','2h','3h','4h','5h','6h','7h','8h','9h','10h','Jh','Qh','Kh', 
        'Ad','2d','3d','4d','5d','6d','7d','8d','9d','10d','Jd','Qd','Kd',
        'As','2s','3s','4s','5s','6s','7s','8s','9s','10s','Js','Qs','Ks',
        'Ac','2c','3c','4c','5c','6c','7c','8c','9c','10c','Jc','Qc','Kc']

complete = random.sample(cards, 21)



def card_trick(complete, a):

    set_1 = complete[0::3]
    set_2 = complete[1::3]
    set_3 = complete[2::3]

    print ('it goes set 1, set 2, set3')
    for i in range(0,7):
        print(set_1[i],   set_2[i],    set_3[i])

    bong = int(input('enter the set your card is in 1 or 2 or 3:  '))

    if bong == 1:
        complete = set_2 + set_1 + set_3

    if bong == 2:
        complete = set_1 + set_2 + set_3

    if bong == 3:
        complete = set_1 + set_3 + set_2

    if a == 3:
        print ('your card is', complete[10])
        print ('if a == 3:, a =', a)

    while a != 3:
        a = a+1
        print ('a ================', a)
        card_trick(complete, a)

card_trick(complete, 1)

所以实际结果是这个

it goes set 1, set 2, set3
As 7c 9h
Qh 8c Ah
9s 10h 3c
Qs 4h 2s
Kh 7h Js
Ks 5s 3s
Jc 10s 5d
enter the set your card is in 1 or 2 or 3:  3
a ================ 2
it goes set 1, set 2, set3
As Qh 9s
Qs Kh Ks
Jc 9h Ah
3c 2s Js
3s 5d 7c
8c 10h 4h
7h 5s 10s
enter the set your card is in 1 or 2 or 3:  2
a ================ 3
it goes set 1, set 2, set3
As Qs Jc
3c 3s 8c
7h Qh Kh
9h 2s 5d
10h 5s 9s
Ks Ah Js
7c 4h 10s
enter the set your card is in 1 or 2 or 3:  1
your card is 9h
if a == 3:, a = 3
a ================ 3

#from here onwards is crap, how can i get rid of this#

it goes set 1, set 2, set3
As Qh 9s
Qs Kh Ks
Jc 9h Ah
3c 2s Js
3s 5d 7c
8c 10h 4h
7h 5s 10s
enter the set your card is in 1 or 2 or 3:  2
your card is 2s
if a == 3:, a = 3

1 个答案:

答案 0 :(得分:0)

将while循环更改为if语句。我试图使问题更直观:

card_trick(..., a=1)
    ...
    # a == 1
    while a != 3:
    a = 1 + 1
    # a == 2
    card_trick(..., a=2)
        ...
        #a == 2
        while a != 3:
        a = 2 + 1
        # a == 3
        card_trick(..., a=3)
            ...
            #a == 3
            while a != 3:
                # a == 3, do nothing, recursion ends, call-stack unwinds
        # a == 3, while loop of second recursion ends, go up one recursion depth
    # a == 2 on this recursion depth, so while loop goes for one more iteration
    a = 2 + 1
    # a == 3
    card_trick(..., a=3)...