Write a function create_box that takes three inputs: height
(rows), width (columns), and a character char and creates a
height * width box using the character char.
This is my code:
def create_box(height, width, char):
for i in range (height):
for j in range(width):
z = char * j + "\n"
return z
The problem with this code is it returns only one line of output. I want to know how is it possible to return the complete box? Can we place the return statement in such a way that it returns after completing all the iterations of first for loop?
I also tried this:
def create_box(height, width, char):
z = ""
for i in range (height):
for j in range(width):
z += char * width + "\n"
return z
ma = create_box(3, 5, "!")
print(ma)
The output is:
!!!!!
!!!!!
!!!!!
!!!!!
!!!!!
You've almost done it correctly with your second approach: This is the working code.
def create_box(height, width, char):
z = ""
for i in range (height):
for j in range(width):
z += char # Width number of chars
z += '\n' # Next row
return z
ma = create_box(3, 5, "!")
print(ma)
All you did was mess up the indentation of your return statement, and add to the string wrongly. If you don't get the logic here, post a comment and I'll explain it fully.
Outputs:
>>> print(create_box(1, 1, '-'))
-
>>> print(create_box(3, 2, '* '))
* *
* *
* *
# Etc etc
In response to your comment:
The reason your first code didn't work was that the approach was wrong, take a look at this:
z = 0
for i in range(5):
z += i
print(z)
# You expected this to output 5, it doesn't
The second attempt was wrong on two counts:
Your return statement was wrongly indented, making it so that the function stopped executing after it completed the first iteration of the outer loop. See below:
def hello():
print("This gets printed")
return
print("This is never executed")
hello()
# Run it and see for yourself!
The z variable: You had z randomly going up, all the second for loop needed to do was add one char to z every iteration.
Anything else you need clarification on?
Related
Here is the function i defined:
def count_longest(field, data):
l = len(field)
count = 0
final = 0
n = len(data)
for i in range(n):
count = 0
if data[i:i + l] is field:
while data[i - l: i] == data[i:i + l]:
count = count + 1
i = i + 1
else:
print("OK")
if final == 0 or count >= final:
final = count
return final
a = input("Enter the field - ")
b = input("Enter the data - ")
print(count_longest(a, b))
It works in some cases and gives incorrect output in most cases. I checked by printing the strings being compared, and even after matching the requirement, the loop results in "OK" which is to be printed when the condition is not true! I don't get it! Taking the simplest example, if i enter 'as', when prompted for field, and 'asdf', when prompted for data, i should get count = 1, as the longest iteration of the substring 'as' is once in the string 'asdf'. But i still get final as 0 at the end of the program. I added the else statement just to check the if the condition was being satisfied, but the program printed 'OK', therefore informing that the if condition has not been satisfied. While in the beginning itself, data[0 : 0 + 2] is equal to 'as', 2 being length of the "field".
There are a few things I notice when looking at your code.
First, use == rather than is to test for equality. The is operator checks if the left and right are referring to the very same object, whereas you want to properly compare them.
The following code shows that even numerical results that are equal might not be one and the same Python object:
print(2 ** 31 is 2 ** 30 + 2 ** 30) # <- False
print(2 ** 31 == 2 ** 30 + 2 ** 30) # <- True
(note: the first expression could either be False or True—depending on your Python interpreter).
Second, the while-loop looks rather suspicious. If you know you have found your sequence "as" at position i, you are repeating the while-loop as long as it is the same as in position i-1—which is probably something else, though. So, a better way to do the while-loop might be like so:
while data[i: i + l] == field:
count = count + 1
i = i + l # <- increase by l (length of field) !
Finally, something that might be surprising: changing the variable i inside the while-loop has no effect on the for-loop. That is, in the following example, the output will still be 0, 1, 2, 3, ..., 9, although it looks like it should skip every other element.
for i in range(10):
print(i)
i += 1
It does not effect the outcome of the function, but when debugging you might observe that the function seems to go backward after having found a run and go through parts of it again, resulting in additional "OK"s printed out.
UPDATE: Here is the complete function according to my remarks above:
def count_longest(field, data):
l = len(field)
count = 0
final = 0
n = len(data)
for i in range(n):
count = 0
while data[i: i + l] == field:
count = count + 1
i = i + l
if count >= final:
final = count
return final
Note that I made two additional simplifications. With my changes, you end up with an if and while that share the same condition, i.e:
if data[i:i+1] == field:
while data[i:i+1] == field:
...
In that case, the if is superfluous since it is already included in the condition of while.
Secondly, the condition if final == 0 or count >= final: can be simplified to just if count >= final:.
Your answers have helped me a lot before, but now I'm stuck on a problem that I can't find the answer to. I'm currently at the start of teaching myself Python, and I've come across an exercise I can't figure out. I need to print each of the characters of a string on a new line in reverse order, with the number of spaces before each character being equal to the character's position in the string. Ideally, this would use a for loop.
I can print each character on a new line and in reverse order fine, but my issue is that when I reverse the string, it reverses the position of each of the characters: e.g. in the string 'dog', 'd' is in position 1, but reversed, is in position 3. I'd like to print the number of spaces multiplied by the original position of the string, rather than after it has been reversed.
This is what I have so far (apologies for any dodgy code).
def print_reverse(text):
x = 0
spc = ' '
for i in text[::-1]:
print(spc * x, i)
x += 1
print_reverse('dog')
Expected results:
g
o
d
Actual results:
g
o
d
The issue is initially x is 0. Instead you can try decreasing x from length of text:
def print_reverse(text):
x = len(text)
spc = ' '
for i in text[::-1]:
print(spc * x, i)
x -= 1
print_reverse('dog')
def print_reverse(text):
x = len(text)
spc = ' '
for i in text[::-1]:
print(spc * x, i)
x -= 1
This works
def print_reverse(text):
x = len(text)
spc = ' '
for i in text[::-1]:
print(spc * x, i)
x -= 1
In the iteration, you iterate like 0,1,2,3,.... You want decreasing spaces (...3,2,1,0), therefore try for example:
def print_reverse(text):
x = 0
spc = ' '
for i in text[::-1]:
print((len(text) - x)*spc,
print(i)
x += 1
Here you take the length of the string and substract your loop index. Same idea as the other stated solution by the user student, but slightly different implementation :)
You can accomplish this in a couple lines with a little bit of generator comprehension and enumerate:
def print_reverse(text):
for line in (' ' * (len(word)-i) + c for i, c in enumerate(text[::-1])):
print(line)
enumerate returns each list item, as well as it's position in a list (or in this case a string).
So enumerate('dog') will return:
((0, 'd'), (1, 'o'), (2, 'g'))
If you subtract the position from the total length of the word (len(word)-i), you'll get the number of spaces you need in front of your leter.
This answer also uses a generator expression, which is easy way to apply the same expression for each item in a list.
Finally, text[::-1] gives you a reversed list (you could also do reversed(text).
I want to print an empty pyramid in python 3 and my teacher suggested me this code but i am confused about the list(array) and i want an alternative of this code. Is there any alternative method to print an empty pyramid. This code is also available on available on stackoverflow but i want to solve it by using simple if else.
#Function Definition
def Empty_triangle(n): # Here value of n is 5
for i in list(range(n-1))+[0]:
line = ""
leadingSpaces = n-2-i
line += " "*leadingSpaces
line += "*"
if i != 0:
middleSpaces = 2*i-1
line += " "*middleSpaces
line += "*"
print(line)
# Function Call
n = 5
Empty_triangle(n)
Example of code which i want
if (row==0 and row==5 and col!=0):
output should like this using ifelse
Can it be done with simple if else
In the code your teacher suggested, the "list" seems redundant. When n=5, the "range(n-1)" command already gives you the numeric list [0, 1, 2, 3, 4]. Since it's already a list, you don't need to put "list()" around it. Then the "+[0]" just adds 0 to the end to give you [0, 1, 2, 3, 4, 0]. Also, I'm not sure if you want that extra star at the bottom center.
There are lots of alternative ways to do it, but here's an alternative version I made:
def triangle2(n):
for row in range(n):
line = [ ' ' for i in range(n+row+1)]
line[n-row] = '*'
line[n+row] = '*'
print ''.join(line)
triangle2(5)
For each row, it creates a list of spaces that's just big enough for that row, then it replaces the spaces with the locations of where the stars should be. Finally it joins all of the spaces and stars into a string, and prints it.
An even shorter way is to essentially take half of each row, then mirror it to make the second half:
def triangle3(n):
for row in range(n):
line = [ ' ' for i in range(n-row) ] + ['*'] + [ ' ' for i in range(row)]
print(''.join(line[:-1] + line[::-1]))
Or skipping lists and joins and just using concatenated strings:
def triangle4(n):
for row in range(n):
first_half = ' '*(n-row) + '*' + ' '*row
second_half = first_half[::-1][1:]
print(first_half + second_half)
The "[::-1]" part is a little trick to reverse a string or list.
# Python 3.x code to demonstrate star pattern
# Function to demonstrate printing pattern triangle
def triangle(n):
# number of spaces
k = 2*n - 2
# outer loop to handle number of rows
for i in range(0, n):
# inner loop to handle number spaces
# values changing acc. to requirement
for j in range(0, k):
print(end=" ")
# decrementing k after each loop
k = k - 1
# inner loop to handle number of columns
# values changing acc. to outer loop
for j in range(0, i+1):
# printing stars
print("* ", end="")
# ending line after each row
print("\r")
# Driver Code
n = 5
triangle(n)
careful with indent.
previously whole code wasn't displayed.
I am working on a basic shapes program in Python and can't seem to work out my code. I need to keep it simple using while loops and the variables given, nested loops are usable.
Here is my code for a square:
def drawSquare(size, drawingChar):
print('Square: ')
row = 1
while row <= size:
# Output a single row
drawRow(size, drawingChar)
# Output a newline to end the row
print()
# The next row number
row = row + 1
print()
It is supposed to print like:
x
x
x
x
based on a size and character entered by the user.
drawRow is another function similar to drawSquare:
def drawRow(size, drawingChar):
col = 1
while col <= size:
print(drawingChar, end=' ')
col = col + 1
It would make more sense with a for loop:
def drawSquare(size, drawingChar):
for i in range(size):
print(" "*i + drawingChar)
Example:
drawSquare(4, "p")
Output:
p
p
p
p
Please show your work for drawDiagonal (or anything) when asking a question.
Diagonal is probably the easier case here:
def drawDiagonal(size, drawingChar):
for y in range(size):
s = ' '* y + drawingChar
print(s)
drawDiagonal(4,"X")
X
X
X
X
(Maybe pick a fixed font)
The solution I came up with is:
def drawDiagonal(size, drawingChar):
print('Diagonal: ')
row = 1
while row <= size:
# Output a single row
drawRow(row - 1, ' ')
print(drawingChar)
# Output a newline to end the row
print()
# The next row number
row = row + 1
print()
Note: drawRow is defined separately (above, in question)
& drawDiagonal was called separately as well:
drawDiagonal(userSize, userChar)
where
userSize = input('Size: ')
userChar = input('Character: ')
Having some difficulty with this problem. The program should get a number from the user. It will be the amount of triangles. The first triangle should have two rows. Each new triangle will have one extra row than the last triangle.
This is what I have:
numTri = input('Please umber of triangles: ')
numTri = eval(numTri)
numRow = 2
x = 0
while j<numTri:
y = '*'
z = 0
while z<numRow:
print y
y = y + *
z += 1
x += 1
numRow += 1
Getting an invalid syntax error on the print line. Not sure if I'm doing anything else wrong. Anyone have any idea?
Assuming you are using Python 3, there is a lot of errors in your code. Let us see them:
Major problems
The j variable
You use a j variable, in the loop condition, which is not set neither used anywhere. This will result in an error:
while j<numTri:
I believe you want to use the x variable:
while x<numTri:
print() is a function
In Python 3, you should put the parameters of a print() function between parenthesis, which is not the case:
print y
Too easy to solve:
print(y)
Note that the parenthesis are optional in Python 2.
'*' char without quotes:
You try to append the '*' char to the string from y but does not enclose the char with quotes:
y = y + *
The interpreter will see this asterisk as the multiplication operator, which will yield an error. Just enclose it with quotes (single or double, it does not matter):
y = y + '*'
Indentation problem
A specially pernicious problem in your code is that, after the second while loop, your code does not return to the same indentation level of the loop. I replaced the spaces below with open boxes so we can count them:
␣␣␣while z<numRow:
␣␣␣␣␣␣␣␣␣print y
␣␣␣␣␣␣␣␣␣y = y + *
␣␣␣␣␣␣␣␣␣z += 1
␣␣␣␣x += 1
␣␣␣␣numRow += 1
Alas, there is one more space in the two last lines when compared with the while line. You should remove those spurious spaces.
A resulting code will be:
numTri = input('Please umber of triangles: ')
numTri = eval(numTri)
numRow = 2
x = 0
while x<numTri:
y = '*'
z = 0
while z<numRow:
print(y)
y = y + '*'
z += 1
x += 1
numRow += 1
Minor problems
There are also some other details in your code which would be considered bad practices. Those will not matter a lot to you yet, since you are really novice, but we can explore some of them.
Avoiding eval()
eval() is a powerful yet risky function, so we avoid using it. It is specially easy to do in your case, since int() will convert the read string to an integer without problems:
numTri = input('Please umber of triangles: ')
numTri = int(numTri)
Non-standard indentation
Sometimes, you indent what is inside your loops with four spaces:
␣␣␣y = '*'
␣␣␣z = 0
␣␣␣while z<numRow:
then with six spaces
␣␣␣␣␣␣print(y)
␣␣␣␣␣␣y = y + '*'
␣␣␣␣␣␣z += 1
and even with four spaces, which results in an error:
␣␣␣␣x += 1
␣␣␣␣numRow += 1
The best thing to do is to always use the same indentation size. PEP 8 (a set of recommendations for all Python programmers) recommends to use four spaces for each indentation:
␣␣␣␣y = '*'
␣␣␣␣z = 0
␣␣␣␣while z<numRow:
␣␣␣␣print(y)
␣␣␣␣y = y + '*'
␣␣␣␣z += 1
␣␣␣␣x += 1
␣␣␣␣numRow += 1
while instead of for
This one is hard stuff for novices, but it may be helpful to point nonetheless. Your code would be much better if you used for loops with the range() function:
for x in range(0, numTri+1):
y = '*'
for z in range(0, numRow+1):
print(y)
y = y + '*'
numRow += 1
However, as you are a student, I believe you will learn about this feature some time in the future, so take it easy :)
The resulting code:
numTri = input('Please umber of triangles: ')
numTri = int(numTri)
numRow = 2
for x in range(0, numTri+1):
y = '*'
for z in range(0, numRow+1):
print(y)
y = y + '*'
numRow += 1
j is never defined before you reach the while loop. Maybe you meant while x < numTri: instead?
Also, the
x = 0
while x < numTri:
# do something
x += 1
construct is not very Pythonic; try
for x in range(numTri):
# do something
instead.
But I think the syntax error (and thus answering your question) is because you are using Python 3 where print needs round brackets. So :
print ( y )
And if you just want the highest grade for your programming task:
print('\n'.join('*'*y for x in range(int(input('Please umber of triangles: '))) for y in range(1,x+3)))
numTri = int(raw_input('Please umber of triangles: '))
or on python 3.x
numTri = int(input('Please umber of triangles: '))