This code prints out a hollow rectangle with a given width and height using stars(*), but instead of printing each segment at a time I need to modify it or create a code that will create a single string that when printed produces the same output as the code above.
def print_rectangle(width, height):
for p in range(1):
print("*" * width)
for i in range(height - 2):
for i in range((width + 1) - width):
print("*", end='')
for n in range(width - 2):
print(" ", end='')
for j in range((width + 1) - width):
print("*", end='')
print("")
print("*" * width)
You need to create a variable, that saves the substrings, than print out the whole string, like this:
def print_rectangle(width, height):
tmp_str = ""
for p in range(1):
tmp_str = "*"*width+'\n'
for i in range(height-2):
for i in range((width+1)-width):
tmp_str += "*"
for n in range(width-2):
tmp_str += " "
for j in range((width+1)-width):
tmp_str += "*"
tmp_str += '\n'
tmp_str += "*"*width+'\n'
print(tmp_str)
print_rectangle(4, 5) #or any other numbers
The question has already been answered of how to correct your own code to make the rectangle, so here is a totally different way to accomplish the same thing:
def rectangle(width: int, height: int) -> str:
top_bottom = "*" * width
middle = "\n*" + (" " * (width - 2)) + "*"
rect = top_bottom
for _ in range(height - 2):
rect += middle
if height > 1:
rect += "\n" + top_bottom
return rect
print(rectangle(10, 5))
Output:
**********
* *
* *
* *
**********
You could build the lines into a list then join them for a single print operation. Here's an example:
width = 5
height = 6
t = ['*' * width + '\n']
m = '*' + ' ' * (width-2) + '*\n'
t.extend(m * (height - 2))
print(''.join(t+[t[0]]), end='')
Output:
*****
* *
* *
* *
* *
*****
Related
I was wondering if anyone could help me create a star pattern of letters. I want to see to have either UP or DOWN on the same line. At the moment, however, the letters are printed underneath each other rather than next on the same line. Any help would be greatly appreciated thank you.
Sample the U function:
def u():
u_str = ''
for row in range (0,7):
for column in range (0,7):
if (((column == 1 or column==5) and row !=6) or ((column==2 or column ==3
or column==4) and row==6)) :
u_str += "*"
else:
u_str += " "
u_str += "\n"
return u_str
function for entering either up or down
def up_or_down():
if len(user_letters) ==4 and user_letters == "DOWN":
print(d()+o()+w()+n())
elif len(user_letters) ==2 and user_letters == "UP":
print(u()+p())
else:
pass
up_or_down()
First, I suggest that you use a dict to store letters ascii art, so you are not recomputing them multiple times:
ascii_letters = {
"D": d(),
"N": n(),
"O": o(),
"P": p(),
"U": u(),
"W": w(),
}
Then create a function that can horizontally concatenate multilines strings:
def hcat_strings(*strings):
"""`strings` must have the same number of lines"""
# in a single line
# return "\n".join((" ".join(l) for l in zip(*(s.splitlines() for s in strings))))
strings_lines = (s.splitlines() for s in strings)
lines_as_tuples = zip(*strings_lines)
lines = (" ".join(l) for l in lines_as_tuples)
return "\n".join(lines)
Which you can finally use as follows:
from operator import itemgetter
text = "UPPUPU"
letters = itemgetter(*text)(ascii_letters)
print(hcat_strings(*letters))
Result:
* * ***** ***** * * ***** * *
* * * * * * * * * * * *
* * * * * * * * * * * *
* * ***** ***** * * ***** * *
* * * * * * * * *
* * * * * * * * *
*** * * *** * ***
The idea is to create a triangle, surrounded in *'s while the $ signs, spaces and height of the triangle are all user inputs.
For example, with height = 9, $=5 and spaces = 2, this should produce the following output:
*
*$*
*$$$*
*$ $$*
*$$$ $$*
*$$$ $$$$*
*$ $$$$$ $*
*$$$$ $$$$$ *
*****************
I tried a couple of different approaches, like stringing the $'s and spaces together and printing by their index, or counting how many times each was printed and not overlapping.
However, I couldn't manage to find anything that worked :(
Any help is appreciated :) just a first semester at CS
My code:
height = int(input('Enter height: '))
numSigns = int(input('Enter number of $: '))
numSpaces = int(input('Enter number of spaces: '))
signCounter = 0
spaceCounter = 0
sign = '$'
row = (sign*numSigns + ' '* numSpaces)*height
count1 = 0
count2 = 0
x =1
for i in range(height):
for j in range(height - i - 1):
print(" ", end = '')
print('*',end = '')
if i == 0:
print()
p = x
x = x + i - 1
for a in range(p,x):
print(row[a], end = '')
if i != 0:
print('*')
Actual output:
Enter height: 9
Enter number of $: 5
Enter number of spaces: 2
*
**
*$*
*$$*
*$$ *
* $$$*
*$$ $*
*$$$$ *
*$$$$$ *
Let's see over what logic it works. You will find logic at last.
1st.
How to create left-side star pattern like this :
*
*
*
*
First thing is how many spaces on the left of each star is equal to TOTAL_HEIGHT_OF_PATTERN - CURRENT_HEIGHT_STATUS. for given example let's take 2nd-line so:
TOTAL_HEIGHT_OF_PATTERN = 4
CURRENT_HEIGHT_STATUS = 2
NUMBER_OF_SPACE_ON_LEFT = TOTAL_HEIGHT_OF_PATTERN - CURRENT_HEIGHT_STATUS = 2
2nd.
How to create `$` and `space` pattern like this in between:
*
*$*
*$$$*
* $$$*
*$$$$$ *
*$$$$$ $$*
*$$$$$ $ $*
*$$$ $$$$$$*
How many spaces at given height, for above system it is found.
spaces:0 for height # 1, 2, 3
spaces:1 for height # 4, 5, 6
spaces:2 for height # 7, 8
we can see a pattern found such that at every height (CURRENT_HEIGHT_STATUS-1)//3 no of space will found.
For NO_OF_DOLLORS we can see it equal to 2*(CURRENT_HEIGHT_STATUS-NO_OF_SPACES)-3 finally by using shuffling operation we can shuffle dollor and spaces
Check out this code:
from random import shuffle
height = int(input('Height : '))
doller = int(input('Dollor : '))
spaces = int(input('Spaces : '))
for i in range(1,height+1):
no_spaces = (i-1)//3
str_ = ['$' for i in range(2*(i-no_spaces)-3)]+[' ']*no_spaces
shuffle(str_)
if i == 1:
print(' '*(height-i) + '*')
elif i != height and i != 1:
print(' '*(height-i) + '*' + ''.join(str_) + '*')
else:
print('*'*(2*height-1))
OUTPUT :
Height : 9
Dollor : 2
Spaces : 5
*
*$*
*$$$*
*$$ $*
*$$ $$$*
*$$$$$$ $*
* $$$$$$$*
*$$ $$$$$$$ *
*****************
Instead of completely using loop let's divide them in procedural code. Logic is similar to my previous solution. For making particular enclose-string we can use make_str function who logic revolves around the remaining number of $
height = int(input('Height : '))
doller = int(input('Dollor : '))
spaces = int(input('Spaces : '))
def make_str(rem, len_str):
x = 0
s = ''
for _ in range(len_str):
if rem >0:
s += '$'
rem -= 1
else:
s += ' '
x += 1
if x == spaces:
x = 0
rem = 5
return (rem, s)
rem_dollor = doller
for i in range(1,height+1):
num = 2*(i)-3
rem_dollor, str_ = make_str(rem_dollor, num)
if i == 1:
print(' '*(height-i) + '*')
elif i != height and i != 1:
print(' '*(height-i) + '*' + str_ + '*')
else:
print('*'*(2*height-1))
**OUTPUT: **
Height : 9
Dollor : 4
Spaces : 3
*
*$*
*$$$*
* $$*
*$$$ $*
*$$$$ $$*
*$$$ $$$$$*
* $$$$$ $$*
*****************
Whilst attempting CS50's PSET6, I was trying to create a double-half pyramid of a size specified by the user.
The pyramid is fine but there's a random new line after the user input and before the pyramid starts. How can I fix it? Any help is appreciated :D
The code is as follows
def main():
hashHeight = height()
create(hashHeight)
# get height
def height():
h = int(input("Height: "))
if h >= 1 and h <= 8:
return h
else:
height()
#print hash
def create(x):
for i in range(x + 1):
print(" " * (x - i) + "#" * i + " " + "#" * i)
main()
def main():
hashHeight = height()
create(hashHeight)
# get height
def height():
h = int(input("Height: "))
if h >= 1 and h <= 8:
return h
else:
height()
#print hash
def create(x):
for i in range(1, x + 1):
print(" " * (x - i) + "#" * i + " " + "#" * i)
main()
I hava an assignment where I have to write a function that will print a rectangle (user can change it's height and width) frame by frame with a square of "x"'es inside of it (I tried my best to describe it, but I hope the image will help).
In my code I represent frame as a list of rows (filled with "o"s). I already have a function that finds the rectangle's center and replaces the middle "o" with "x"- that's my first frame.
Originally I wanted to make all remaining frames with nested loops but it got confusing fairly quickly since there are 2 horizontal lines of "x"es.
I'm pretty sure I need a new "coordinate system" to iterate over frames. Can someone please point me to the right direction?
def squareAnimation():
while True:
frameHeight = int(input("Please enter frame's height: \nRemember: Odd numbers only!\n"))
frameWidth = int(input("Please enter frame's width:\nRemember: Odd numbers only!\n"))
if (frameHeight % 2 != 0 and frameWidth % 2 != 0):
break
numberOfFrames = min(int(frameWidth/2), int(frameHeight/2))
lineTemplate = "o " * frameWidth
#frame filled with "o" only
blankFrame = [lineTemplate] * frameHeight
#frame with x in center
frameTemplate = blankFrame
findListCenter(frameTemplate, frameHeight, frameWidth)
printListWithoutBrackets(frameTemplate)
def findListCenter(frame, height, width):
frame[int(height / 2)] = "o " * (int(width / 2)) + "x " + "o " * (int(width / 2))
def printListWithoutBrackets(frame):
for object in range(0, len(frame)):
tempLine = frame[object]
print("".join(tempLine))
squareAnimation()
So eventually I came up with my own solution. It might not be the prettiest one, but it works.
import copy
import time
def squareAnimation():
while True:
height = int(input("Please enter frame's height: \nRemember: Odd numbers only!\n"))
width = int(input("Please enter frame's width:\nRemember: Odd numbers only!\n"))
if (height % 2 != 0 and width % 2 != 0):
break
numberOfFrames = min(int(width/2), int(height/2))
middleRow = int(height / 2)
middleColumn = int(width / 2)
numberOfHorizontalXes = 3
lineTemplate = "o " * width
blankFrame = [lineTemplate] * height
currentFrameIndex = 1
completeListOfFrames = ([blankFrame] * (numberOfFrames + 1)) #an array filled with blankGrames
firstFrame = copy.deepcopy(blankFrame)
firstFrame [int(height / 2)] = "o " * (int(width / 2)) + "x " + "o " * (int(width / 2))
completeListOfFrames[0] = firstFrame
for frame in completeListOfFrames:
if frame == firstFrame:
continue
numberOfO = int((width - numberOfHorizontalXes) / 2)
loopFrameCopy = copy.deepcopy(frame)
loopFrameCopy[middleRow + currentFrameIndex] = "o " * numberOfO + "x " * numberOfHorizontalXes + "o " * numberOfO
loopFrameCopy[middleRow - currentFrameIndex] = "o " * numberOfO + "x " * numberOfHorizontalXes + "o " * numberOfO
loopFrameCopy[middleRow] = "o " * numberOfO + "x " + "o " * (width - (2 * numberOfO + 2)) + "x " + "o " * numberOfO
for wallIndex in range(1, currentFrameIndex):
loopFrameCopy[middleRow + wallIndex] = "o " * numberOfO + "x " + "o " * (width - (2 * numberOfO + 2)) + "x " + "o " * numberOfO
loopFrameCopy[middleRow - wallIndex] = "o " * numberOfO + "x " + "o " * (width - (2 * numberOfO + 2)) + "x " + "o " * numberOfO
completeListOfFrames[currentFrameIndex] = loopFrameCopy
numberOfO += 3
numberOfHorizontalXes += 2
currentFrameIndex += 1
revCompleteListOfFrames = copy.deepcopy(completeListOfFrames[::-1])
revCompleteListOfFrames.pop(0)
finalList = completeListOfFrames + revCompleteListOfFrames
printListWithoutBrackets(finalList)
def printListWithoutBrackets(frameOfFrames):
for frame in frameOfFrames:
for line in frame:
print("".join(line))
time.sleep(0.3)
print("\n")
squareAnimation()
I just wrote up a simple neural network in python as I have been studying them recently. I am using backpropogation. The activation function is a sigmoid. The inputs and weights generate randomly and the ideal output is 0. I am new to python so the code is written very inefficiently, but it is readable. When I run the code, the output is always zero and I can't seem to find why. Also, I didn't use a module.
from random import uniform
input_one_input_value = 1
input_two_input_value = 0
bias_value = 1
#use global to globalize function-based variables
#use lists to store data in future
def hidden_One():
global weighted_sum_hidden_one
weighted_sum_hidden_one = (input_one_input_value * weights[0]) + (input_two_input_value * weights[1]) + (bias_value * weights[2])
hidden_one_output = activation(weighted_sum_hidden_one)
return hidden_one_output
def hidden_Two():
global weighted_sum_hidden_two
weighted_sum_hidden_two = (input_one_input_value * weights[3]) + (input_two_input_value * weights[4]) + (bias_value * weights[5])
hidden_two_output = activation(weighted_sum_hidden_two)
return hidden_two_output
def output_One():
weighted_sum = (hidden_One() * weights[6]) + (hidden_Two() * weights[7]) + (bias_value * weights[8])
return activation(weighted_sum)
def activation(x):
sigmoid_value = 1 / (1+(2.71828 ** x))
return sigmoid_value
def calculate_gradient():
E = ideal_output - actual_output
output_delta = -E * activation(weights[6] + weights[7] + weights[8])
h1_delta = activation(weighted_sum_hidden_one) * weights[6] * output_delta
h2_delta = activation(weighted_sum_hidden_two) * weights[7] * output_delta
b2_delta = activation(bias_value) * weights[8] * output_delta
i1_delta = activation(input_one_input_value) * ((weights[0] * h1_delta) + (weights[3] * h2_delta))
i2_delta = activation(input_one_input_value) * ((weights[1] * h1_delta) + (weights[4] * h2_delta))
b1_delta = activation(bias_value) * ((weights[2] * h1_delta) + (weights[5] * h2_delta))
global w1_gradient
global w2_gradient
global w3_gradient
global w4_gradient
global w5_gradient
global w6_gradient
global w7_gradient
global w8_gradient
global w9_gradient
w1_gradient = input_one_input_value * h1_delta
w2_gradient = input_two_input_value * h1_delta
w3_gradient = bias_value * h1_delta
w4_gradient = input_one_input_value * h2_delta
w5_gradient = input_two_input_value * h2_delta
w6_gradient = bias_value * h2_delta
w7_gradient = hidden_One() * output_delta
w8_gradient = hidden_Two() * output_delta
w9_gradient = bias_value * output_delta
def backpropogation():
E = .7 #learning rate
a = .3 #momentum to prevent settling for local minima
global weightchanges_previous
global weight_change
weightchanges_previous = []
weight_change = []
if len(weightchanges_previous) == 0:
weight_change.append((E * w1_gradient))
weight_change.append((E * w2_gradient))
weight_change.append((E * w3_gradient))
weight_change.append((E * w4_gradient))
weight_change.append((E * w5_gradient))
weight_change.append((E * w6_gradient))
weight_change.append((E * w7_gradient))
weight_change.append((E * w8_gradient))
weight_change.append((E * w9_gradient))
weightchanges_previous.append(weight_change[0])
weightchanges_previous.append(weight_change[1])
weightchanges_previous.append(weight_change[2])
weightchanges_previous.append(weight_change[3])
weightchanges_previous.append(weight_change[4])
weightchanges_previous.append(weight_change[5])
weightchanges_previous.append(weight_change[6])
weightchanges_previous.append(weight_change[7])
weightchanges_previous.append(weight_change[8])
elif len(weightchanges_previous) != 0:
weight_change[0] = (E * w1_gradient) + (a * weightchanges_previous[0])
weight_change[1] = (E * w2_gradient) + (a * weightchanges_previous[1])
weight_change[2] = (E * w3_gradient) + (a * weightchanges_previous[2])
weight_change[3] = (E * w4_gradient) + (a * weightchanges_previous[3])
weight_change[4] = (E * w5_gradient) + (a * weightchanges_previous[4])
weight_change[5] = (E * w6_gradient) + (a * weightchanges_previous[5])
weight_change[6] = (E * w7_gradient) + (a * weightchanges_previous[6])
weight_change[7] = (E * w8_gradient) + (a * weightchanges_previous[7])
weight_change[8] = (E * w9_gradient) + (a * weightchanges_previous[8])
while len(weightchanges_previous) > 0 : weightchanges_previous.pop()
weightchanges_previous.append((E * w1_gradient) + (a * weightchanges_previous[0]))
weightchanges_previous.append((E * w2_gradient) + (a * weightchanges_previous[1]))
weightchanges_previous.append((E * w3_gradient) + (a * weightchanges_previous[2]))
weightchanges_previous.append((E * w4_gradient) + (a * weightchanges_previous[3]))
weightchanges_previous.append((E * w5_gradient) + (a * weightchanges_previous[4]))
weightchanges_previous.append((E * w6_gradient) + (a * weightchanges_previous[5]))
weightchanges_previous.append((E * w7_gradient) + (a * weightchanges_previous[6]))
weightchanges_previous.append((E * w8_gradient) + (a * weightchanges_previous[7]))
weightchanges_previous.append((E * w9_gradient) + (a * weightchanges_previous[8]))
def edit_weights():
weights[0] += weight_change[0]
weights[1] += weight_change[1]
weights[2] += weight_change[2]
weights[3] += weight_change[3]
weights[4] += weight_change[4]
weights[5] += weight_change[5]
weights[6] += weight_change[6]
weights[7] += weight_change[7]
weights[8] += weight_change[8]
while len(weight_change) > 0 : weight_change.pop()
weights = []
x = 0
while x <=8:
weights.append(uniform(-10, 10))
x += 1
ideal_output = 0
actual_output = output_One()
print "Output %d" % output_One()
x = 0
while x <= 10:
output_One()
calculate_gradient()
backpropogation()
edit_weights()
print "Output %d" % output_One()
print "----------------------"
actual_output = output_One()
x += 1
print "FINAL WEIGHTS:"
print weights[0]
print weights[1]
print weights[2]
print weights[3]
print weights[4]
print weights[5]
print weights[6]
print weights[7]
print weights[8]
Your problem is the output line:
print "Output %d" % output_One()
You're using %d which prints integer values so it rounds float values down to the nearest integer (integer conversion). Use %f instead and you should get the floating point numbers correctly.