alternating fill color in a line of squares - colors

I'm trying to make a line of squares that alternate between two colors, but it only runs the first color. We've been going over building our own functions and using the modulo operator, so that's how I'm trying to alternate the colors. I'm not sure what's going wrong.
Here's the code I've been trying. I guess I missed something but I don't know what I'm not understanding about why the color won't change. I have tried moving the if/else but that didn't change anything and I'm pretty sure it should be inside the first for loop.
def square_line(num_squares, color1, color2):
for square in range(num_squares):
if num_squares % 2 == 1:
t.fillcolor(color1)
else:
t.fillcolor(color2)
t.begin_fill()
for sides in range(4):
t.forward(25)
t.right(90)
t.end_fill()
t.penup()
t.forward(25)
t.pendown()
square_line(6, 'blue', 'green')

In this bit of your code:
if num_squares % 2 == 1:
you are telling your program to fill with color1 if num_squares is odd, otherwise fill with color2, and as num_squares doesn't change, this only fills one color.
I'd recommend doing something like:
for square in range(num_squares):
if square % 2 == 1: # not: num_squares % 2 == 1
t.fillcolor(color1)
else:
t.fillcolor(color2)
...
As the value of square alternates between odd and even each iteration, this will change the fill color each iteration.

Related

Skipping a value in a range within a for loop

So the course I'm in posted an exercise:
# Modify the code inside this loop to stop when i is exactly divisible by 11
for i in range(0, 100, 7):
print(i)
I added:
if i % 11 == 0:
break
However my code gets stuck on the first value as it is 0 thus ending the program.
What function would I use to skip over the first value and proceed with the rest of the range?
Any help would be greatly appreciated!
To "skip over" a certain value (here 0), you can use python's continue
for i in range(0, 100, 7):
print(i)
if i == 0:
continue
if i % 11 == 0:
break
This is like a break statement, but it returns you to the top of the loop instead of skipping to the end of it.
You could also do as below:
print(0)
for i in range(1, 100, 7):
print(i)
if i % 11 == 0:
break
Print the first value and start the loop from index 1.

Codingame 'A child's play' process times out

I'm trying to solve the coding challenge A child's play on Codingame using python.
With my program I can pass the first two test cases but when the test requires a lot of loops my program goes in timeout. What could I improve?
To fully understand the problem the details of the challenge are needed but I don't want to copy and paste them here because I'm not sure it's allowed.
I try to explain the problem with my words. Given this input:
12 6
987
...#........
...........#
............
............
..#O........
..........#.
O is the character starting point.
# are the walls you can not step on
. is where the character can step
In this example w=12 (width of the matrix) and h=6 (height of the matrix).
n = 987 is the number of steps the character has to take.
Required Output:
In this case 7 1 the position of the character after the number of moves given
Rules:
The character starts always by moving upwards
When a wall is encountered the character turns clockwise and keeps moving
The walls are placed so that the caracter can not get stuck and can not exit the matrix.
When I run the program with that test case I get the right result.
With the following test case instead:
14 10
123456789
..#...........
....#..#......
.#O.....#.....
..............
..............
.......##...#.
............#.
.#........###.
.#.#..........
..............
I get:
Failure
Process has timed out. This may mean that your solution is not optimized enough to handle some cases.
This is the code I managed to write:
import math
import sys
def find_initial_position(maze, w, h):
for i in range(0, h):
for j in range(0,w):
if maze[i][j] == "O":
return [i, j]
return -1
def can_move(maze, direction, x, y):
if direction == "U":
if maze[ x -1 ][ y ] == "#":
return False
elif direction == "R":
if maze[ x ][ y + 1 ] == "#":
return False
elif direction == "D":
if maze[ x +1 ][ y ] == "#":
return False
elif direction == "L":
if maze[ x ][ y-1 ] == "#":
return False
return True
def turn_clockwise(direction):
directions = ["U", "R", "D", "L"]
return directions[ (directions.index(direction) + 1) % 4 ]
def move(direction, coordinates):
if direction == "U":
coordinates[0] -=1
elif direction == "R":
coordinates[1] +=1
elif direction == "D":
coordinates[0] +=1
elif direction == "L":
coordinates[1] -=1
def main():
w, h = [int(i) for i in input().split()]
n = int(input())
maze = []
direction = "U"
position = [0, 0]
for i in range(h):
line = input()
maze.append(line)
position = find_initial_position(maze, w, h)
for i in range(0, n):
while not can_move(maze, direction, position[0], position[1]):
direction = turn_clockwise(direction)
move(direction, position)
print( "%(x)d %(y)d" %{"x": position[1], "y": position[0]} )
main()
I streamlined your code a little bit and made it somewhat more readable, by:
making use of matrix multiplication with numpy to do the 90° clockwise turns;
using the built-in str.index() to find the initial position.
Result below...
But really, this is missing the point.
If you look at the "mazes" in all the test cases, what's happening is that the "robot" is bouncing cyclically between four # obstacles in a rectangular pattern (could also be a more complex pattern). So with your approach, you're computing and re-computing the same short sequence of moves, millions and billions of times; even though the longest possible cycle cannot possibly have more moves than the number of squares in your small maze (order of magnitude).
What you should try to do is keep a continuous log of all the moves done so far (position, direction). And if – or rather, when – you end up in a (position, direction) where you've already been before, then you've covered one full cycle. No need to compute any more moves. Say your cyclic sequence is of length L and the total number of moves prescribed is n, then the final position will be sequence element number L mod n (or something like that, off-by-one errors notwithstanding).
import sys
import numpy as np
def is_obstacle(maze, position):
return maze[position[0]][position[1]] == '#'
def main():
w, h = [int(i) for i in input().split()]
n = int(input())
# Load maze
maze = []
for i in range(h):
line = input()
maze.append(line)
if 'O' in line:
# Found initial position
position = np.array([i, line.index('O')])
# Initial direction
direction = np.array([-1,0])
# Define actions
turn_clockwise = np.array([[0,-1],[1,0]])
# Walk maze
for i in range(n):
while is_obstacle(maze, position + direction):
direction = direction # turn_clockwise
position = position + direction
print( "%(x)d %(y)d" %{"x": position[1], "y": position[0]} )
main()

this code is getting skipped, does anyone know why?

I am trying to make a program that will randomly generate a number, then when you guess a number, it either says, 'you won' if you guess correctly, 'higher' if your guess was too low or 'lower' if your guess was too high. Everything is defined just so you know.
I have tried changing the if statements around, and altered the grater than and less than symbols. I have also tryed elif statements for the second two if's.
for i in range(50):
word = input('what number do you think it is?')
number = randint(0,100000)
if word > 'number':
print('the generated number is lower than your guess')
drawrectanage1()
penup()
goto(-180, 0)
color(colours['bakery'])
style = ('Roboto', 60, 'bold')
write('Lower', font=style, align='left')
hideturtle()
if word < 'number':
print('the generated number is higher than your guess')
drawrectanage1()
penup()
goto(-180, 0)
color(colours['bakery'])
style = ('Roboto', 60, 'bold')
write('Higher', font=style, align='left')
hideturtle()
if word == 'number':
drawrectanage1()
penup()
goto(-180, 0)
color(colours['bakery'])
style = ('Roboto', 60, 'bold')
write('you won!', font=style, align='left')
hideturtle()
#there are no error messages and I have tested it and realised that the code...
if word > 'number':
print('the generated number is lower than your guess')
drawrectanage1()
penup()
goto(-180, 0)
color(colours['bakery'])
style = ('Roboto', 60, 'bold')
write('Lower', font=style, align='left')
hideturtle()
... just isn't running and I am not sure what to do.
Now because you have number wrapper in a string your conditional, ie if is not checking for the numerical value of number but instead is using string comparison.
In all of the occurrences of conditionals where you are comparing the value of number (which has been evaluated from rand), just unwrap it from string, like
if word < number

scipy.stats converter normal z scores to p value Python3

struggling a bit with this little converter, I couldn't get it to take me past the first input, which is repeatedly asked for. Is there a more elegant way to get around the ValueError problem that gets me out of the loop?
EDIT: I also played around with the position of the a=1 and a=0's and when I do that, it stops asking me for input but it just runs the script without asking me for the second user input.
Thanks folks!
import scipy.stats as st
a=1
while a==1:
try:
choice = input('Press 1 for percentages to Z-Score, 2 for Z-score into percentages, one tailed')
if choice ==1:
percentage = input('Enter value')
print(st.norm.ppf(percentage))
a=0
if choice ==2:
score = input('Enter value')
print(st.norm.cdf(score))
a=0
except ValueError:
print('Invalid Entry')
a=1
After thinking about how the code is wrong, I forgot to check for the basics:
Convert your inputs before processing!!!
I just converted both inputs into floats and now it works like a charm, including asking for new input in case it's an invalid entry.
import scipy.stats as st
a=1
while a==1:
try:
float(choice = input('Press 1 for percentages to Z-Score, 2 for Z-score into percentages, one tailed'))
if choice ==1:
percentage = float(input('Enter value'))
print(st.norm.ppf(percentage))
a=0
if choice ==2:
score = float(input('Enter value'))
print(st.norm.cdf(score))
a=0
except ValueError:
print('Invalid Entry')
a=1

Using parameters throughout multiple subroutines python

I am currently trying to write a program where the user inputs what colour carpet they would like and then depending on what carpet and what area they have inputted it will give them a different price, However my current issue is using the parameters correctly since I am very new to both using python and to programming. The current program specification requires the use of subroutines. An example problem is with my last line main(exit1) where it says that exit1 isn't defined and if I try to edit the code to main() it says that exit1 is required. Any help will be greatly appreciated.
def prices():
PriceA = 40
PriceB = 50
PriceC = 60
def main(exit1):
exit1 = False
while exit1 == False:
carpet = str(input("What carpet would you like blue, red or yellow "))
carpet = carpet.upper()
if carpet == "X":
exit1 = True
else:
width = int(input("What is the width of the room in M^2 "))
height = int(input("What is the height of the room in M^2 "))
area = width * height
if carpet == "BLUE":
a(area)
elif carpet == "RED":
b(area)
elif carpet == "YELLOW":
c(area)
else:
print("Invalid carpet")
cost = 0
output(cost)
def output(cost, exit1):
print ("the price is £", cost)
def a(area, PriceA):
cost = PriceA * area
output(cost)
def b(area, PriceB):
cost = PriceB * area
output(cost)
def c(area, PriceC):
cost = PriceC * area
output(cost)
main(exit1)
You are trying to pass in a variable as an argument to the main function on the last line of your program, but you have not defined the exit1 variable before that line is executed (you define it within the scope of the main function). To achieve what you want to do you don't need to provide main with the exit1 argument, so you can just remove it from the function definition and the function call.
def main():
...
...
main()
The problem you are having is that a variable needs to be defined before it can be entered into a function. I fixed the code and made a few corrections it also appeared that you had an indentation error and didn't feed in enough arguments into your functions when you called them. The code ive written is a bit easier to follwo. If I have done anything you dont understand send me a message, otherwise I recommend sites such as code acadamy and pythonprogramming .net.
def main():
PriceA = 40
PriceB = 50
PriceC = 60
while True:
carpet = str(input('What carpet would you like blue, red or yellow? '))
carpet = carpet.upper()
if carpet == 'X':
break
else:
width = int(input("What is the width of the room in M? "))
height = int(input("What is the height of the room in M? "))
area = width * height
if carpet == "BLUE":
output(area,PriceA)
elif carpet == "RED":
output(area,PriceB)
elif carpet == "YELLOW":
output(area,PriceC)
else:
print('Invalid carpet')
def output(area,Price):
cost = area*Price
print('the price is £',cost)
main()

Resources