Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trying to build triangle of symbols in Python

Tags:

python

So my professor is trying to get us to write a function within a function that prints a triangle of different symbols, like this:

&

&

&&

%

%%

%%%

@

@@

@@@

@@@@

I can write the triangle function and have it print in that format, but I'm having a difficult time making the mental leap to attach a variable symbol element. In short, I can print the proper shape, but not with different symbols. Here's what I have so far:

s = "&"
def stars(i):
    '''Prints n number of stars'''
    print(i*s)

def triangle_of_symbols(s, n):
    '''Creates symbol triangle function with variable n.'''
    for i in range (n):
        stars(i+1)

triangle_of_symbols(s, 1)

triangle_of_symbols(s, 2)

triangle_of_symbols(s, 3)

triangle_of_symbols(s, 4)

How would I accomplish this? Even being pointed in the right direction would be enormously helpful right now.

like image 552
CodeBlue04 Avatar asked Apr 23 '17 21:04

CodeBlue04


People also ask

What type are symbols in python?

No, python doesn't have a symbol type. However string literals are interned by default and other strings can be interned using the intern function.


2 Answers

Your stars function currently takes i, which is how many stars to print, and then pulls from the global variable s for what symbol to print.

Instead, parameterize s in stars so you can tell the function which symbol to print on each call.

def starts(i, s):
    print(s * i)  # I think that order scans better -- "s, i times". YMMV

Then in triangle_of_symbols pass s along with i+1.

...
for i in range(n):
    stars(i+1, s)

though really there's little reason to separate the two functions.

def triangle_of_stars(s, n):
    for i in range(n):
        print(s * i+1)
like image 124
Adam Smith Avatar answered Oct 16 '22 18:10

Adam Smith


You can also put your symbols in a dictionary.

shapes = {"stars": "*", "at": "@"}


def generate_triangle(shape_key, lines):
    for i in range(lines):
        print (shapes[shape_key] * (i+1))


generate_triangle('at', 4)
generate_triangle('stars', 4)
like image 2
vonBerg Avatar answered Oct 16 '22 17:10

vonBerg