A puzzle that needs to be programmed with Python? [closed] - python

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I'm a beginner in Python ... In fact, I'm beginner in programming. Python is the first programming language I started to learn.
I had received a puzzle which I liked to solve by writing a program to do it (as a practice) , but I couldn't.
The puzzle was the following:
Say you have 100 people, standing like they make a circle, each one of them has a number, the first one carries the number 1 , the second one carries the number 2 , ... , and so on ending with the last one who's carrying the number 100 ... The first one was given a sword to kill the one who has the number which is greater than his with 1 ... Which means he kills number 2 ... And then he gives the sword to the next one who is number 3 ... And the process keeps going until only one gets to stay alive! ... Who is that one?
I tried to solve it manually , and it turned out the answer was 73 ... Number 73 is the one who stays alive!
But, do you have any idea how to program it?
Thanks for your help!

Obviously you solved it by yourself... How? Can you make Python do it the same way ?
Because you are doing this as a learning exercise let's think about a few different things
How are you going to keep track of who is alive
How are you going to know when to stop killing people (that made me laugh) and
How are you going to pass the sword
To get you on the right track I would suggest googling something like "iteration in Python" or "Python control structures "
Because another answer has provided an iterative approach In my solution I will use recursion to solve the problem, where the function calls itself until it reaches the exit condition.
numPeople = 100
theCircle = list(range(1, numPeople + 1))
#Solve with recursion
def massacreRecursion(theCircle):
#Exit condition
if len(theCircle) == 2:
theCircle.pop(1) #kill the last victim so len(theCircle) == 1 is True
print(theCircle[0]) #Print the survivor
else:
theCircle.pop(1) #kill some poor pleb
theCircle.append( theCircle.pop( 0 )) #rotate the circle left 1 effectively passing the sword right
massacreRecursion(theCircle) #do it again and again and again...
#enter the recursion
massacreRecursion(theCircle)

Okay this is a fun problem and in my opinion is a great excuse to use pythons .pop function.
circle = list(range(1,101))
#100 people numbered 1-100
while len(circle) > 1: #run this code as long as the circle has more than one person
print(str(circle[0]) + " kills " + str(circle[1]))
survivor = circle[0] #save the survivor to a variable
circle.pop(1) #remove the person killed from the list
circle.pop(0) #remove the person who survives from the list
#now the new start of the list is whoever is next in line
circle.append(survivor) #re-add the survivor to the list at the end
print(str(circle[0]) + "is the winner") #print out the survivor
This works because the "start" of the circle is always circle[0], when two people fight, both the winner and loser are removed from the list, making circle[0] whoever is next in line. Then the winner is re-added to the end of the list, putting him at the back
I added a couple lines to print out the full evolution of the circle and uploaded it to a pastebin http://pastebin.com/raw/z6ghuqE3

Related

How to make a Dungeons and Dragons-esque skill check in Python?

I am trying to make a small text-based adventure game in Python IDLE, but I am running into some issues with having the game give a different response if the player rolls above or below the DC of a DND style preception check. I am very new to this so it's probably an easy fix. Here's the code.
I have no idea how to input the code into the question correctly so here is a picture.
BTW I did import random at the beginning of the code its just too far back to include in the screencap.
Your problem is you are not specifying what numbers the random module to choose from, in the line if random.randint > 10:. To fix this, put the numbers you want it to choose between. For example, if you want it to choose a random number between 1 and 20, your line would become if random.randint(1,20) > 10:.
You will also want to do this for the other line, which reads if random.randint < 10:.
welcome to SO,
Please read the minimal reproducible example guide posted in the comments by D.L. First thing I would do is to post the actual code, because if the link expires, then others viewing this post with a similar issue cannot figure out what was the given example, and how it was solved.
With logistics out of the way, to fix the error you are specifically receiving is to put what is rolled in a variable.
Here are a few things I would change to make your code clear
# Some string that receives yes or no
room_2_input = ("...")
# if condition is yes
if room_2_input == 'yes':
# Put it in a variable
roll = random.randint(1,20)
# You do not have to format a string this way, but I think it makes it easier
print('You rolled {}'.format(roll)
# Put this condition within the first if, because you don't
# need to execute it if they do not choose to roll
# Neither of your original condition has inclusivity, so if 10 is rolled,
# your program will do nothing, because neither condition would be met
if roll >= 10:
'''do stuff'''
# I would only include elif < 10 if you are specifically looking for > 2
# outcomes, but your outcome appears to be binary, either above or below 10
else:
'''do stuff'''
The reason you would not do a random.randint(1,20) > 10: check in your second if statement is because you would be executing a different roll than your first one.

Python - Method that calls itself [duplicate]

This question already has answers here:
How to repeat a section of the program until the input is correct?
(3 answers)
Closed 5 years ago.
I am trying to learn Python. I just made a simple rock, paper, scissors game for practice. I am having a small problem.
When each player choose the same item, the game ends in a tie.
When the player makes a mistake and has to choose again, the variable is empty. Notice that Player 1 says "none".
This is the method. The problem occurs in the else branch.
def play1():
player1_choice = input("Player 1 - Go: ")
if (check(player1_choice)):
return player1_choice
else:
print(error_msg)
play1() # Something is wrong here.
What did I do wrong? How can I fix it? Thanks
Don't use recursion if you don't have to. Try this:
def play1():
while True:
player1_choice = input("Player 1 - Go: ")
if (check(player1_choice)):
return player1_choice
else:
print(error_msg)
This is a classic while loop application; you want to loop until you get a reasonable answer (while the known answer is unacceptable), returning that answer to the calling program.
Use a for loop when you know as you enter the loop how many times you have to repeat it.
Recursion is proper when you have a job in which you can:
do something simple;
reduce the remaining task to something smaller, closer to a trivial "completed" state;
pass that smaller task to the same function for further processing.
In this application, getting a wrong answer from the user doesn't put you any closer to a solution (a valid answer) than when you started. The task isn't any simpler now. Further processing is the same, but you get that just as well with an iteration loop.

Restart Python Program within and If statement - not complex [duplicate]

This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 6 years ago.
Question1 = input("We will start off simple, what is your name?")
if len(Question1) > 0 and Question1.isalpha(): #checks if the user input contains characters and is in the alphabet, not numbers.
Question2 = input("Ah! Lovely name, %s. Not surprised you get all the women, or is it men?" % Question1)
if Question2.lower() in m: #checks if the user input is in the variable m
print ("So, your name is %s and you enjoy the pleasure of %s! I bet you didnt see that coming." % (Question1, Question2))
elif Question2.lower() in w: # checks if the user input is in the variable w
print ("So, your name is %s and you enjoy the pleasure of %s! I bet you didnt see that coming." % (Question1, Question2))
else: #if neither of the statements are true (incorrect answer)
print ("Come on! You're helpless. I asked you a simple question with 2 very destinctive answers. Restart!")
else:
print ("Come on, enter your accurate information before proceeding! Restart me!") #if the first question is entered wrong (not a name)
Question3 = input("Now I know your name and what gender attracts you. One more question and I will know everything about you... Shall we continue?")
In order to get the right answer, I will first tell you what happens when I run it:
There are several scenarios but I will walk you through 2. When I run the program I am first asked what my name is, I can enter anything here that is alphabetic, then it asks me if I like men or woman, weird I know but it's a project I am working on, if I were to say 'men' or 'women' the program runs perfectly, but if I were to enter say... 'dogs' it would follow the else statement print ("Come on! You're helpless. I asked you a simple question with 2 very destinctive answers. Restart!") but then it continues the code and goes to the last line shown above "Now I know your name and what gender attract you...... blah blah". What I am trying to do is have it restart the script if you were to enter anything other than 'men' or 'women'.
I was told that a while statement would work, but I would need an explanation as to why and how... I'm new to Python in a sense.
That's what loops are for.
while True:
# your input and all that here
if answer == "man" or answer == "woman":
# do what you want if the answer is correct
break # this is important, as it breaks the infinite `while True` loop
else:
# do whatever you want to do here :)
continue
If you want the script to repeat indefinitely, you can simply wrap everything in a while loop like so:
while True:
# Do yo your logic here.
# Break out when a condition is met.
If you want to be more savvy with it you can use a method and have the method call itself over and over until it's done.
def ask_questions():
# Do your logic here
if INPUT_NOT_VALID:
ask_questions()
else:
# Continue on.
Also, search on this site for you text because I've seen about five or six questions all involving this programming scenario which means it has to be a common problem from a programming class (one I'm assuming you are in). If that's the case discuss with classmates and try to stimulate each other to find the solution instead of just posting online for an answer.

Bypassing in-line if statements? Python [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
So I'm making a video player that automatically chooses the next video based on some weighted probabilities. When a video comes in, it reads all its metatags from a csv, then looks up the next match after the probability rolls. I had all the various metatag checks programmed in-line with if statements and for loops, but the client has just asked to have on and off switches for each of the filters and I'm having trouble wrapping my head around the most efficient way of approaching the problem.
I'm still fairly green with Python, so I figured I'd ask before trying to do something the worst way possible. I'm wondering (if there isn't a way to do this that I just don't know of yet) if it would be better to have the on and off switches interrupt and change the variables before they get to this point, so that for example when the on switch is on, a list of every possible color would be assigned to the variable color, so that it always passes and no videos get rejected from the color, thus keeping the same basic formatting.
Below is a simplified version of what I kind of have going on, for readabilities sake. Before it, the program gets all the variables it needs from the csv, and after the final print, the ones that pass get added to a list of good choices which is randomly pulled from:
for eachrow in table:
Answer = False
for eachcell in eachrow:
if color == req_color:
if speed == req_speed:
if exclusion == req_exclusion:
print ('No pass!')
else:
Answer = True
print ('All attributes match')
if Answer:
print ('This passes')
Cheers!
perhaps you are looking for continue ?
The continue statement is used to tell Python to skip the rest of the statements in the current loop block and to continue to the next iteration of the loop.
http://docs.python.org/reference/simple_stmts.html#continue
It sounds like you want to use continue. Continue is sort of like break, except where break terminates the loop, continue just skips the rest of the current run of the loop and starts the next.
I can't really tell what you are trying to do, but you could try something like this:
testsToRun = ['speed','color']
for row in table:
Answer = False
for cell in row:
if cell['color'] == color and 'color' in testsToRun:
print ('No pass!')
continue
if cell['speed'] == speed and 'speed' in testsToRun:
print ('No pass!')
continue
if cell['exclusion'] == exclusion and 'exclusion' in testsToRun:
print ('No pass!')
continue
Answer=True
print ('All attributes match')
if Answer:
print ('This passes')
Thanks for the advice, everyone. I solved the issue by actually going back to where the variables are defined. I set it so that when its off, it sends all the possible variables to the if, so that it always passes if its off. That way when the switch is on and it takes the user input, it selectively passes things through. I thought about other options but since this prototype has to have a quick turn around time, this seemed like the best bet.
Thanks again!

progress of loop indicator [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Python Progress Bar
I am running a for loop 10,000 times,
but inside the loop there are a lot of calculations going on.
I would like to print out a progress message to the console informing me how far along in the loop the program is how much longer I might have to wait.
the basic loop is
n = 10000
for i in range(n):
do_stuff_method()
if(i%100 == 0):
print (float(i)/n)*100,
This prints out a percentage message on the same line, but the problem is that the next thing that I print out is also printed out on the same screen. That, and since there are 99 prinouts, the console gets pretty wide and there is a lot of scrolling across.
What I would really like is for the console to print out the current % done, and an estimated time to finsih on the one line replace that which had been previously printed, so there doesn't have to be a lot scrolling.
Can this be done?
Cheers,
Davy
In your case you can do it simply by changing your print line to be:
print "\r{0}".format((float(i)/n)*100),
Or you can try it like this instead of print:
sys.stdout.write("\r{0}".format((float(i)/n)*100))
sys.stdout.flush()

Categories

Resources