最新消息:

VB_Python代码对照算法百题(030)

Python 少儿编程 1630浏览 0评论

 VB代码:(2018年8月浙江名校新高考联盟)16.【加试题】某种纸牌游戏,三人一起玩一副牌,每人 17 张。5 张及以上的连续单牌(不分花色)称为顺子,顺子最大到K,如“A,2,3,4,5,6”是长度为 6 的顺子。编写程序,判断游戏刚开始时某玩家有没有顺子,最长的顺子是几张。

实现上述功能的 VB 程序代码如下,但加框处代码有错,请改正。
Const n = 17

Dim a(n) As Integer

Private Sub Command1_Click()

Dim max As Integer, count As Integer

Dim i As Integer, j As Integer

count = 0: max = 0

i = 1

Do While i <= n -1

    count = 0

    j = i + 1

    Do While j <= n

        If a(j) = a(j -1) – 1 Then

            j = j + 1

            count = count + 1

        ElseIf a(j) = a(j – 1) Then

            j = j + 1

        Else

            Exit Do ’

        End If

    Loop

    i = j

    If count > max Then max = count

Loop

If max < 5 Then

    Label2.Caption = “无顺子”

Else

    Label2.Caption = “最长顺子长度:” + Str(max)

End If

End Sub

Private Sub Form_Load()

‘获取 17 张牌的数值(J、Q、K、A分别对应11、12、13、1),升序存储在数组 a 中

‘代码略End Sub

参考答案:

(1)count = 1(1分)

(2)a(j) = a(j – 1) + 1  (或其他等价答案) (2分)

Python参考代码如下:

a=[]

i=0

while i<17:

    x=int(input(‘请发一张牌:n’))

    a.append(x)

    i+=1

print(a)

a=sorted(a)

count=0

ma=0

i=0

while i<=15:

    count=1

    j=i+1

    while j<=16:

        if a[j] == a[j - 1] + 1:

            j=j+1

            count +=1

        elif a[j]==a[j-1]:

           j=j+1

        else:

            break

    i=j

    if count>ma:

        ma=count

if ma<5:

    print(‘无顺子!’)

else:

    print(‘最长顺子长度:’ ,str(ma))

VB_Python代码对照算法百题(030)

VB_Python代码对照算法百题(030)

Python代码运行结果:

VB_Python代码对照算法百题(030)

VB_Python代码对照算法百题(030)

 

您必须 登录 才能发表评论!