I'm trying to build Nim "mathematical game of strategy" in Python, I have problem with removing element from specific list from the matrix, I started with getting game mode from user and then start removing elements.
def RemoveMatches(Stacks,StackNum,Matches):
if not_empty(Stacks[StackNum]):
lenStack=len(Stacks[StackNum])
try:
val=int(Matches)
except ValueError:
print ("Wrong input,try only with numbers")
return False
if val>lenStack:
print "try again with smaller number"
return False
else :
for i in range(Matches):
Stacks[StackNum].pop()
return True
else:
print "Stack that you have chose is already empty,try other satck"
return False
Stacks is the matrix that i build in main.
StackNumnumber of list that i want to remove from it elements.
Matches number of elements that i want to remove.
There is another function called ManageGame which control user's input "if it's 2 players or 1, getting StackNum/Matches":
def ManageGame(Stack,gameMode):
if gameMode=='2':
while(lastDot(Stack)):
stackNum,matchesNum=raw_input('select number of the Stack and number of Matches between 1-10. keep a space between two numbers:').split(' ')
check=RemoveMatches(Stack,int(stackNum),int(matchesNum))
if check:
DrawStacks(Stack)
else:
print "try again."
lastDot(Stack) is a function which checks if the matrix has more then 1 Dot.
The problem is when I'm trying to remove number of elements from StackNum I get somthing like this:
from:
When I type StackNum=1,Matches=2 I get:
Somehow I remove 2 Dots from each matrix line, I cannot see the problem in my code.
The return in the line:
for i in range(Matches):
Stacks[StackNum].pop()
return True
is situated in the wrong location. you have to move it after the for.
Otherwise, after the first iteration it will exit and not run all the iterations:
for i in range(Matches):
Stacks[StackNum].pop()
return True
the problem here with the list l=[],here how I build my matrix:
l=[]
tmp=[]
for i in range(10):
l.append('*')
for i in range(5):
tmp.append(l)
python works with pointers so I'm appending same pointer for tmp, when I make a change to one of them the rest going to be the same .
Here how I did solve it :
for i in range(5):
tmp.append(10)
When I want to pop an element I subtract Matches number.
Related
I'm making a method that takes a string, and it outputs parts of the strings on separate line according to a window.
For example:
I want to output every 3 letters of my string on separate line.
Input : "Advantage"
Output:
Adv
ant
age
Input2: "23141515"
Output:
231
141
515
My code:
def print_method(input):
mywindow = 3
start_index = input[0]
if(start_index == input[len(input)-1]):
exit()
print(input[1:mywindow])
printmethod(input[mywindow:])
However I get a runtime error.... Can someone help?
I think this is what you're trying to get. Here's what I changed:
Renamed input to input_str. input is a keyword in Python, so it's not good to use for a variable name.
Added the missing _ in the recursive call to print_method
Print from 0:mywindow instead of 1:mywindow (which would skip the first character). When you start at 0, you can also just say :mywindow to get the same result.
Change the exit statement (was that sys.exit?) to be a return instead (probably what is wanted) and change the if condition to be to return once an empty string is given as the input. The last string printed might not be of length 3; if you want this, you could use instead if len(input_str) < 3: return
def print_method(input_str):
mywindow = 3
if not input_str: # or you could do if len(input_str) == 0
return
print(input_str[:mywindow])
print_method(input_str[mywindow:])
edit sry missed the title: if that is not a learning example for recursion you shouldn't use recursion cause it is less efficient and slices the list more often.
def chunked_print (string,window=3):
for i in range(0,len(string) // window + 1): print(string[i*window:(i+1)*window])
This will work if the window size doesn't divide the string length, but print an empty line if it does. You can modify that according to your needs
I am trying to solve some problems in CodeAbbey using Python.I have run into a wall trying to take input for these programs.I have spent so much time analyzing how to take the input data without even solving the question.Hope someone explains how to take input.
Problem:I have to input the following numbers in One go. I have tried using 'input()' but it takes only one line. Is there any work around to do it in a simple way? i wasted so much time trying to analyse various options
632765 235464
985085 255238
621913 476248
312397 751031
894568 239825
702556 754421
474681 144592
You can find the exact question here: http://www.codeabbey.com/index/task_view/sums-in-loop
You can just repeat input() until you get all your data, e.g.:
try:
input = raw_input # fix for Python 2.x compatibility
except NameError:
pass
def input_pairs(count):
pairs = [] # list to populate with user input
print("Please input {} number pairs separated by space on each new line:".format(count))
while count > 0: # repeat until we get the `count` number of pairs
success = True # marks if the input was successful or not
try:
candidate = input() # get the input from user
if candidate: # if there was some input...
# split the input by whitespace (default for `split()`) and convert
# the pairs to integers. If you need floats you can use float(x) instead
current_pair = [int(x) for x in candidate.split()]
if len(current_pair) == 2: # if the input is a valid pair
pairs.append(current_pair) # add the pair to our `pairs` list
else:
success = False # input wasn't a pair, mark it as unsuccessful
else:
success = False # there wasn't any input, mark it as unsuccessful
except (EOFError, ValueError, TypeError): # if any of the conversions above fail
success = False # mark the input as unsuccessful
if success: # if the input was successful...
count -= 1 # reduce the count of inputs by one
else: # otherwise...
print("Invalid input, try again.") # print error
return pairs # return our populated list of pairs
Then you can call it whenever you need number pairs like:
my_pairs = input_pairs(7) # gets you a list of pairs (lists) entered by user
My first attempt would be to try a typing like "632765 235464\n985085 255238[...]" so you could read it as one line. This would be pretty hacky and not a good idea if its real userinput.
The other idea: Why not taking the input line by line and putting these lines in a list / appending them to a string?
EDIT:
I found some Code on SO, but its python2.7 i guess. ->Here
The Python3.X style would be:
#!/usr/bin/python
input_list = []
while True: # Infinite loop, left by userinput
input_str = input(">") #The beginning of each line.
if input_str == ".": #Userinput ends with the . as input
break # Leave the infinite loop
else:
input_list.append(input_str) #userinput added to list
for line in input_list: #print the input to stdout
print(line)
Hope this will help :)
My goal is to create a little program that converts angle from radiant to degree and vice-versa. I need the program to close with no error message from python if the user enters the information to convert in the wrong format.
After assigning the variable ‘angle’ to both values of the input. The angle variable becomes a list type.
In norther to exit program with no error message I write this:
'if angle is not list():break'.
The problem is when I do that it exits the program for any type of command entered as an input.
here is my code:
import numpy as np
while 1:
angle=input("Please enter the angle you want to convert,\n\n"\
"If you wish to convert degrees in radiant or vise-versa,\n"\
"follow this format: 'angle/D or R'").split('/')
if angle is not list():break
angle[0]=float(angle[0])
radiant= (angle[0]*(np.pi))/180
degre=((angle[0]*180)/np.pi)
if (angle[0]>=0 or angle[0]<=360) and angle[1] is 'D' :
print(radiant,'radiants')
elif angle[1] is 'R':
print(degre,'degrés')
else:break
You can use isinstance(angle, list) to check if it is a list. But it won't help you achieve what you really want to do.
The following code will help you with that.
question = """Please enter the angle you want to convert.
If you wish to convert degree in radiant or vice-versa.
Follow this format: 'angle/D or R'
"""
while 1:
angle=input(question).split('/')
if not isinstance(angle, list): break # This will never happen
# It will never happen because string.split() always returns a list
# Instead you should use something like this:
if len(angle) != 2 or angle[1] not in ['D', 'R']:
break
try:
angle[0]=float(angle[0])
except ValueError:
break
if (angle[0]>=0 or angle[0]<=360) and angle[1] is 'D':
# You could also improve this by taking modulo 360 of the angle.
print((angle[0]*np.pi)/180, 'radiants')
else:
# Just an else is enough because we already checked that angle[1] is either D or R
print((angle[0]*180)/np.pi, 'degrees')
What you want:
if not isinstance(angle, list): break
What you've done: if angle is not list():break will always evaluate to True as no object will ever have the same identity as the list list(); since is is a check for identity.
Even this:
>>> list() is not list()
True
break statements are used to get out of for and while loops. Try using a while loop after the input statement to evaluate the input. Use a possible set as a conditional. You do not need to break from an if statement because it will just be bypassed if the the conditional is not met.
Sometimes you might see an if statement followed by a break statement. The break statement, however, is not breaking from the if statement. It is breaking from a previous for or while loop.
Pretty new to python/programming in general, this is my biggest project yet.
I am writing a program that will do SUVAT equations for you. (SUVAT equations are used to find the displacement, start/end velocity, acceleration and time travelled by an object with constant velocity, you may call them something different.)
I made this list:
variables = ["Displacement", "Start Velocity", "End Velocity", "Acceleration", "Time"]
which is used in the following while/for loop:
a = 0
while a==0:
for variable in variables:
# choice1 is what the user is looking to calculate
choice1 = raw_input("Welcome to Mattin's SVUVAT Simulator! Choose the value you are trying to find. You can pick from " + str(variables))
# will execute the following code when the for loop reaches an item that matches the raw_input
if choice1 == variable:
print "You chave chosen", choice1
variables.remove(variable) #Removes the chosen variable from the list, so the new list can be used later on
a = 1 # Ends the for loop by making the while loop false
# This part is so that the error message will not show when the raw_input does not match with the 4 items in the list the user has not chosen
else:
if choice1 == "Displacement":
pass
elif choice1 == "Start Velocity":
pass
elif choice1 == "End Velocity":
pass
elif choice1 == "Acceleration":
pass
# This error message will show if the input did not match any item in the list
else:
print "Sorry, I didn't understand that, try again. Make sure your spelling is correct (Case Sensitive), and that you did not inlcude the quotation marks."
Hopefully the comments I have written in the code should explain my intentions, if not, feel free to ask anything.
The problem is that when I run the code, and input choice1, the for loop activates the last line of code:
else:
print "Sorry, I didn't understand that, try again. Make sure your spelling is correct (Case Sensitive), and that you did not inlcude the quotation marks."
and then prompts me to enter the input again, and will do this as many times as it needs to get to the item on the list that I am typing.
However, I specifically coded that if what I input does not match the item on the list the for loop is currently checking, but does match one of the other items on the list, then it should pass and loop round to checking the next item.
I am probably doing something stupid, but I don't see it, so please help me figure out what I have to do to get my desired result? I assumed it was the syntax I had wrong so that is why that is the title.
Thanks for any help, I appreciate it.
Besides the problem with the indentation in your pasted code, I would rewrite it as such:
while True:
choice = raw_input('...')
if choice in variables:
print "You chave chosen", choice
# Remove the chosen member from the list
variables = [v for v in variables if v != choice]
# Break out of loop
break
# Print error messages etc.
Also remember that string comparisons are case sensitive. I.e 'Displacement' != 'displacement'.
Question: write a program which first defines functions minFromList(list) and maxFromList(list). Program should initialize an empty list and then prompt user for an integer and keep prompting for integers, adding each integer to the list, until the user enters a single period character. Program should than call minFromList and maxFromList with the list of integers as an argument and print the results returned by the function calls.
I can't figure out how to get the min and max returned from each function separately. And now I've added extra code so I'm totally lost. Anything helps! Thanks!
What I have so far:
def minFromList(list)
texts = []
while (text != -1):
texts.append(text)
high = max(texts)
return texts
def maxFromList(list)
texts []
while (text != -1):
texts.append(text)
low = min(texts)
return texts
text = raw_input("Enter an integer (period to end): ")
list = []
while text != '.':
textInt = int(text)
list.append(textInt)
text = raw_input("Enter an integer (period to end): ")
print "The lowest number entered was: " , minFromList(list)
print "The highest number entered was: " , maxFromList(list)
I think the part of the assignment that might have confused you was about initializing an empty list and where to do it. Your main body that collects data is good and does what it should. But you ended up doing too much with your max and min functions. Again a misleading part was that assignment is that it suggested you write a custom routine for these functions even though max() and min() exist in python and return exactly what you need.
Its another story if you are required to write your own max and min, and are not permitted to use the built in functions. At that point you would need to loop over each value in the list and track the biggest or smallest. Then return the final value.
Without directly giving you too much of the specific answer, here are some individual examples of the parts you may need...
# looping over the items in a list
value = 1
for item in aList:
if item == value:
print "value is 1!"
# basic function with arguments and a return value
def aFunc(start):
end = start + 1
return end
print aFunc(1)
# result: 2
# some useful comparison operators
print 1 > 2 # False
print 2 > 1 # True
That should hopefully be enough general information for you to piece together your custom min and max functions. While there are some more advanced and efficient ways to do min and max, I think to start out, a simple for loop over the list would be easiest.