python打印字母表

题目:

1 A B C D E F G H

2 V W X Y Z A B I

3 U J K L M N C J

4 T I H G F E D K

5 S R Q P O N M L

输入:一行字符串,包含两个M,N,M和N均为大于0,小于10000的整数,M代表行,N代表列。

输出:M*N的矩阵,以空格分隔。


题目解析:

        在这个矩阵中,是按照顺时针填入字母(右->下->左->上->右->下->......)

        因此,首先想到了顺时针打印矩阵,其次将字母输入进位置。


代码:j

class Solution:
    def huihuanzimu(self, M, N):
        left, right, top, bottom = 0, N-1, 0, M-1
        matrix = [[0] * N for i in range(M)] 
        x = 'A'
        count = 0
        while left <= right and top <= bottom:
            for row in range(left, right): 
                matrix[top][row] = x
                x = chr(ord(x) + 1)   
                count += 1
                if count >= 26:
                    x = 'A'
                    count = 0
                print(count)
                print(matrix[top][row])
            for col in range(top, bottom):
                matrix[col][right] = x
                x = chr(ord(x) + 1)
                count += 1
                if count >= 26:
                    x = 'A'
                    count = 0
            #if left < right and top < bottom:
            for row in range(right, left, -1):
                matrix[bottom][row] = x
                x = chr(ord(x) + 1)
                count += 1
                if count >= 26:
                    x = 'A'
                    count = 0
            for col in range(bottom, top, -1):
                matrix[col][left] = x
                x = chr(ord(x) + 1)
                count += 1
                if count >= 26:
                    x = 'A'
                    count = 0
                                      
            left += 1
            right -= 1
            top += 1
            bottom -= 1
        for i in range(M):
            for j in range(N):
                print(matrix[i][j], end = " ")
            print()
        
solution = Solution()
solution.huihuanzimu(10,8)

结果:


 代码遇到的问题:

1.如何顺时针打印矩阵?

答:采用四个指针,分别记录上下左右。

2.如何创建python二维数组?

答: matrix = [[false] * N for i in range(M)]

        对于[[false] * N] * M 改变第一个的数的时候,也会将其他同时改变。

3.如何打印英文字母?

答:ASCII码:‘A’:65,‘a’:97。

        chr():将数字转化为字母。 

        ord():将字母转化为数字。

        本题中,还需注意到超出后,需要再从A开始。

如果大家有更好的解决方法,希望和大家共同探讨!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值