Python: How to make numeric triangle with recursion - python

while I was working on the Python practice, I found a question that I cannot solve by myself.
The question is,
Input one integer(n), and then write the codes that make a triangle using 1 to 'n'. Use the following picture. You should make only one function, and call that function various times to solve the question. The following picture is the result that you should make in the codes.
Receive one integer as an argument, print the number from 1 to the integer received as a factor in a single line, and then print the line break character at the end. Once this function is called, only one line of output should be printed.
So by that question, I found that this is a question that requires the
recursion since I have to call your function only once.
I tried to work on the codes that I made many times, but I couldn't solve it.
global a
a = 1
def printLine(n):
global a
if (n == 0):
return
for i in range(1, a + 1):
print(i, end=" ")
print()
a += 1
for k in range(1, n+1):
print(k, end=" ")
print()
printLine(n - 1)
n = int(input())
printLine(n)
Then I wrote some codes to solve this question, but the ascending and descending part is kept overlapping. :(
What I need to do is to break two ascending and descending parts separately in one function, but I really cannot find how can I do that. So which part should I have to put the recursive function call?
Or is there another way can divide the ascending and descending part in the function?
Any ideas, comments, or solutions are appreciated.
Thx

You can use the below function:
def create_triangle(n, k: int = 1, output: list = []):
if n == 1:
output.append(n)
return output
elif k >= n:
output.append(" ".join([str(i) for i in range(1, n + 1)]))
return create_triangle(n - 1, k)
else:
output.append(" ".join([str(i) for i in range(1, n + 1)[:k]]))
return create_triangle(n, k + 1)
for i in create_triangle(5):
print(i)
Output:
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
1 2 3 4
1 2 3
1 2
1

# function to print all the numbers from 1 to n with spaces
def printLine(k):
# create a range. if k is 4, will create the range: 1, 2, 3, 4
rng = range(1, k + 1)
# convert each number to string
str_rng = map(lambda x: str(x), rng)
# create one long string with spaces
full_line = " ".join(str_rng)
print(full_line)
# capture input
n = int(input())
# start from 1, and up to n, printing the first half of the triangle
for i in range(1, n):
printLine(i)
# now create the bottom part, by creating a descending range
for i in range(n, 0, -1):
printLine(i)

Using default parameter as a dict, you can manipulate it as your function variables, so in that way, you can have a variable in your function that keeps the current iteration you are at and if your function is ascending or descending.
def triangle_line(n, config={'max':1, 'ascending':True}):
print(*range(1, config['max'] + 1))
if config['ascending']:
config['max'] += 1
else:
config['max'] -= 1
if config['max'] > n:
config['ascending'] = False
config['max'] = n
elif config['max'] == 0:
config['ascending'] = True
config['max'] = 1
Each call you make will return one iteration.
>>> triangle_line(4)
1
>>> triangle_line(4)
1 2
>>> triangle_line(4)
1 2 3
>>> triangle_line(4)
1 2 3 4
>>> triangle_line(4)
1 2 3 4
>>> triangle_line(4)
1 2 3
>>> triangle_line(4)
1 2
>>> triangle_line(4)
1
Or you can run on a loop, two times your input size.
>>> n = 4
>>> for i in range(0,n*2):
... triangle_line(n)
...
1
1 2
1 2 3
1 2 3 4
1 2 3 4
1 2 3
1 2
1

Related

Python How to make a number triangle

So I've recently started learning python and my friend gave me a changllege. How to make a number triangle. So basically, I need to make python let me input a number, for example 5. After I do that, I want python to print
54321
4321
321
21
1
But because I am new to python, I don't know how to do it.
So far, I've got this:
x = int(input('Enter a Number: '))
for i in range(x,0,-1):
print(i,end='')
if i != 0:
continue
else:
break
And the output is:
Enter a Number: 5
54321
Any ideas how to make it print
54321
4321
321
21
1
?
Thanks for any advice
Here is a sample code for you.
Short version (suggest learning about list comprehension and join functions):
x = int(input('Enter a Number: '))
for i in range(x, 0, -1):
print(''.join([str(j) for j in range(i, 0, -1)]))
Longer version which is easier to understand:
for i in range(x, 0, -1):
s = ''
for j in range(i, 0, -1):
s += str(j)
print(s)
Output:
54321
4321
321
21
1
rows = int(input("Inverted Right Triangle Numbers = "))
print("Inverted")
for i in range(rows, 0, -1):
for j in range(i, 0, -1):
print(j, end = ' ')
print()
Output
5 4 3 2 1
4 3 2 1
3 2 1
2 1
1
def trig_print(number):
if number > 0:
for i in range(number):
print(number - i,end='')
print('')
number = number - 1
trig_print(number)
else:
return 0
trig_print(5)
I used to solve it by while loop.
3 step
input initial number.
make list one to initial number.
reverse list and print it.
>>> x = int(input('Enter a Number: '))
Enter a Number: 5
>>> while x >0 :
l=list(range(1,x+1)) # range function
l.reverse() # list.reverse function
print(' '.join(map(str,l))) # join and map function
# I recomanded input space between number for readability.
x -= 1
5 4 3 2 1
4 3 2 1
3 2 1
2 1
1

How do I print every iteration possible between a multiplication of two products in a list?

Given a list with numbers between 0 and 5. I want every possible result of two numbers in this list that returns true for (a ** 2 + b ** 2) < 12.
My code for this is:
from random import choices
from math import factorial
nodes = list(range(0,6))
lis = []
for e in range(0,factorial(5)):
nodesf = choices(nodes, k= 2)
if not nodesf in lis:
if (nodesf[0]**2 + nodesf[1]**2) <= 12:
print(nodesf)
lis.append(nodesf)
lis.append(nodesf[::-1])
print(lis)
else:
lis.append(nodesf)
But, as you can see, this is probably a horrible way to solve this.
If you see a more clear and efficient code to solve this, please, help me.
You can try the combinations_with_replacement() method from the built-in module, itertools:
from itertools import combinations_with_replacement
for a, b in combinations_with_replacement(range(6), 2):
if (a ** 2 + b ** 2) < 12:
print(a, b)
Output:
0 0
0 1
0 2
0 3
1 1
1 2
1 3
2 2
The combinations_with_replacement() method is similar to the combinations() method, except the combinations_with_replacement() method allows one element to be used in the same combination more than once.
Do note that it does not include 1 0 as a solution as there already exists 0 1 in the results. If you want to include such, you can use the product() method:
from itertools import product
for a, b in product(range(6), repeat=2):
if (a ** 2 + b ** 2) < 12:
print(a, b)
Output:
0 0
0 1
0 2
0 3
1 0
1 1
1 2
1 3
2 0
2 1
2 2
3 0
3 1
What's wrong with your code ?
Iterating through range(0, factorial(5)) does not make a lot of sense to me : you're going to do 120 iterations. To solve this, you just need two compare each elements of nodes with the whole list, hence two for loops on your nodes : only 25 iterations.
Why using choices to pick elements from nodes ? It's a stochastic operation, you won't be sure to go through every elements of the list.
Simple solution
If you care about permutation, i.e. you want to get both (0, 1) and (1, 0) for example, a simple list comprehension should do the trick.
[ (a, b) for a in nodes for b in nodes if a**2+b**2<12 ]
Otherwise, just take a look at the perfect Ann Zen's answer using the itertools module :)

Python range() giving the wrong list

I am using this little code to generate a weighted modulo-103 checksum.
The problem is that when I run the following code:
def checksum_bar(array):
s = array[0]
s += array[1]
for x in range(2, len(array)):
print x
s += array[x] * x
m = s % 103
I get the following result for x when entering a array of length 10:
1
2
3
4
5
6
7
8
9
10
But when I run the following code (3rd line commented):
def checksum_bar(array):
s = array[0]
#s += array[1]
for x in range(2, len(array)):
print x
s += array[x] * x
m = s % 103
It gives me the result I want, even though I didn't change the iteration:
2
3
4
5
6
7
8
9
10
Am I missing something here? I would like to know if someone can reproduce the same result and some explanation would be very nice too.
The two sets of code provided will give the same result, because the range function is sure to start from 2

Creating a triangle using a ragged 2D array

i need to use a ragged 2D array to create a triangle like the one shown,
0 0 0 0 0 0
1 1 1 1 1
2 2 2 2
3 3 3
4 4
5
def triangle(n):
for i in range(n):
tri = n
for j in range(n-i):
tri = tri * 10 - n
print tri
i have tried this but it returns,
444445
44445
4445
445
45
Since you made atleast some effort, here it is one way to do it
We only need to iterate over the loop once. Since the index are int, we need to convert to str. Also, they start at 0 so either you iterate from n+1 or use i+1 to print so you get your expected output. You can then multiply how many times you want to print the numbers which is converted to string.
def triangle(n):
for i in range(n):
print (str(i+1) + " ") * (n - i)
Demo

Python: print without overwriting printed lines

I have
for i in range(0, 11): print i, "\n", i
I'd like my python program to print this way for each for loop
1st loop:
1
1
2nd loop:
1
2
2
1
3rd loop:
1
2
3
3
2
1
I've tried using \r\n or \033[1A but they just overwrite the previous line. Is there a way I can "push" the outputted line down so I don't overwrite it?
One way to do this,
def foo(x, limit):
if x < limit :
print x
foo(x + 1, limit)
print x
foo(1, 11)
It's not possible to do it in 1 for loop as you're currently trying.
As I suggested, you can do it like this by using lists
>>> l1 = []
>>> l2 = []
>>> for i in range(0, 11):
... l1.append(i)
... l2 = [i] + l2
>>> l1.extend(l2)
>>> for i in l1:
... print i
0
1
2
3
4
5
6
7
8
9
10
10
9
8
7
6
5
4
3
2
1
0
Concatenation of two list generators.
>>> ladder = [x for x in range(5)] + [x for x in range(5,-1,-1)]
>>> ladder
[0, 1, 2, 3, 4, 5, 4, 3, 2, 1, 0]
>>> for x in ladder:
... print x
...
0
1
2
3
4
5
4
3
2
1
0
>>>
one of ways to solve this
def two_side_print(start, end):
text = [str(i) for i in range(start,end)]
print '\n'.join(text), '\n', '\n'.join(reversed(text))
two_side_print(1, 11)
Another option is to save the printed values in a list and print that list in reverse order in each loop iteration.
My suggestion:
l = []
for i in range(1, 5):
print 'Loop '+str(i) # This is to ease seeing the printing results
for val in l:
print val
print i
l.insert(len(l),i)
for val in reversed(l):
print val
The output for a loop iterating from 0 to 5:
Loop 1
1
1
Loop 2
1
2
2
1
Loop 3
1
2
3
3
2
1
Loop 4
1
2
3
4
4
3
2
1
I hope this is what you are looking for.
You can use a recursive function to help here:
def print_both_ways(start, end):
print(start)
if start != end:
print_both_ways(start+1, end)
print(start)
Usage:
print_both_ways(1,3) # prints 1,2,3,3,2,1 on separate lines

Categories

Resources