A function that prints an xo square - python

I have a school proejct. I'm having a bit of trouble. I was thinking of implementing a 2D lists in python and then using a while loop to update the variables and index the lists to reassign the index to an x. The details are
Go to main.py write a function called xo that accepts an integer size as a parameter and prints a square of size by size characters,
where all characters are "o" except that an “x” pattern of "x" characters has been drawn from the corners of the square.
On the first line, the first and last characters are "x";
on the second line, the second and second-from-last characters are "x"; and so on.
For example, the call of xo(5) should produce the following outputs:
xooox
oxoxo
ooxoo
oxoxo
xooox
my code so far was
def xo(num):
square=[]
section=["o"*num]
for i in range(1,num+1):
square.append(section)
for row in square:
print("".join(row))
xo(5)
and it prints
ooooo
ooooo
ooooo
ooooo
ooooo
vertically

It helps to look at this type of exercise as a math problem before trying to turn it into code. We can start with code that prints every square as an "o" (as you've already done), but it'll be easier to take it to the next step if each time we print an "o" we have a particular coordinate on the grid (x and y) to work with:
def xo(n):
for y in range(n):
for x in range(n):
print("o", end="")
print()
xo(5)
This gets us the output:
ooooo
ooooo
ooooo
ooooo
ooooo
We know we want some of those os to be xs, so let's look at what the x and y values in our code will look like when we want that to happen:
y x
0: 0, 4
1: 1, 3
2: 2, 2
3: 1, 3
4: 0, 4
This is the math problem -- how do we come up with a mathematical way to express that relationship between x and y?
We can see that in every case we want to change what we print when x == y, or x == 4 - y. Remembering that in this case n == 5, we might change our code to do:
def xo(n):
for y in range(n):
for x in range(n):
print("x" if x in (y, n - 1 - y) else "o", end="")
print()
which for xo(5) gets us:
xooox
oxoxo
ooxoo
oxoxo
xooox
and since we wrote our code in terms of n instead of hardcoding 4 in there as a magic number, we can also run, say, xo(20) and get:
xoooooooooooooooooox
oxooooooooooooooooxo
ooxooooooooooooooxoo
oooxooooooooooooxooo
ooooxooooooooooxoooo
oooooxooooooooxooooo
ooooooxooooooxoooooo
oooooooxooooxooooooo
ooooooooxooxoooooooo
oooooooooxxooooooooo
oooooooooxxooooooooo
ooooooooxooxoooooooo
oooooooxooooxooooooo
ooooooxooooooxoooooo
oooooxooooooooxooooo
ooooxooooooooooxoooo
oooxooooooooooooxooo
ooxooooooooooooooxoo
oxooooooooooooooooxo
xoooooooooooooooooox

Related

Most constraining variable and least constraining value for N-Queens - Python

I was trying to solve the N-Queens(Only 1 solution) problem and I succeeded but my program could only calculate up to N = 47 in a good amount of time so I tried to implement least constraining value and most constraining variable and even though it got faster, it was still slow. What can I do to be able to calculate up to N = 1000?
def solve(n, x, board, mid_rows, sd_squares):
# If we are on the last row, it means we have put all the queens:
if x >= n:
print_board(board)
sys.exit(0)
for i in sd_squares:
# If we can put a queen on the current square, do it
if isOk(board, mid_rows[x], i, n):
board[mid_rows[x]][i] = 1
# Do the same thing for the next row
solve(n, x + 1, board, mid_rows, sd_squares)
# If we are here, it means we put the queen in the wrong square so we have to remove that queen
board[mid_rows[x]][i] = 0
I can't post the whole code because it's too long but please note that isOk(board, x, y, n) is a function that tells if we put a queen on the x row and y column it threatens other queens or not.
mid_rows is an array that includes the most middle rows to the side rows so like let's say n = 5, then it's [2,3,1,4,0] or when n = 6 it's [3,2,4,1,5,0].
sd_squares is a list that contains the side squares to middle squares. Like when n = 5 it's [0,4,1,3,2] or when n = 6 it's [0,5,1,4,2,3].

Creating Lights On Game

I'm working on writing code for a game called Lights On where the idea of the game is to produce a board of randomly lit squares and to win all squares must be lit (1 is on 0 is off). Clicking on a square inverts that square and any squares neighboring it above, below, left, or right. However, I am having trouble inverting the board correctly using my code bellow
import time # provides time.sleep(0.5)
from csplot import choice
from random import * # provides choice( [0,1] ), etc.
import sys # larger recursive stack
sys.setrecursionlimit(100000) # 100,000 deep
def runGenerations2d(L , x = 0,y=0):
show(L)
print( L ) # display the list, L
time.sleep(.1) # pause a bit
newL = evolve2d( L ) # evolve L into newL
print(newL)
if min(L) == 1:
#I like read outs to be explained so I added an extra print command.
if x<=1: # Takes into account the possibility of a 1 click completition.
print ('BaseCase Reached!... it took %i click to complete' % (x))
print (x)
done()#removes the need to input done() into the shell
else:
print ('BaseCase Reached!... it took %i clicks to complete' % (x))
print (x)
done()#removes the need to input done() into the shell
return
x = x+1 # add 1 to x before every recusion
runGenerations2d( newL , x,y ) # recurse
def evolve2d( L ):
N = len(L)
x,y = sqinput2()
return [[ setNewElement2d( L, i, j,x,y ) for i in range(N)]for j in range(N) ]
def setNewElement2d( L, i, j, x=0, y=0 ):
if y==j and (i == x-1 or i == x+1 or i ==x):
return 1-L[i][j]
elif x==i and (j == y-1 or j == y+1):
return 1-L[i][j]
else:
return L[i][j]
I believe the issue is with my setNewElement2d function, but I cannot seem to figure it out.
Short answer: You've swapped i and j in evolve2d().
Long answer: When evolve2d() creates the new matrix, i needs to be in the outer loop, not the inner loop. Else, swap i and j. For example, if I change the call to
return [[ setNewElement( L, j, i, x, y ) for i in range(N) ] for j in range(N) ]
then I get the correct answer for your example.
This has to do with the organization of a two-dimensional array. In Python, L[i][j] looks in the ith row (vertical count down) and the jth column (horizontal count right). But you want i to compare to the x value, which in your mind is horizontal. So the point you're testing against has its coordinates swapped from the points you think you're testing against.
Last edit, I swear: Basically, the program did exactly what it was supposed to do. But when you looked at it, you imagined x and y to have the traditional meanings (horizontal and vertical, respectively) when in the array they have the opposite meanings: L[x][y] looks down x rows and right y columns.

For loop in CS Circles section 7C coding exercise: One Triangle

Here is an example of a for loop inside another for loop.
Example
This code prints a 5×5 square of ones.
Note: when we multiply a number X by ten and add one, we're essentially putting an extra 1 digit at the end of X. For example, (1867*10)+1=18671.
for i in range(0, 5):
X = 0
for j in range(0, 5):
X = (X*10)+1
print(X)
Modify the previous program in two ways. First, instead of a square, make it draw a triangle shaped like this: ◤. Second, instead of always having 5 lines, it should take the desired size as input from input(). For example, if the input is 3, then the output should be
111
11
1
So far the code that I have got is:
X=input()
for i in range(0, 3):
X = 0
for j in range(0, 3):
X = (X*10)+1
print(X)
However this code outputs:
1
11
111
When the expected output should be:
111
11
1
I can't seem to figure out how to change my code that I have so far to get the expected output?
This can solve the problem for you:
def test(X,_range):
x = X
for j in range(0, _range):
print int(str((x*10) +1) + ("1"*(_range-1-j)))
test(0,3)
>>>
111
11
1
>>>
In every loop step the number starts with (X*10)+1
In the next step X has changed and you add the digit 1 to the right side
If want to reverse it, you need to use ("1"*(_range-1-j))
The for iterator changes the X content every step. (he don't use i and j, "For" only for step derivation )
Here's the solution:
n=int(input())
for i in range(0, n):
X = 0
for j in range(0, n-i):
X = (X*10)+1
print(X)
As you said, 10*X + 1 means putting extra 1 at the end of X. You need an inverse operation: how to remove the last digit of a number. Hint: integer division. Google "python integer division" to get to pages such as Python integer division yields float.
So, then all you've to do is construct 111...11 of the right length, and then iteratively print and remove digits one by one.
This block is very confusing, here's what happens:
X=input()
Get value of X from input.
for i in range(0, 3):
X = 0
Now set the value of X to 0 three times (overwriting your input)
for j in range(0, 3):
X = (X*10)+1
print(X)
Now X is being set to 1, then 11 and then 111.
Even if you meant to nest the for loops, this wont behave right. Instead, you want to get the i value to loop backwards, using the slice operator [::-1]. You should then make j's range be zero to i.
You'll also need to compensate by increasing the value of both numbers in i's range (otherwise the last line will be a zero) but this will work:
for i in range(1, 6)[::-1]:
X = 0
for j in range(0, i):
X = (X*10)+1
print(X)
Note that I moved the print out of the j loop, as that wasn't how the original code was (and generated the wrong output), pay attention to whitespace. Using 4 spaces is preferable to just 2 for reasons like this.
If you are doing CS Circles than these other answers probably contain code you still haven't come in contact with, at least I haven't, so I'll try to explain it with the knowledge I've gathered so far (couple weeks doing CS Circles).
You are ignoring the first loop and it is where your answer lies. Notice that if you put the print command outside of the loop body it would just output:
111
That it because your second loop is not in the body of the first, so python just loops the first one 3x and than moves to the second loop. Instead it should be:
for i in range(0, 3):
X = 0
for j in range (0, 3):
X = (X*10)+1
print(X)
Now the program outputs:
111
111
111
But you want one less digit each time print is called again. This is achieved by subtracting the value of "i" (since it neatly goes from 0 to 2) from second loop's range tail value. So now you have :
for i in range(0, 3):
X = 0
for j in range(0, 3-i):
X = (X*10)+1)
print(X)
Finally the output is:
111
11
1
Protip: use the visualizer in CS Circles, it helps you better understand the way code is executed in python, and can provide insight to your problems. Best of luck!
The easiest way is to use the following code;
p = int(input())
for i in range(0,p):
x = 0
for j in range(i,p):
x = (x*10)+1
print(x)

Triangle side sum program with input from user (Think Python exercise 5-4-2)

I'm trying to solve Think Python's exercise 5-4-2, which asks to write a program that will prompt the user to input the size of three sticks in order to calculate if they can make up a triangle. The rule is that if any of the three length of the sticks is greater than the sum of the other two, the triangle cannot be made.
Here is my code. The problem is that it always return 'no triangle' (I tried with correct values such as 4, 5 and 3, and with values that should return wrong such as 1,2, and 12), and it always indicates "None" (as if I wasn't using "return"):
def is_triangle(x,y,z):
if (x>y+z) or (y>z+x) or (z>x+y):
print 'no triangle'
else:
print 'triangle yes'
return
prompt1 = 'Input firt stick length for your triangle please...'
x = raw_input(prompt1)
int(x)
prompt2 = 'Input second stick length for your triangle please...'
y = raw_input(prompt2)
int(y)
prompt3 = 'Input third stick length for your triangle please...'
z = raw_input(prompt3)
int(z)
print is_triangle(x,y,z)
Thanks in advance for your help!... Norpa
The issue here is that you're not reassigning your int casts back to x, y and z. Thus, they are treated as strings, and in your last comparison, you end up with (x + y) = 34 (as a string), and the comparison becomes True.
So all the prompt sections should be like this:
prompt1 = 'Input firt stick length for your triangle please...'
x = raw_input(prompt1)
x = int(x)
Or:
prompt1 = 'Input firt stick length for your triangle please...'
x = int(raw_input(prompt1))
You are not casting x y and z to integers properly, thus comparing the input strings with >.
Change
int(x)
to
x = int(x)
and do the same for y and z.
The issue here is that you forgot to assign the return value of int(x) to the variable x, thus int(x) has no meaningful effect.
While structuring the function you can set it out to be the integer.
def is_triangle(a,b,c):
if (int(a)>int(b+c)) or (int(b)>int(c+a)) or (int(c)>int(a+b)):
print("No")
else:
print("Yes")
This is considering the scope limited to your exercise. You can take it to little advanced level by making it dynamic to restrict the user input to be only the integer(in the prompt). Hope you can do that once you move to advance user. Good Luck!

Python - Prime Number exercise

Note, this is not my homework assignment! I'm just trying to understand Python (and math, sadly) at the same time. I know the ultimate goal of this program is to get a list of prime numbers in the range 1 to 20, however, once it gets to the "for x in range..." line, I'm getting lost and the tutorial doesn't explain it in detail.
Could you please explain in plain English step by step and clarify specifically
a) what is x in the line for x in range (2,n)
b) in the line for x in range (2,n), what is n? Is it the same "n" at the bottom?
c) what is this n, x, n // x saying exactly. Please clarify the //
thanks if you can help
def isprime(n):
if n == 1:
print("1 is special")
return False
for x in range(2, n):
if n % x == 0:
print("{} equals {} x {}".format(n, x, n // x))
return False
else:
print(n, "is a prime number")
return True
for n in range(1, 20):
isprime(n)
a)
for x in range (2,n)
is the same like
for (x = 2; x < n; x++)
in some other language: a loop where x gets integer values between 2 and n-1 included.
b)
for x in range (2,n):
this n comes from the first def isprime(n) and is whatever this function is later called with. In this case it is always the same n from the bottom.
c)
print("{} equals {} x {}".format(n, x, n // x))
this writes the following text: A equals B x C where A is n, B is x and C is n/x rounded to the nearest smaller integer. It is so called integer division (e.g. 9 // 2 = 4)
a) Try this at the prompt:
help(range)
It will tell you that range(a,b) returns a list atarting as a, ending at b-1, so
range(2,10)
is
[2, 3, 4, 5, 6, 7, 8, 9]
Play at the prompt, type range(2,2), range(2,-1), range(2,3) and see what comes out. You'll see that n==1 isn't the only special case.
Now, something like for x in y iterates over the elements of y, which in your case would be a list. You can also verify this at the prompt:
for x in range(2,10) :
print x
b) the block starting with def isprime(n) is a function, with argument n. You can call it for any n: isprime(100). At the bottom of the code, you are iterating over range(1,20) (if in doubt type it into the prompt) and calling isprime for each value, i.e. 1,2,3,4,...,19.
Note that in this example, there isn't a need to create and return a list with range, you can use xrange, which is a generator. Type help(xrange) in the prompt...
a) x takes on the values from 2 to n-1 (since range excludes the upper bound)
b) No, it's the same n as in the method definition (i.e. the method argument)
c) Integer division

Categories

Resources