How can i improve this code to run faster? [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 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.

Related

"The cheater's coin" python riddle [closed]

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.

Conditional - Try something for x seconds [closed]

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 1 year ago.
Improve this question
This is my first question, as I have started to code recently.
here it goes...
I dont know how to do it, so I haven't coded it yet.
The idea is to have a Conditional to try doing something for x seconds, and if nothing happens on this x seconds, then do something to try it again.
Like this..
Try for 5 seconds to:
click on element to download something # <- this I know how to do
if nothing happens: # <- no error, just not executed the line above
refresh the page
try again:
finally:
You have your file
sorry for my English, as it is not my primary language and I am also learning it...
what web scraping tool you are using? selenium ? I can only give you my
logic if you do not post your code.
import datetime
def page_refresh():
print('refresh page')
driver.refresh()
def check_and_wait():
status_ready = False
while (not status_ready):
start_time = datetime.now()
while(not status_ready and datetime.now()-start_time<5): # loop 5 seconds
if(condtion == True): # if something happen
status_ready = True
return
page_refresh() # nothing happen , loop again

While loop not running indefinitely [python3]? [closed]

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 3 years ago.
Improve this question
I'm creating TUI (Text-based user interface) using print statements, and when I want to return to the 'homescreen' i want the older code to run again.
randbool = True
while randbool:
print('1')
randbool = False
while not randbool:
print('2')
randbool = True
the result im expecting is
1
2
1
2
1
2
....
but it only prints 1, 2 how can I make it run indefinitely?
Not advisable, but:
while True:
print('1')
print('2')
This will print 1,2,1,2,1,2 indefinitely, until your CPU usage is at 100%, and your whole system freezes.
But it will accomplish what you're asking for.
Edit to add: 100% CPU usage demonstrated on an i7 laptop with 16GB RAM on Ubuntu 18.04:
If the value of randbool lets you get in a loop, changing it will stop the loop.
So don't change it for a loop you don't want to stop.
If you want to print 1 and 2 indefinitely, a simpler solution would be:
# loop forever
while True:
print('1')
print('2')

How to call function every 2 seconds in Python? [closed]

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 3 years ago.
Improve this question
I am trying to figure out How to call function every 2 seconds in Python?
Should I use timer or thread?
Can anyone provide links/examples please?
The sched module can do that:
import sched, time
schedTimer = sched.scheduler(time.time, time.sleep)
def increaseX(x):
x += 1
print('X increased to ' + str(x))
schedTimer.enter(2, 1, increaseX, (x,))
schedTimer.enter(2, 1, increaseX, (3,))
schedTimer.run()

How Can I Print Running Text? For Example to Print "Stack" Python Will Print S then t then a then c and then k? [closed]

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")

Categories

Resources