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()
Related
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:
*****
* *
* *
* *
* *
*****
I am trying to draw a box with symbols on the terminal. The shape is created by a class object. I want to know how I could print my object dynamically.
class Box:
def __init__(self, width, height):
self.width = width
self.height = height
def draw_box(self):
print('+ ' * self.width)
for s in range(self.height-2):
print('+ ', ' ' * (self.width-1), ' +')
print('+ ' * self.width)
# Create and Run code
box = Box(5,4)
box.draw_box()
But you can see below that the "width" coding of the box is broken. It was a little difficult to test because every time I changed the width and height arguments of my object, I would have to "fix" it to print correctly by either adding or subtracting a hard-coded number from or to self.width. The text are the width and height argument I tested for.
+ + + + + + + + + + +
+ + (11,7)
+ +
+ +
+ +
+ +
+ + + + + + + + + + +
>>> #Bad output
+ + + + + (5,5)
+ +
+ +
+ +
+ + + + +
>>> #Good output
class Box:
def __init__(self, width, height):
self.width = width
self.height = height
def draw_box(self):
print('+ ' * self.width)
for s in range(self.height-2):
print('+ ' + ' ' * (2*(self.width-2)) + '+')
print('+ ' * self.width)
# Create and Run code
box = Box(10,4)
box.draw_box()
Since you need a space after printing each '+' symbol. You should consider double the width. If you have 5 +'s to print then you will be using 10char spaces to print them. So, double the width should be included in the line print('+ ' + ' ' * (2*(self.width-2)) + '+')
There are three issues with your code, all in the line print('+ ', ' ' * (self.width-1), ' +'):
If you pass two arguments to print(), they are printed separated by a space. Thus, you now have an offset of two spaces in this line.
Your second argument passed to print is a single space. However, your box is defined by + , which has a width of two. Therefore this space should be adjusted to a double space.
The last argument is + instead of + , which also gives an offset.
Based on this, I would change draw_box() to:
def draw_box(self):
print('+ ' * self.width)
spacing = ' ' * (self.width-2)
for s in range(self.height-2):
print(f'+ {spacing}+ ')
print('+ ' * self.width)
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()
import math
# The standard gravitational parameter for the sun
mu = 1.327 * math.pow(10, 20)
class Planet:
def __init__(self, name, radius, moons, orbital_radius):
self.name = name
self.radius = radius
self.moons = moons
self.orbital_radius = orbital_radius
def collide(self):
self.moons = self.moons + 1
return self.moons
def volume(Planet):
v = (4 / 3) * math.pi * math.pow(Planet.radius, 3)
return str(v)
def surface(Planet):
area = 4 * math.pi * math.pow(Planet.radius, 2)
return str(area)
def physical(Planet):
if Planet.moons == 1:
Planet.moons = str(Planet.moons) + " moon"
else:
Planet.moons = str(Planet.moons) + " moons"
return (Planet.name + " has a volume of " + volume(Planet) + " cubic km, a surface area of " + surface(Planet) + " sq. km, and " + Planet.moons)
def dynamic(Planet):
period = 2 * math.pi * Planet.orbital_radius * math.sqrt(Planet.orbital_radius / mu)
return (Planet.name + " has a year of approximately " + str(period // (60 * 60 * 24)) + " days")
Earth = Planet('Earth', 6371, 1, 1.496 * math.pow(10, 11))
Jupiter = Planet('Jupiter', 69911, 79, 7.786 * math.pow(10, 11))
print(physical(Earth))
print(physical(Jupiter))
print(dynamic(Earth))
print(dynamic(Jupiter))
print(Earth.collide())
I understand that self.moons is turned into a string due to the physical function but how would I go about in turning into an integer again. It doesn't seem possible as an integer and string is stored as its value that's why I'm getting the error message ValueError: invalid literal for int() with base 10: '1 moon' when I attempt to print(Earth.collide())
Just partition the string on a space and take the first part:
int(self.moon.partition(" ")[0])
You can also use str.split() but partition is a little faster for the 'only need to split once' case.
The better approach is to not set the .moons attribute to a string. Keep it an integer, there is no need to replace it just to format a nice string with information:
def physical(Planet):
if Planet.moons == 1:
moons = str(Planet.moons) + " moon"
else:
moons = str(Planet.moons) + " moons"
return (Planet.name + " has a volume of " + volume(Planet) + " cubic km, a surface area of " + surface(Planet) + " sq. km, and " + moons)
You may want to look at formatted string literals or the format string syntax:
def physical(Planet):
moons = f"{Planet.moons} moon"
if Planet.moons != 1:
moons += 's'
return (
f"{Planet.name} has a volume of {volume(Planet)} cubic km, a surface "
f"area of {surface(Planet)} sq. km, and {moons}"
)
Either way, by using a local variable moons to contain the formatted number of moons value, you don't alter the Planet.moons value so don't have to worry about how to go back to it being an integer again.
I would recommend, to stick with a local/private variable in def physical(Planet), because it is not used anywhere else and just a format to a value.
def physical(Planet):
if Planet.moons == 1:
_planet_moons = str(Planet.moons) + " moon"
else:
_planet_moons = str(Planet.moons) + " moons"
return (Planet.name + " has a volume of " + volume(Planet) + " cubic km, a surface area of " + surface(Planet) + " sq. km, and " + _planet_moons)
This prevents you from convering the value forth and back.
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.