path finder for multidimensional array - python

I am trying to make a dungeon based game and was in the process of making a theoretical path finder, but whenever I run the program, it just prints the same coordinates(theoretical) that I entered in the 1st place. I'm a bit "new" to programming in general so I got stuck
import winsound
def main():
snd = winsound.Beep
a = input("Enter the x value for the entrance: ")
b = input("Enter the y value for the entrance: ")
entrance = [a, b]
x = input("Enter the x value for the exit: ")
y = input("Enter the y value for the exit: ")
a = float(a)
b = float(b)
x = float(x)
y = float(y)
exut = [x, y] #deliberatly placed exit misspelling as exit is a command
done = False
while done == False:
if b > a:
b = b - 1
elif b < a:
b = b + 1
else:
if a > x:
a = a - 1
elif a < x:
a = a + 1
else:
done = True
done2 = False
while done2 == False:
if b > y:
b = b - 1
elif b < y:
b = b + 1
else:
snd(494, 250)
snd(659, 400)
print("done!")
print(entrance)
print(exut)
entrance = [a, b]
exut = [a, b]
done2 = True
when I run it and put lets say 1 for x value of entrance, 2 for y value of entrance, 3 for x value of exut and 4 for y value of exut I get this result;
>>> main()
Enter the x value for the entrance: 1
Enter the y value for the entrance: 2
Enter the x value for the exit: 3
Enter the y value for the exit: 4
done!
['1', '2']
[3.0, 4.0]
>>>
I don't know why it does that so please can you help, it would be much appreciated, thanks.

Firstly, you don't need to convert to float since you only move in steps of one, so get rid of this code:
a = float(a)
b = float(b)
x = float(x)
y = float(y)
It's inconsistent because you are assigning a and b to entrance before converting to float, but assigning x and y to exut after converting. However you should add code to make sure that only integer values can be entered for entrance and exut.
In your first loop, you are comparing b to a, when it should be compared to y (because y is the target value of b):
while done == False:
if b > y: # changed a to y here
b = b - 1
elif b < y: # changed a to y here too
b = b + 1
else:
if a > x:
a = a - 1
elif a < x:
a = a + 1
else:
done = True
Also, you don't need the second loop because after the first loop finishes, a and b will already be set to x and y. So you can just print out your values.
You are printing out entrance and exut, but you aren't printing out the final values of a and b:
print("done!")
print(entrance)
print(exut)
print(a, b) # print out a and b. they should be equal to exut
If you want to see the progress of your pathfinder you can add print(a, b) to your pathfinding loop:
while done == False:
print(a, b)
if b > y: # changed a to y here
b = b - 1
elif b < y: # changed a to y here too
b = b + 1
else:
if a > x:
a = a - 1
elif a < x:
a = a + 1
else:
done = True

Related

Factorization: What went wrong with d? [duplicate]

This question already has answers here:
What is a debugger and how can it help me diagnose problems?
(2 answers)
Closed 2 years ago.
Consider:
Enter image description here
Input: 20
17
999997
Output: 2^2 * 5
17
757 * 1321
My code:
a = int(input())
# Find the factors first
for i in range(2, a+1):
s = 0
b = a
d = 0
# See if it is a prime number
if a%i == 0:
for x in range(1, i+1):
if a%x == 0:
d = d + x
if (d-1)/i == 1:
d = 0
print(i)
else:
s = 0
b = a
d = 0
continue
d = 0
# I will see how many prime numbers
while(b>0):
if (b/i)%1 == 0:
s = s + 1
b = b/i
else:
b = 0
if b == 1:
b = 0
print(s)
I will find the factors first, and then see if it is a prime number. If so, I will see how many prime numbers it is
if i input 12, it outputs 2 2
Enter link description here
I believe you need the output of the following.
import math
a = int(input())
while (a % 2 == 0):
print(2)
a = int(a/2)
while (a % 3 == 0):
print(3)
a = int(a/3)
for i in range(5, math.ceil(math.sqrt(a)), 6):
while (a % i == 0):
print(i)
a = int(a / i)
while (a % (i + 2) == 0):
print(i + 2)
a = int(a / (i + 2))
if (a > 3):
print(a)
This will give you the prime factors for a given number. As I can understand, it is what you are looking for.
a = int(input("Enter a number:"))
for i in range(2, a + 1):
if a % i != 0:
continue
# SETTING THE DEFAULT VALUES AT THE BEGINNING OF EVERY ITERATION OF THE LOOP
s = 0
b = a
d = 0
for x in range(1, i + 1):
if b % x == 0:
d = d + x
if (d - 1) / i == 1:
d = 0
print(i)
else:
# s = 0 # NO LONGER NEEDED, AS WE RESET THEM AT THE BEGINNING OF THE LOOP
# b = a
# d = 0
continue
while b > 0:
if (b / i) % 1 == 0:
s = s + 1
b = b / i
else:
b = 0
if b == 1:
b = 0
print(s)
a /= i**s # THIS LINE IS IMPORTANT
You were close. You forgot to set the default values at the beginning of every iteration of the loop, so they sometimes didn't have the right values ; and you should set a to a different value by dividing it by the factor you found (i**s, so i to the power of s).
As has been mentioned, your code also follows an odd coding style. I suggest you stop putting newlines between each statement, and start separating operators with spaces (example: range(3+5) is bad, range(3 + 5) is more readable)
You are using too many loops here and that's why you are getting too much confused. Here is the code which serve the same purpose (if I understand your problem correctly)
a = int(input("Enter a number: "))
i = 2
factors = []
while i <= a:
if (a%i) == 0:
factors.append(i)
a = a/i
else:
i = i + 1
print(factors)
here I am returning a list, if you want you can change the type accordingly.
Here are the inputs/outputs:
Enter a number: 17
[17]
Enter a number: 100
[2, 2, 5, 5]
Enter a number: 12
[2, 2, 3]

How can you sum these outputs in Python?

I made this code about a number and it's power. It will ask a number and it's power and show the output like a horizontal list.. Like
Number = 2
Power = 3.... then output will be like=
1
2
4
Number and power can be +/-.
But I want to sum those numbers like Sum = 7 after it shows
1
2
4
I have no idea how to do it after the output. I am new to programming maybe that's why can't figure out this problem.
Here is the code in Python :
A =float(input("Number:"))
B =float(input("Power:"))
print("Result of Powers:")
i = 0
while i < B:
print(A**i)
i = i + 1
while i >= B:
print(A**i)
i = i - 1
You could simplify this with numpy as follows
import numpy as np
A =float(input("Number:"))
B =int(input("Power:"))
print("Result of Powers:")
power = np.arange(B)
power_result = A ** power
sum_result = np.sum(power_result)
print(power_result)
print(sum_result)
I made B into an int, since I guess it makes sense. Have a look into the numpy documentation to see, what individual functions do.
You can create another variable to store the sum
and to print values on the same line use end=" " argument in the print function
a = float(input("Number:"))
b = int(input("Power:"))
sum = 0.0
i = 0
while b < 0:
ans = a**i
i = i - 1
print(ans, end=" ")
sum = sum + ans
b += 1
while b >= 0:
ans = a**i
i = i + 1
print(ans, end=" ")
sum = sum + ans
b -= 1
print("\nSum = " + str(sum))
I'm not sure what you want to achieve with the second loop. This works:
A =float(input("Number:"))
B =float(input("Power:"))
print("Result of Powers:")
i = 0
n_sum = 0
while i < B:
n_sum += A**i
print(A**i)
i = i + 1
while i >= B:
n_sum += A**i
print(A**i)
i = i - 1
print(n_sum)

Why is the entire loop code is being ignored?

The block of loop code is ignored and only the initial value is being used. It works well till I input fin and then simply the value 0 (as I have initialised it like that) is output as shown in the code.
I'm trying to make a very basic voting system with numbers as input.
z = 0
a = 0
b = 0
while z != 'fin':
n = input()
if n == 1:
a = int(a) + 1
elif n == 2:
b = int(b) + 1
else:
pass
z = n
c = 'kushagra'
d = 'kunaal'
print(f"{c} got {a} votes.\n{d} got {b} votes")
Like Mad Physicist said, n is a string not a number.
I changed the code to this :
z = 0
a = 0
b = 0
while z != 'fin':
n = input()
if n == '1':
a += 1
elif n == '2':
b += 1
else:
pass
z = n
c = 'kushagra'
d = 'kunaal'
print(f"{c} got {a} votes.\n{d} got {b} votes")
And it seems to work.

how to print all the output at the end of the while loop in python

I already solved this with list.append() function however my instructor told me to just use the basic python functions. Here is my code:
a = 0
b = 0
s = 0
x = str(s)
print ('Enter the first number: ', end = '')
c = input()
a = int(c)
finished = False
while not finished:
print ('Enter the next number (0 to finish): ', end ='')
n = input()
b = int(n)
if b != 0:
if b == a:
x = ('Same')
elif b > a:
x = ('Up')
elif b < a:
x = ('Down')
a = b
s = x
else:
finished = True
print (str(x))
I am aiming to print (e.g. Up Down Up Down Same in comparing the input integers) in one line at the end of the while loop. Let me know how can I improve my code. Thank you very much
Use string concatenation to get the result you want without using a list:
http://www.pythonforbeginners.com/concatenation/string-concatenation-and-formatting-in-python
I'll give you two hints on how to do this for your program:
Initialize x as an empty string by replacing
x=str(s)
with
x=""
There is no need for it to begin as the string "0", which str(s) does since s is 0.
Instead of saying
x=('SAME')
x=('UP')
x=('DOWN')
try saying
x=x+'SAME'
x=x+'UP'
x=x+'DOWN'
I removed the parentheses because they are not necessary.
As for style, it is good practice to name your variables as useful things instead of just letters. Last staement in an if/else chain that covers all bases should just be else. Best of luck to you sir
Not sure what result you're looking for, but perhaps this works:
a = 0
b = 99
result = ""
a = int(input('Enter the first number: '))
while b != 0:
b = int(input('Enter the next number (0 to finish): '))
if b == a:
result += ' Same'
elif b > a:
result += ' Up'
elif b < a:
result += ' Down'
a = b
print(result.strip())
Output:
Enter the first number: 12
Enter the next number (0 to finish): 12
Enter the next number (0 to finish): 12
Enter the next number (0 to finish): 1
Enter the next number (0 to finish): 1
Enter the next number (0 to finish): 5
Enter the next number (0 to finish): 0
Same Same Down Same Up Down
You can simply initialize x with an empty string and keep concatenating to it.
a = 0
b = 0
s = 0
x = ''
print('Enter the first number: ', end='')
c = input()
a = int(c)
finished = False
while not finished:
print('Enter the next number (0 to finish): ', end='')
n = input()
b = int(n)
if b != 0:
if b == a:
x += 'Same\n'
elif b > a:
x += 'Up\n'
elif b < a:
x += 'Down\n'
a = b
s = x
else:
finished = True
print(str(x))

python function wont return value

I'm new to python and am trying to make a simple paper, rock, scissors game. no matter what I do inside my "lame" function the value of local variable "y" will not be assigned to global variable "var1" or "var2". I have tried using return but cannot get anything to work.
#get input (paper, rock scissors from players)
play1 = input("player 1:")
play2 = input("player 2:")
#set value of players score to 0
val1 = 0
val2 = 0
def lame(x, y):
#set value of p, r, s choice, to 1, 2 or 3
if x in("p","P"):
y = y + 1
elif x in("r","R"):
y = y + 2
elif x in("s","S"):
y = y + 3
else:
print("your value was not p, r or s")
#run function "lame" and pass in "play1" choice and
#retrieve "val1" for that choice
lame(play1, val1)
lame(play2, val2)
def win(x, y):
#subtracts value of players choices to find winner
dif = x - y
if dif == 0:
print("tie game")
elif dif % 3 == 1:
print("player 2 wins")
elif dif % 3 == 2:
print("player 1 wins")
else:
print("logic error")
#call function "win" and pass in results of their choices
win(val1, val2)
The wrong way to do this:
val1 = 0
...
def lame(x):
global val1
val1 = result_of_some_calculations_to_do_with(x)
The right way to do this:
def lame(x):
return result_of_some_calculations_to_do_with(x)
val1 = lame(x)
Contrary to what L3viathan said in the comments, Python DOES pass variables by reference, but does not ASSIGN variables by reference. In other words:
x = 3 # x is 3
y = x # x is 3, y is 3, x is y
y = 4 # x is 3, y is 4, y is REASSIGNED so y is not x
That's basically what you were trying to do, passing val1 to your lame function and rebinding it as y.
val1 = 0 # val1 is 0
def lame(x, y):
# y is val1
y = some_calculations_to_do_with(x)
# y has been REASSIGNED so y is not val1
This is important when you pass objects like lists that are mutable (e.g. they can be changed, as opposed to immutable objects line int and str in Python).
val1 = list() # val1 is an empty list
def lame(x,y):
y.append(x) # append x to y, DO NOT REASSIGN y TO ANYTHING ELSE
lame(1, val1) # val1 is [1]
Right after I posted this question I figured it out, and can confirm what Adam Smith has said.
Here is the code I changed to get it working properly:
def lame(x):
#set value of p, r, s choice to 1, 2 or 3
if x in("p","P"):
return 1
elif x in("r","R"):
return 2
elif x in("s","S"):
return 3
else:
print("your value was not p, r or s")
#run function "lame" and pass in play1 choice and
#retrive val1 for that choice
val1 = lame(play1)
val2 = lame(play2)

Categories