首页 > 编程语言 >python N 字形变换 多种解法

python N 字形变换 多种解法

时间:2023-12-13 13:32:58浏览次数:36  
标签:index rows 字形 python len numRows step result 解法

解法一:使用二维数组

def convert(s, numRows):
    if numRows == 1 or numRows >= len(s):
        return s
    
    rows = [''] * numRows
    index, step = 0, 1
    
    for char in s:
        rows[index] += char
        
        if index == 0:
            step = 1
        elif index == numRows - 1:
            step = -1
            
        index += step
    
    return ''.join(rows)

解法二:使用列表存储每行的字符

def convert(s, numRows):
    if numRows == 1 or numRows >= len(s):
        return s
    
    rows = [[] for _ in range(numRows)]
    index, step = 0, 1
    
    for char in s:
        rows[index].append(char)
        
        if index == 0:
            step = 1
        elif index == numRows - 1:
            step = -1
            
        index += step
    
    result = ''
    for row in rows:
        result += ''.join(row)
    
    return result

解法三:直接计算字符在每行的索引位置

def convert(s, numRows):
    if numRows == 1 or numRows >= len(s):
        return s
    
    n = len(s)
    cycle_len = 2 * numRows - 2
    result = ''
    
    for i in range(numRows):
        for j in range(i, n, cycle_len):
            result += s[j]
            
            if i != 0 and i != numRows - 1 and j + cycle_len - 2 * i < n:
                result += s[j + cycle_len - 2 * i]
    
    return result

标签:index,rows,字形,python,len,numRows,step,result,解法
From: https://blog.51cto.com/lzning/8801680

相关文章

  • 随机模拟——蒙特卡洛算法的Python实现
    蒙特卡洛方法是一类基于随机抽样的数值计算技术,通过模拟随机事件的概率过程,从而近似计算复杂问题的数学期望或积分。其核心思想是通过大量的随机抽样来逼近问题的解,从而在随机性中获得问题的统计特性。蒙特卡洛方法广泛应用于概率统计、物理学、金融工程、生物学等领域。在蒙特卡......
  • python——小游戏(ball,bird)
      ball #-*-coding:utf-8-*-"""CreatedonWedDec1309:19:382023@author:kabuqinuo"""importsys#导入sys模块importpygame#导入pygame模块pygame.init()#初始化pygamesize=width,height=640,480#设置窗......
  • Python——第五章:hashlib模块
    hashlib模块hashlib模块是Python中用于加密散列(hash)算法的模块。它提供了对常见的哈希算法(如MD5、SHA-1、SHA-256等)的支持,使得开发者可以轻松地在其应用中进行数据的安全散列。以下是hashlib模块中一些常用的哈希算法:MD5(MessageDigestAlgorithm5):产生128位的哈......
  • 【python】文件锁模块fcntl
      #!/usr/bin/python#coding:utf8importosimportsysimporttimeimportfcntl#导入模块classFLOCK(ojbect):def__init__(self,name):""":paramname:文件名"""self.fobj=open(name,'......
  • Python报错:performance hint: av/logging.pyx:232:5: the GIL to be acquired
     参考:https://stackoverflow.com/questions/77410272/problems-installing-python-av-in-windows-11https://github.com/PyAV-Org/PyAV/issues/1177  ================================  报错信息:C:\Windows.old\Users\chris>pipinstallavDefaultingtouserinstallatio......
  • Python报错:pkg-config could not find libraries ['avformat', 'avcodec', 'av
    参考:https://github.com/PyAV-Org/PyAV/issues/238https://pyav.org/docs/6.1.2/installation.html#mac-os-x  =====================  报错信息:C:\Users\liuxue>pipinstallavCollectingavUsingcachedav-0.3.3.tar.gzInstallingcollectedpackages:avRunning......
  • Python学习多线程、多进程、多协程记录
    一、多线程应用于请求和IO#1.Python中关于使用多线程多进程的库/模块#2.选择并发编程方式(多线程Thread、多进程Process、多协程Coroutine)前置知识: 一、三种有各自的应用场景 1.一个进程中可以启动多个线程 2.一个线程中可以启动多个协程 二、各自优缺点 1......
  • Python各种奇奇怪怪的写法以及常用案例
    工具类common#####工具类commonimportrequestsimporttimeimportjsonimportrandomimportosfromlxmlimportetreeimportconcurrent.futuresfromurllib.parseimportunquote,quotefromPILimportImagedefstrClear_v1(str):try:returnst......
  • 用python实现电子公文传输系统中遇到的数据库连接问题
    在实现电子公文传输系统时,数据库连接是一个重要的问题。Python中有多种库可以用于数据库连接,比如SQLite、MySQL、PostgreSQL等。下面是一个简单的示例,演示如何使用Python连接MySQL数据库:importmysql.connector#连接数据库conn=mysql.connector.connect(host="localhos......
  • python 报错应对列表
    =========================RESTART:D:/Python37/ziti1.py========================Traceback(mostrecentcalllast):File"D:/Python37/ziti1.py",line1,in<module>importdocxModuleNotFoundError:Nomodulenamed'docx'>>......