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.
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.
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)
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With