Creating number patterns in python - python

I am trying to create 2 patterns of similar type (in python):
1
2 2
3 3 3
and
1
2 3
4 5 6
up to a length specified by the user
I have written a code to print the pattern of the 1st type:
def rec1():
for i in range(0,n,1):
count=i
print(" "*(n-i) + str(i+1) + " ",end=" ")
if count!=0:
rec2(i+1)
else:
print("\n")
def rec2(x):
print(str(x) + " ",end=" ")
count=count-1
if count>0:
rec2(x)
else:
print("\n")
return
count=0
n=int(input("Number?"))
rec1()
However i am getting the following error:
Number?5
1
2 2 *Traceback (most recent call last):
File "C:/Python34/pattern1.py", line 33, in <module>
rec1()
File "C:/Python34/pattern1.py", line 18, in rec1
rec2(i+1)
File "C:/Python34/pattern1.py", line 24, in rec2
count=count-1
UnboundLocalError: local variable 'count' referenced before assignment*
Can anyone provide a more efficient code?

Try this:
def rec1(n):
for i in range(1,n+1,1):
s = ""
s += (" "*(n-i))
for j in range(0,i,1):
s += (str(i) + " ")
print(s)
n=int(input("Number?"))
rec1(n)
You don't need rec2

The following is another approach to generate the first and second pattern:
def generate(n, flag = 0):
""" n: number; 0 is 1st pattern; 1 is 2nd pattern """
g = [range(1,n+2)[i*(i+1)/2:i*(i+1)/2 +i+1] for i in range((n+2)/2-1)] if flag else \
[ (i,)*i for i in range(1, n+1)]
return [' '* range(1,len(g)+1)[::-1][i] + ' '.join([str(j) for j in g[i]]) for i in range(len(g))]
for t in generate(6, 0): print t # 1st pattern
for t in generate(6, 1): print t # 2nd pattern
Output:
1
2 2
3 3 3
4 4 4 4
5 5 5 5 5
6 6 6 6 6 6
1
2 3
4 5 6

Related

Printing 10 values per line

I'm new to python and have a question
I want to print 10 values per line and I can't figure out how to do it. Here's my attempt at it;
a = 1
b = 15
count = 0
count_end = 10
while count < count_end:
while a < b:
count = count + 1
print(a, end = " ")
a = a + 1
if(count == count_end):
break
The output is 1 2 3 4 5 6 7 8 9 10 but I want the output to go from 1 to 10 on one line and then continue from 11 to 15 on a new line under it. I've seen some people use lists to answer a similar question but I don't want to use lists for this question.
Any help would be greatly appreciated :)
Just use one loop, and then check if count % count_end == 0 to detect every multiple of count_end.
for count, current in enumerate(range(a, b)):
print(current, end=" ")
if count % count_end == 0 or current == b-1:
print()
a = 1
b = 15
count = 0
count_end = 10
while count < count_end:
while a <= b:
count = count + 1
print(a, end = " ")
a = a + 1
if(count == count_end):
print("")
something like this ?

Sum input integer by itself, integer times

Salam, I'm given a user input that I have to sum it by itself n-times. Which means if the input is "5" for example, I should return 5 + 5 + 5 + 5 + 5 = 25
I used:
def sum(user_input):
inp_sum = 0
string = ''
for n in range(0, user_input, 1):
inp_sum += user_input
if n != user_input -1:
string+= "5 + "
else: string += '5'
return string + ' = ' + str(inp_sum)
but it returns
Failed for value=6
Expected: 6 + 6 + 6 + 6 + 6 + 6 = 36
Actual: 5 + 5 + 5 + 5 + 5 + 5 = 36
what is the solution?
You hardcoded 5 in to the logic of your function, when you should be passing in the user input to the string format logic. Also, do not name your function sum as you will shadow the built-in function sum.
def mysum(user_input):
inp_sum = 0
string = ""
for n in range(0, user_input, 1):
inp_sum += user_input
if n != user_input - 1:
string += "{} + ".format(user_input)
else:
string += str(user_input)
return "{} = {}".format(string, inp_sum)
You can simplify it like this:
def user_input(n):
return "{} = {}".format(' + '.join([str(n) for _ in range(n)]), str(n*n))
print(user_input(5))
# 5 + 5 + 5 + 5 + 5 = 25
print(user_input(6))
# 6 + 6 + 6 + 6 + 6 + 6 = 36

About new line and space after last row and last column respectively

What I must get as output, exactly like this :
Example-1:
Input:
3
Output:
1\n
1 2\n
1 2 3
Example-2:
Input:
4
Output:
1\n
1 2\n
1 2 3\n
1 2 3 4
In the first example the input was 3. Hence there are 3 rows. The first row has element 1. The second row contains two elements 1 and 2 and the third row contains 1, 2 and 3 separated by a space.
What I actually get to: Example 1- 1 \n Example 2 - 1 \n
the below code and I don't 1 2 \n 1 2 \n
want this as an output 1 2 3 \n 1 2 3 \n
1 2 3 4 \n
There should not be any space after the each element of the last column and no new line after the last row.
My code:
n = int(input())
i=1
j=1
for i in range(1,n+1):
for j in range(1,i+1):
if i>=j:
print(j, end=" ")
if(i!=j):
print(end="")
print()
You can use:
N = 5
result = '\n'.join(
# space delimited numbers from 1 to current loop
' '.join(str(i) for i in range(1, j))
# for everything for 1..2, 1..3, 1..4 etc...
# since range(1,1) is empty and we're starting from 2,
# we use N+2 to ensure all loops are counted
for j in range(2, N + 2)
)
Which'll give you:
'1\n1 2\n1 2 3\n1 2 3 4\n1 2 3 4 5'
​
lst_number= []
my_input = int(input("Enter Number:: "))
for i in range(0,my_input):
for j in range(i+1):
lst_number.append(j)
print(''.join([str(val) for val in lst_number]))
In case you are wondering, this is how I want my pattern output to be:
Example-1:
Input:
3
Output:
1\n
1 2\n
1 2 3
Example-2:
Input:
4
Output:
1\n
1 2\n
1 2 3\n
1 2 3 4
You're going to want to have a start state and an adding state. The adding state is pre-pended with a space. Each adding state is appended to the start state in turn. When you're done with the row, append a new line character.
start state: "1"
adding state: " " + n
roll over an array from 2 to n, append the changed adding state to the current answer
append end of line character
In Javascript...
var start = 1
var limit = 4
for(var i = 1; i <= limit; i++){
let retval = start;
for (var j = 2; j <= i; j++){
retval = retval + ' ' + j;
}
if (i < limit)
retval = retval + '\\n';
$('<div>' + retval + '</div>').appendTo('#out');
}
https://jsfiddle.net/etLms32o/6/
Try this.It worked for me.
n = int(input())
for i in range(1,n+1):
count = 1
for j in range(1,i+1):
if j == i:
print(count,end = "\n")
count+=1
else:
print(count,end = " ")
count+=1
a,b=map(int,input().split())
n=0
for i in range(a):
for j in range(b):
n=n+1
if(j<(b-1)):
print(n,end =' ')
elif(n==a*b):
print(n,end ='')
else:
print(n)

Backward Modulo/Reminder Cycle

Using Python as an example:
for i in range(-5, 5, 1):
print(i % 4, end = " ") ## Will output 0 1 2 3 0 1 2 3...
Is there a nice way do get a reverse cycle with decreasing input including negative numbers? How would I get the following without using conditions?
for i in range(5, -5 , -1):
print('''Something here''', end = " ") ## Will output 3 2 1 0 3 2 1 0...
What's wrong with this simple offset shift:
for i in range(5, -5 , -1):
print((i+2)%4, end = " ")
outputs:
3 2 1 0 3 2 1 0 3 2

Recursive numeric triangle in python

I'm trying to create a triangle like the following:
1 2 3 4 5 6
2 3 4 5 6
3 4 5 6
4 5 6
5 6
6
Without using while, for in, lists, etc. Just "if-else" cases and recursive functions. I've just learned how to do an asterisk triangle.
def triangle(i, t=0):
if i == 0:
return ' '
else:
print '*' * i
return triangle( i - 1, t + 1 )
triangle(6)
It has the same idea I want to apply to my exercise, but I really don't know how to do with the code for changing term by term and print them all to the right like this one.
Here is my solution. Note that there is neither range nor join, which implies for or list
In [1]: def tri(size, row = 0, col = 0):
...: if row < size:
...: num = row + col + 1
...: if num == size + 1:
...: print '\n',
...: tri(size, row + 1, 0)
...: if num <= size:
...: print num, '',
...: tri(size, row, col + 1)
...:
In [2]: tri(6)
1 2 3 4 5 6
2 3 4 5 6
3 4 5 6
4 5 6
5 6
6
If range is acceptable, then here is a short one:
def tri2(size):
row = map(str, range(1, size + 1))
print '\n'.join(map(lambda n: ' '.join(row[n:]), range(size)))
You can use range() or xrange() to get the list of numbers, and decrease the range with each recursion:
def triangle(i, t):
if i == t:
return i
else:
print " ".join([str(x) for x in range(i,t+1)])
return triangle( i + 1, t )
output:
>>> triangle(1,6)
1 2 3 4 5 6
2 3 4 5 6
3 4 5 6
4 5 6
5 6
6
>>> triangle(1,8)
1 2 3 4 5 6 7 8
2 3 4 5 6 7 8
3 4 5 6 7 8
4 5 6 7 8
5 6 7 8
6 7 8
7 8
8
By calling the function recursively You have realized a kind of loop.
Now you can replicate the same idea:
def OneLess(i,j):
print i,
if i < j:
OneLess(i+1,j)
else:
print ""
def triangle(i, t=1):
OneLess(t,i)#print '*' * i
if i == t:
return ' '
return triangle( i , t + 1 )
triangle(6)
I'd suggest something like this:
def triangle(i, t = 1):
if i > 0:
print ' '.join([str(n+t) for n in range(i)])
triangle( i - 1, t + 1 )
The range gives you a list of the numbers needed at each level, and the t offset is increased by one so you're starting from a higher value each level you go down.
Update
I've just noticed your requirement for no for in and lists, which probably makes the above example wrong. So here is another suggestion using only recursion:
def triangle(size, col = 1, row = 1):
if col < size:
print col,
triangle(size, col+1, row)
else:
print col
if row < size:
triangle(size, row+1, row+1)

Categories

Resources