Printing a X using * in Python - 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)

Related

I'm trying to use a while loop instead of a for loop. How would I change this code so that it works using a while loop in python?

# Generating Hollow Pyramid Pattern Using Stars
row = int(input('Enter number of rows required: '))
for i in range(row):
for j in range(row-i):
print(' ', end='') # printing space required and staying in same line
for j in range(2*i+1):
if j==0 or j==2*i or i==row-1:
print('*',end='')
else:
print(' ', end='')
print() # printing new line
I've tried swapping the (for) for (while <= .... etc) and add in i = 1 and i += 1 at the end but none seem to work.
Based on the code above, are you sure that you are adding the integer increment within the while loop?
for example,
i = 1
while i <= 10:
do_something
i+=1
will stop after 10 cycles, but
i = 1
while i <= 10:
do_something
i+=1
will go on forever

I have question about python for loop if statement and multiple for loop

So if I get input number "n" and what I want to do is print 1~n like this. If n = 10
1
23
456
78910
and my code is this
x = int(input())
n=1
for i in range(1, x+1):
sum = (n+1)*n // 2
print(i , end = ' ')
if(sum == i):
print()
n+=1
I solved this question with my TA but is there a way to solve using multiple for statements other than this one? I don't want to use sum = (n+1)*n // 2 this part because my TA actually made this part without explanation.
I guess this is what you were thinking about:
x = int(input())
n = 1
for i in range(1, x+1):
for j in range(1, i):
if n <= x:
print(n, end=' ')
n += 1
print()
if n >= x:
break
If you're worried about needlessly looping too often on j for very large x, you could change:
if n <= x:
print(n, end=' ')
else:
break
of course you can do the summation using another for loop
sum = 0
for j in range(1,n+1):
sum += j
you cold also do sum = sum(range(n+1)), but (n + 1) * n // 2 is the best way of getting the summation of n

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)

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

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

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