【问题标题】:a for loop for a string that has vertices, edges and faces具有顶点、边和面的字符串的 for 循环
【发布时间】:2014-08-08 06:37:01
【问题描述】:
complex = {1},{2},{3}, {1,2},{1,3},{2,3},{1,2,3} this is my string.

我想创建一个循环,让我说好的,这有

vertices = 3
edges =3
faces =1

我可以使用条件语句为“特定”结构做到这一点。但是无论我输入多少顶点边和面,我都希望它给我,以便它可以正确计数。 我的问题是 {} 我该如何处理。这有2个循环对吗?只是会想办法指挥。

我拥有的代码是我唯一能做的。请帮忙。我是 python 新手。

def nsimplex(vertices, edges, faces):
    sum = vertices + edges + faces
    if sum == 14:
         print('This is a Tetrahedron')
    elif sum == 25:
        print('This is a 4 simplex')
    else:
        print('this is a nsimplex')

    sentence = 'the sum of {} and {} and {} is {}.'.format(vertices, edges, faces, sum)
    print(sentence)


def count():
    vertices = int(input("enter number of vertices: "))
    edges = int(input("enter number of edges: "))
    faces = int(input("enter number of faces: "))
    nsimplex(vertices, edges, faces)

count()

【问题讨论】:

  • 我不确定你在问什么。英语是你的母语吗?
  • 您的帖子似乎没有意义。它们似乎相关性模糊,但是您所说的字符串与您的帖子的其余部分没有意义,并且代码所做的事情与您的任务的英文描述不匹配。非常不清楚你在问什么。
  • 你在问什么......你将你的必需品作为用户本身的原始输入? \
  • @user2357112 好的。对于造成的混乱,我深表歉意。所以我需要的是以下内容。假设我使用 {1}、{2}、{3}(必须在大括号中)等符号定义了一个复数(三角形)。我想编写一个程序,将 {x} 视为一个顶点,将 {x,y} 视为一条边,而 {x,y,z} 是一张脸。
  • @TusharGupta 很抱歉造成混乱。我在上面的评论中写了我需要的东西。我写的代码是我写的,考虑到我做了一些条件语句,它会输出顶点、边和面的数量。这需要用户在编写代码之前了解复数(四面体、三角形)。我采取了那条路线,但没有奏效。所以我想要一种更有效的方式来编写我的预期任务。

标签: python string


【解决方案1】:

我猜你正在寻找类似的东西:

comp = {1},{2},{3}, {1,2},{1,3},{2,3},{1,2,3}

print "vertices =", map(len, comp).count(1)
print "edges =", map(len, comp).count(2)
print "faces =", map(len, comp).count(3)

(我会避免使用 complex 作为变量名,因为它是 Python 中的关键字。)


编辑:如果您的输入数据确实是一个字符串,您可以简单地评估它:

comp = eval("{1},{2},{3}, {1,2},{1,3},{2,3},{1,2,3}")

编辑:如果您真的真的很想以冗长的循环方式实现它,那么您可以:

comp = "{1},{2},{3}, {1,2},{1,3},{2,3},{1,2,3}"

pos = 0
vertices = edges = faces = 0
while pos < len(comp):
    if comp[pos] == '{':
        pos = pos + 1
        count = 1
        while comp[pos] != '}':
            pos = pos + 1
            if comp[pos] == ',':
                count = count + 1
        if count == 1:
            vertices = vertices + 1
        elif count == 2:
            edges = edges + 1
        elif count == 3:
            faces = faces + 1
    pos = pos + 1

print "vertices =", vertices
print "edges =", edges
print "faces =", faces

(我讨厌这样的代码。但是如果您需要使用两个循环,那可能是一个合理的解决方案。)

【讨论】:

  • 谢谢。这很有效,你能给我一个关于如何使用循环来做到这一点的提示吗?就像一个框架作品。我的任务是使用最少 2 个循环。一个循环用于主字符串。第二个循环必须告诉我,当代码看到 { 开始计数时,当它看到 } 时停止计数。在过去的 4 天里,我一直在尝试以这种方式对其进行编码,但没有任何进展。很抱歉给您添麻烦了。
  • 再次抱歉给您带来麻烦,感谢您的宝贵时间。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-11-02
  • 2018-08-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-10-03
相关资源
最近更新 更多