Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 months ago.
Improve this question
I tried for hours to solve this python riddle in my level of knowledge and I don't know what to write past the thinking part "I need to make tails more frequent by using +1 to something" maybe. The riddle goes like that:
import random
def broken_coin():
if random.random() <= 0.9:
return "Heads"
return "Tails"
using no random source part of the function(which you can't edit), and turn the coin into a standard one: if you print the code the chances for heads will be 50% and the chances for tails will be 50%
thanks early to anyone who commented :)
EDIT: added what was my idea
If I read your problem correctly, you need to provide a method to compensate for the broken coin producing a relatively fair amount of results. With that instead of calling the broken_coin() function every time directly, one could call a function that calls the function and every other time returns the reverse result to the calling function.
After reading the comments about what could or could not be used, I've updated my sample code.
import random
def broken_coin():
if random.random() <= 0.9:
return "Heads"
return "Tails"
def fix_coin(j):
if j == 0:
return broken_coin()
coin = broken_coin()
if (coin == "Heads"):
return "Tails"
else:
return "Heads"
for x in range (100):
print(fix_coin(x %2))
See if this more closely fulfils the spirit of the problem.
Regards.
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I want to avoid bot detection and my random stuff isn't working. Actually it's not hitting dislike at all. Xpaths are all right. What am I doing wrong here?
def auto_swipe(self):
while True:
sleep_time = random.randrange(1, 3)
time.sleep(sleep_time)
try:
rand1 = random.randrange(0,100)
if rand1 < random.randrange(70,80):
self.like()
else:
self.dislike()
except Exception:
try:
self.close_popup()
except Exception:
self.close_match()
The standard way to use random is as follows. Assuming you'd like something to happen 75% of the time, you'll write the following:
if random.random() < 0.75:
# do something
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
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 7 years ago.
Improve this question
I'm making The Powder Toy in Python, and I encountered some problems. Firstly the code runs VERY slowly. I know the problem is in my main file: http://pastebin.com/bbQ4H4Xu. The other files are just detecting input / creating the 2d array, so the problem isn't there.
Within my main file, the problem seems to be in the method updatescreen(). How can I increase the performance of this function?
import pygame
#inputkey.py
from pygame.locals import *
def input_key():
global inputt
inputt = ""
key = pygame.key.get_pressed()
if key[K_q]:
return 'q'
elif key[K_w]:
return 'w'
elif key[K_e]:
return 'e'
elif key[K_r]:
return 'r'
#Createblocks.py
blocks = []
for i in range(400):
blocks.append([])
for j in range(400):
blocks[i].append(0)
Your Main.py file has a print statement in the loop:
def updatescreen():
#The problem is here, it slows down the code.
for i in range(windh):
for x in range(windw):
print x, i # <== Here
if not blocks[i][x] == 0:
if blocks[i][x] == "Stone":
screen.blit(elementStone, (x,i))
presumably for debug? That's performing windw * windh = 2,500 print operations, which will slow the code down for sure. Try removing that and see how it improves.
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
i am new to python as you may be able to tell with this question. I am currently building a Rock, Paper, Scissors game to later include into a bigger program i am working on in python 3.4. the problem i am having is in the code listed below.
def computerPlayer(): #randomly selects a rock paper or scissor for computer hand
c = random.randint(0, 2)
if c==0:
y=('rock')
if c==1:
y=('scissors')
if c==2:
y==('paper')
return y
in front of the bottom line return y i am getting a unexpected Indent error, i have tried correcting this over the past day now with no results, if i move it forward i get 'return' outside function, but when i move it back i get the unexpected indent, I am honestly at a complete loss here and im not sure where to go. Any help is great thanks.
the above problem is now fixed, but i know have a break outside of loop error. it is appearing at the end of my code now. any help is great thank you.
again = raw_input('do you wish to try again? (yes\no)\n :') #Ask the user if they want play again
if again == ('yes') or again == ('sure') or again == ('okay'):
print ('')
elif again == ('no') or again == ('nah') or again == ('nope') or again == ('screw you') or again == ('screw it'):
print ('FINE THEN!!! =^( \n (Enter>>>game()<<< if you change your mind)')
#breaks the loop
break
game()
Try this:
def computerPlayer():
'''
Randomly selects a rock paper or scissor for computer hand
'''
c = random.randint(0, 2)
if c == 0:
y = ('rock')
if c == 1:
y = ('scissors')
if c == 2:
y = ('paper')
return y
Indentation is important in python, it shows where your methods and control flows start and end. In your previous code, the if statements were not indented under the method and so python could not tell that it was apart of the computerPlayer() function.
According to PEP8 ( a style guide for python ) proper indentation is 4 spaces. For more information on PEP8 and its view on indentation, check here:
http://legacy.python.org/dev/peps/pep-0008/#indentation
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I am using notepad++ for writing codes and then seeing output using Windows Power Shell. Now lets say I want to print this...
"Stack Overflow"
But not all at once. First of all it will print S then t then a then c then k then a space and then O ...... ?
So is there any function/method to post the text as we type in old PCs?
If the question is not complete let me know what more information I can provide you.
Update
#uʍop ǝpısdn Yes, you understood my requirement. And many thanks for the answer. :)
Well I didn't know that it calls Emulating text. :)
Here you go:
import time, sys
for letter in "Stack Overflow":
sys.stdout.write(letter)
sys.stdout.flush()
time.sleep(1) # that's in seconds, adjust at will
sys.stdout.write('\n')
Why stdout.flush?
Output from a running program is usually buffered (i.e. held waiting) until certain conditions are met. The call to sleep() will not fulfill these conditions, and the text will not appear. By calling flush() after each letter, you force it out.
from __future__ import print_function # only needed for Python 2.x
import random
from time import sleep
def delay_print(s, min_delay=0.1, max_delay=0.8):
for ch in s:
delay = min_delay + random.random() * (max_delay - min_delay)
sleep(delay)
print(ch, end="")
print('')
delay_print("StackOverflow")