包含顶点,边和面的字符串的for循环

时间:2014-08-08 06:37:02

标签: python string

complex = {1},{2},{3}, {1,2},{1,3},{2,3},{1,2,3} this is my string.

我想创建一个循环,让我说好了

vertices = 3
edges =3
faces =1

我可以使用CONDITIONAL STATEMENTS为“特定”结构做到这一点。但无论我输入多少个顶点边和面,我都希望它能给我,这样它才能正确计数。 我的问题是{}我该怎么处理这个问题。这有两个循环吗?只是可以想出如何命令。

我所拥有的代码是我唯一能做的。请帮忙。我是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()

1 个答案:

答案 0 :(得分:0)

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

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

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