How to write such a number pattern problems in python 3? - python

For example, if given a number 3, the program will print
1
1 2 2
1 2 2 3 3 3
OK,what I have tried like this:
n = eval(input("Enter a positive integer: "))
a=1
for i in range(1,n+1):
for j in range(1,a+1):
print(j," ",sep="",end="")
a+=1
print()
It will print like:
1
1 2
1 2 3

You were close. Your problem is that you need to use j to print the current number j times. Thankfully, Python makes this easy by using sequence multiplication. That is, Python allows you to multiply a sequence - like a string - by a number. The contents of the string is replicated the amount of times it was multiplied by:
>>> 'a' * 3
'aaa'
>>> '1' * 4
'1111'
Thus, you can convert the current integer j to a string, and multiplied the string by j:
for j in range(1, a + 1):
print((str(j) + ' ') * j, sep='', end="")
With the above change your code now outputs:
Enter a positive integer: 3
1
1 2 2
1 2 2 3 3
Here are a few more ways you can improve your code.
Avoid eval like the black plague. It's very dangerous security-wise. Of course, you probably don't even have to worry about this now, but better not get in the habit. There's always a Better Way TM. In this case, use the built-in function int.
Rather than keeping an explicit counter with a, use the built-in function enumerate.
With the above improvements, your code becomes:
n = int(input("Enter a positive integer: "))
for a, i in enumerate(range(1, n + 1), 1):
for j in range(1, a + 1):
print((str(j) + ' ') * j, sep='', end="")
print()

You're missing a key thing in the code you've given (as below):
n = eval(input("Enter a positive integer: "))
a=1
for i in range(1,n+1):
for j in range(1,a+1):
print(j," ",sep="",end="")
a+=1
print()
Within the for j in range(...) loop, where you actually print out each number, you only print the each number out once, rather than j times (where j is the current number).
You can fix this by using a special behavior of Python (string 'multiplication').
n = eval(input("Enter a positive integer: "))
a = 1
for i in range(1, n+1):
for j in range(1, a+1):
print('{} '.format(j) * j, end="")
a += 1
print()

Here is a method that does what you're requesting.
def numbers(n: int) -> None:
for i in range(1, n+2):
for j in range(1, i):
print(j * (str(j) + ' '), end='')
print()
First, we loop over all numbers from 1 to n+1.
Then, we loop over all numbers from 1 to the current number we are working with, minus one (that's why we have the n+2 in the outer loop).
Now we have all the information we need to print our line: we are printing j times the value of j followed by a space, appending it to whatever was printed on this line already before.
Finally, after finishing our line, we print a newline, so we can start fresh in the next outer loop.
Hope this helps!

You are definitely on the right track. Let's look closer at your code:
n = eval(input("Enter a positive integer: "))
a=1
for i in range(1,n+1):
for j in range(1,a+1):
print(j," ",sep="",end="")
a+=1
print()
i is going iterate from 1 to n. That's a good intuition, as we need every number.
j is going iterate from 1 to a. A way to debug the code is to work through an example. Let's say i will iterate in range(1, 3). The first time in the loop, j will iterate in range(1, 2) and it'll print "1". The second time, j will iterate in range(1, 3) and it'll print "1 2". There's our problem; we wanted 2 to print out twice!
i is actually the number we want to print, j is the number of times we want to print the number. We actually don't need the a variable:
n = int(input("Enter a positive integer: "))
message = ""
for i in range(1, n + 1):
for j in range(0, i):
message += str(i) + " "
print(message)
We can condense this further. I try to think of it in my head first, and then code it.
"I want 1 once, 2 twice, 3 thrice, etc.". This means, we don't even need an inner loop. You know how many times you want to print i... i times!
message = ""
for i in range(1, n + 1):
message += (str(i) + " ") * i
print(message)
Also, notice the style in your code. PEP8 has guidelines for how to write proper Python code. Notice:
Using "int" is better than "eval" if possible, because you only want your program to take numbers.
Spacing in parenthesis "range(1, a+1)" is better than "range(1,a+1)".
Variable declarations like "a = 1" is better than "a=1".
These best practices will make your code more readable :)

>>> print(*[' '.join(map(str, [n for n in range(1, n+1) for n in [n]*n])) for n in range(1, n+1)], sep='\n')
1
1 2 2
1 2 2 3 3 3

Related

one while loop to count up and down

How do you write a program to count up and down from a users integer input, using only one while loop and no for or if statements?
I have been successful in counting up but can't seem to figure out how to count down. It needs to look like a sideways triangle also, with spaces before the number (equal to the number being printed).
this is my code so far;
n = int(input("Enter an integer: "))
i = " "
lines = 0
while lines <= n-1:
print(i * lines + str(lines))
lines += 1
You can solve this by making good use of negative numbers and the absolute value: abs() which will allow you to "switch directions" as the initial number passes zero:
n = int(input("Enter an integer: "))
s = " "
i = n * -1
while i <= n:
num = n - abs(i)
print(s * num + str(num))
i += 1
This will produce:
Enter an integer: 3
0
1
2
3
2
1
0
Move the print line to after the while loop. Form a list of lists (or an array) in the while loop using the content from your current print statement. Then create a second statement in your single while loop to count down, which creates a second list of lists. Now you can sequentially print your two lists of lists.

For loop overiding the previous result

Count the number of trailing 0s in factorial of a given number.
Input Format
First line of input contains T - number of test cases. Its followed by T lines, each containing an integer N.
Output Format
For each test case, print the number of trailing 0s in N!, separated by new line
Here's the code for the above problem
`n=int(input())
for i in range (0,n):
num=int(input())
count=0
i=5
m=num/i
for i in range (m>=1):
count= count+m
print(count)`
the expected output is:
Input:
2
5
10
output:
1
2
but only 2 is being displayed as output overriding 1
plz help
You just need to move your print statement into your outer loop:
result = []
n = int(input())
for i in range(0, n):
num = int(input())
count = 0
i = 5
m = num / i
for i in range(m >= 1):
i * 5
count = count + m
result.append(count) # <- print statement was here but I added extra indent and then changed to append
for count in result:
print(count)
Per your comment, I also added code to store up your results instead of printing each result right away, so that they will all be printed at the end, after you've given all of your input.
This is one of the downsides of Python using indentation as language syntax. It's easy to make these sorts of mistakes.
btw, this gives the output you expect, but what do you think the line i * 5 is doing? It isn't doing anything. Also, with range(m >= 1), you're creating a range from a boolean value, which is strange.
This code finds no. Of trailing zeroes in factorial of numbers
for i in range(int(input())):
a=int(input())
f=1
c=0
for j in range(1,n+1):
f*=j
while(f%10==0):
f/=10
c+=1
print(c)

printing a number pattern in python without white space and new line at the end

The aim is to print a pattern half triangle depending upon the user input for example if the user input is 3 the pattern would be
1
1 2
1 2 3
but upon executing there is a space after the each element of the last column and a new line (\n) after the last row. i would like to remove that please help.
1 \n
1 2 \n
1 2 3 \n
likewise whereas the expected output is
1\n
1 2\n
1 2 3
here is the code i wrote
rows = int(input())
num = 1
for i in range (0, rows):
num = 1
for j in range(0, i + 1):
print(num,end=" ")
num = num + 1
print("")
Others have already shown the alternatives. Anyway, I believe that you are learning, and you want to understand that exact case. So, here is my comment.
YOU print the space. You cannot unprint it when already printed. There are more ways to solve that. If you want to preserve the spirit of your solution, you must not print the space after the last num. You can do one less turn of the inner loop, and print the last num separately, like this:
rows = int(input())
num = 1
for i in range (0, rows):
num = 1
for j in range(0, i):
print(num, end=' ')
num = num + 1
print(num)
In the example, the first num line can be removed. Also, you combine counted loop with your own counting (the num). It usually means it can be simplified. Like this:
rows = int(input('Type the number of rows: '))
for i in range (0, rows):
for j in range(1, i + 1):
print(j, end=' ')
print(i + 1)
Now, some experiment. Everything under the outer loop is actually printing a row of numbers. The sequence is generated by the range -- the generator that produces the sequence. When the sequence is wrapped by list(), you get a list of the numbers, and you can print its representation:
rows = int(input('Type the number of rows: '))
for i in range (1, rows + 1):
print(list(range(1, i + 1)))
It prints the result like...
[1]
[1, 2]
[1, 2, 3]
[1, 2, 3, 4]
[1, 2, 3, 4, 5]
Instead, you want to print the sequences of the same numbers joined by space. For that purpose, you can use join. However, you have to convert each of the elements to a string:
rows = int(input('Type the number of rows: '))
for i in range (1, rows + 1):
print(' '.join(str(e) for e in range(1, i + 1)))
And that is already similar to the solutions presented by others. ;)
Its too simple than the code you have made:
a = int(input("Enter a num: "))
for i in range(a+1):
print(" ".join(list(map(str,range(1,i+1)))),end="")
if i != a:print("")
Executing:
Enter a num: 3
1
1 2
1 2 3
>>>
I suggest you the following soltuion, building the whole result string first before printing it without new line character at the end:
my_input = int(input("Enter a num: "))
s = ""
for i in range(my_input):
s += " ".join([str(j) for j in range(1,i+2)])
s += "\n" if i != my_input-1 else ""
print(s, end="")
My version of your requirement,
rows = int(input('Enter a number - '))
num = 1
for i in range(0, rows):
num = 1
tmp = []
for j in range(0, i + 1):
tmp.append(str(num))
num = num + 1
if i + 1 == rows:
print(repr("{}".format(' '.join(tmp))))
else:
print(repr("{}\n".format(' '.join(tmp))))
p.s - Remove repr() if not required
Output
Enter a number - 3
'1\n'
'1 2\n'
'1 2 3'
Instead of printing a line piece by piece, or building a string by repetitively adding to it, the usual and efficient way in Python is to put all the values you want to print in a list, then to use join to join them.
Also, you don't need two imbricated loops: just append the latest number to your existing list on each loop, like this:
rows = int(input())
values = []
for i in range(1, rows + 1):
values.append(str(i))
print(' '.join(values))
Output:
3
1
1 2
1 2 3

Printing a X using * in Python

I have to write a python program which allows a user to input an odd integer, n, greater than or equal to three. The program outputs an x with n rows and n columns. *My professor said using nested for loops would be ideal for this. The X is printed using *'s *
I have been experimenting over the past couple days and have had little success.
This is my starting code for the program and after that it's just blank, like my mind. If you could provide some explanation as to how the code works that would be amazing.
num=int(input("Please type in an odd integer."))
if num%2==0:
print("Your number is incorrect")
This should do it:
Python 2
N = 5
for i in range(N):
for j in range(N):
if (i == j) or ((N - j -1) == i):
print '*',
else:
print ' ',
print ''
Python 3
N = 5
for i in range(N):
for j in range(N):
if (i == j) or ((N - j -1) == i):
print('*', end = '')
else:
print(' ', end = '')
print('')
(thanks to Blckknght for Python 3 knowledge)
You're looping through all the rows in the outer loop, then all the columns or cells in the inner. The if clause checks whether you're on a diagonal. The comma after the print statement ensures you don't get a new line every print. The 3rd print gives you a new line once you're finished with that row.
If this is helpful / works for you; try making a Y using the same approach and post your code in the comments below. That way you could develop your understanding a bit more.
I'll give you a hint :
n = int(input("Please type in an odd integer."))
for i in range(n):
print('x', end='')
print()
This prints a x, n times on the same line and then go back to next line.
I'll let you figure out how you print this same line n times.
Using single for loop:
for i in range(num):
a = [' '] * num
a[i] = '*'
a[num-i-1] = '*'
print(''.join(a))
Using nested for loops:
for i in range(num):
s = ''
for j in range(num):
if j in [i, num-i-1]:
s += '*'
else:
s += ' '
print(s)

Print statements in a for loop

I am working on a function which takes a positive integer N and computes the following sum:
1 - 2 + 3 - 4 + 5 - 6 + .... N.
My professor said we can not use "math formulas" on this, so how could I go about it?
I thought about using a for loop, but I don't know how or what to write for the print statement. This is what I have so far:
n=int(input("enter N="))
for i in range(1, n+1, 1):
if i % 2 == 0:
# I'm not sure what print statement to write here
I tried print(i= "+" i+1) and just weird stuff like that, but I get errors and am lost after that.
what i have now
n=int(input('enter N='))
total=0
print("sum",)
for i in range(1, n+1, 1):
if i % 2 == 0:
count=count - i
print("-", i)
else:
count=count + i
print("+", i, end=" ")
print("=", total)
#still get errors saying name count not defined and unsupported sperand for +:
First, to accumulate the sum as described, and to do it by looping instead of "using math formulas", you want to do this:
n=int(input("enter N="))
total = 0
for i in range(1, n+1, 1):
if i % 2 == 0:
????
else:
????
print(total)
You should be able to figure out what the ???? are: you need to do something to total for each i, and it's different for even and odd.
Now, if you want it to print out something like this:
sum 1 - 2 + 3 - 4 + 5 - 6 + .... N = X
You can print things out along the way like this:
n=int(input("enter N="))
total = 0
print ("sum", end=" ")
for i in range(1, n+1, 1):
if i % 2 == 0:
print("-", i, end=" ")
????
else:
if i == 1:
print(i, end=" ")
else:
print("+", i, end=" ")
????
print("=", total)
If you want to keep negative and positive totals separately and then add them, as you mentioned in an edit, change total = 0 to ntotal, ptotal = 0, 0, then change each of the ???? parts so one works on one total, one on the other.
All of the above is for Python 3. If you want to run it in Python 2, you need to turn those print function calls into print statements. For the simple cases where we use the default newline ending, that's just a matter of removing the parentheses. But when we're using the end=" ", Python 2's print statement doesn't take keyword parameters like that, so you instead have to use the "magic comma", which means to end the printout with a space instead of a newline. So, for example, instead of this:
print("+", i, end=" ")
You'd do this:
print "+", i,
Again, for Python 3, you don't have to worry about that. (Also, there are ways to make the exact same code run in both Python 2 and 3—e.g., use sys.stdout.write—which you may want to read up on if you're using both languages frequently.)
You're most of the way there already. I'm not sure why you think you need to put a print statement inside the loop, though. You only want one result, right? You already have if i % 2 == 0 - which is the case where it's even - and you want to either add or subtract based on whether the current i is odd or even. So keep a running tally, add or subtract in each loop iteration as appropriate, and print the tally at the end.
You see the difference between what happens with odd and even numbers, which is good.
So, as you cycle through the list, if the number is even, you do one operation, or else you do another operation.
After you've computed your result, then you print it.
There are a lot of explanations in the answers already here. So I will try to address the different ways in which you can compute this sum:
Method 1:
def mySum(N):
answer = 0
for i in range(1, N+1):
if i%2:
answer += i
else:
answer -= i
return answer
Method 2:
def mySum(N):
answer = 0
for i in range(1, N+1, 2):
answer += i
for i in range(2, N+1, 2):
answer -= i
return answer
Method 3:
def mySum(N):
pos = range(1, N+1, 2)
neg = range(2, N+1, 2)
return sum(pos) - sum(neg)
Method 4:
def mySum(N):
return sum([a-b for a,b in zip(range(1, N+1, 2), zip(2, N+1, 2))])
Method 5:
def mySum(N):
return sum([i*-1 if not i%2 else i for i in range(1,N+1)])
Method 6:
def mySum(N):
return sum(map(lambda n: n*[-1, 1][i%2], range(1, N+1)))
Again, these are only to help prime you into python. Others have provided good explanations, which this is not meant to be
count = 0
print "0"
for i in range(1, n+1, 1):
if i % 2 == 0:
count = count - i
print "-" , i
else:
count = count + i
print "+" , i
print "=", count

Categories