You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用FOR循环从含分隔符字符串生成表格并移除逻辑表达式

移除表格生成代码中的逻辑表达式

需求概述

  • 根据给定宽度、高度,从6字符字符串生成表格,使用2个指定分隔符,分隔符不得出现在每行首尾
  • 禁止使用import、def、if、else、while、iter、[、]等语法,仅允许Python基础函数与for循环

示例效果

3x5表格,字符串为Python,分隔符为+和-,输出如下:

P+y-t+h-o
n+P-y+t-h
o+n-P+y-t

修改后的代码

# width = int(input("?"))
# height = int(input("?"))
# word = input("?")
# separators = input("?")
width = 13
height = 6
word = "matfyz"
separators = "()"
separator1, separator2 = separators
length = width * height
count = (length) // len(word) + 1
string = ""

for _ in range(count):
    for letter in word:
        string += letter

for row in range(height):
    temp_separator = ''
    current_sep1, current_sep2 = separators
    for col in range(width):
        # 计算当前单元格的位置索引
        pos = col + width * row
        # 直接输出分隔符+对应字符
        print(temp_separator + string[pos], end='')
        # 切换下一个分隔符
        temp_separator = current_sep1
        current_sep1, current_sep2 = current_sep2, current_sep1
    print('')

关键修改点

  • 移除逻辑表达式:通过计算单元格的绝对位置pos = col + width * row,直接从预先生成的长字符串中提取目标字符,彻底消除了原代码中的条件逻辑运算。
  • 合规切换分隔符:在每行循环内重新初始化分隔符变量,通过变量交换current_sep1, current_sep2 = current_sep2, current_sep1实现分隔符交替,符合禁止使用if/else的要求。
  • 简化循环结构:删除了原代码中冗余的内层字符遍历循环,直接定位目标字符,既满足语法限制又提升了代码效率。

内容的提问来源于stack exchange,提问作者Illia Shkudskyi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.17 10:28:09