so I wanted to create a code in python that automatically type numbers from 1 to 100
and it doesn't work. Hope someone can help
Here's my code
from pynput.keyboard import Key, Controller
import time
keyboard = Controller()
n = 1
time.sleep(2)
while 1 == 1:
keyboard.press(n)
keyboard.release(n)
n = n + 1
(I have "pynput" and "time" installed)
I tried reading error and from what I know have I think it's the problem with this characters "", but if I'm gonna add them I will not be able to add bigger number
You can convert the type of the variable to string:
while 1 = 1:
for ch in str(n):
keyboard.press(str(ch))
keyboard.release(str(ch))
n = n + 1
But you need to put a for loop because when the number is over 9, you need to send separately all digits for each number.
check your conditions in while loop
from pynput.keyboard import Key, Controller
import time
keyboard = Controller()
n = 1
time.sleep(2)
while n <= 100:
if n <10:
press_key = str(n)
keyboard.press(str(press_key))
keyboard.release(str(press_key))
elif n>=10 and n<=99:
press_key_first_digit = str(n//10)
press_key_second_digit = str(n%10)
keyboard.press(str(press_key_first_digit))
keyboard.release(str(press_key_first_digit))
keyboard.press(str(press_key_second_digit))
keyboard.release(str(press_key_second_digit))
else:
keyboard.press("1")
keyboard.release("1")
keyboard.press("0")
keyboard.release("0")
keyboard.press("0")
keyboard.release("0")
n = n + 1
Related
Well, I'm quite a beginner and need some help and advice. Sometime ago i watched this video about 100 prisoners question and wanted to write a proof program to see if the ratio really approaches to ~30%. But i got ~12%. I couldnt really find out where I did mistakes. Here is my code:
import random
from statistics import mean
prisoners = []
box_dict = {}
saved_prisoners = []
counter = 0
average = []
for i in range(1, 101):
prisoners.append(i)
for i in range(1000):
def control_list_generation():
for i in range(100):
x = random.sample(prisoners, 1)
y = x[0]
box_dict[i] = y
control_list_generation()
def open_box():
global saved_prisoners
global counter
counter = 0
for prisoner in range(100):
counter = prisoner
for turn in range(50):
if box_dict.get(counter) == (prisoner + 1):
saved_prisoners.append(1)
break
else:
counter = box_dict.get(counter) - 1
continue
open_box()
average.append(len(saved_prisoners))
saved_prisoners.clear()
print(mean(average))
P.S. range on the 13th line can be changed
Your code has a lot of superfluous lines. Just by editing out anything unneeded, you can end up with:
import random
from statistics import mean
prisoners = list(range(1, 101))
box_dict = {}
saved_prisoners = []
counter = 0
average = []
for i in range(1000):
for i in range(100):
x = random.sample(prisoners, 1)
y = x[0]
box_dict[i] = y
counter = 0
for prisoner in range(100):
counter = prisoner
for turn in range(50):
if box_dict.get(counter) == (prisoner + 1):
saved_prisoners.append(1)
break
else:
counter = box_dict.get(counter) - 1
continue
average.append(len(saved_prisoners))
saved_prisoners.clear()
print(mean(average))
However, you just use the dict more or less as a new list (the indices amount to the same as just shuffling the prisoners in a list). And when constructing it, you're accidentally duplicating prisoner tickets by sampling from the same prisoners over and over. (as user #MichaelButscher correctly points out in the comments)
If you fix those issues, your code still doesn't quite work because you have some further mistakes and moving around of numbers in your box checking.
Here's a solution that follows the pattern of your code, but shows the problem correctly:
import random
n_prisoners = 100
prisoners = list(range(n_prisoners))
boxes = []
failures = 0
attempts = 1000
for i in range(attempts):
boxes = list(prisoners)
random.shuffle(boxes)
for prisoner in prisoners:
box_nr = prisoner
for turn in range(n_prisoners // 2):
if boxes[box_nr] == prisoner:
break
box_nr = boxes[box_nr]
else:
failures += 1
break
print(f'{failures / attempts * 100}% of attempts failed')
Example output:
70.3% of attempts failed
As a general tip: don't get too hung up on numbering stuff from 1 instead of 0. That caused several coding mistakes in your code, because you kept having to correct for 'off by one' problems. Simply numbering the prisoners from 0 to 99 is far simpler, as it allows you to use the prisoner's number as an index. In case you need to print their number and need that to start at 1 - that would be the time to offset by one, not everywhere in your logic.
Starting to learn Python 3 on HackerRank when I run this code I get
this error:
Time limit exceeded
Your code did not execute within the time limits. Please optimize your code. For more information on execution time limits, refer to the environment page
Here is a link to the question on Hackerrank.
https://www.hackerrank.com/challenges/repeated-string/problem?h_l=interview&playlist_slugs%5B%5D=interview-preparation-kit&playlist_slugs%5B%5D=warmup
#!/bin/python3
import math
import os
import random
import re
import sys
#
# Complete the 'repeatedString' function below.
#
# The function is expected to return a LONG_INTEGER.
# The function accepts following parameters:
# 1. STRING s
# 2. LONG_INTEGER n
#
def repeatedString(s, n):
Write your code here
i = 0
aCount = 0
while i <= n:
if 'a' == s[i]:
aCount += 1
++i
else:
++i
print(aCount)
return aCount
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
s = input()
n = int(input().strip())
result = repeatedString(s, n)
fptr.write(str(result) + '\n')
fptr.close()
Even though ++i is syntactically valid, it doesn't do what one would expect it to do, coming from a C-like language. In Python, ++i is just unary + applied to i twice (+(+i)), without changing it. The Python way of incrementing a variable is i+=1.
You're running the while loop from 0 to n, maximum value for n is 10^12. That while loop is running 10^12 times in worst case. That's why time exceeded. Try to optimize code.
Try this code
def repeatedString(s, n):
#Write your code here
aCount = 0
for i in range(len(s)):
if 'a' == s[i]:
aCount += 1
aCount*=(n//len(s))
x=n%len(s)
for i in range(x):
if 'a' == s[i]:
aCount += 1
return aCount
I have a function and I want to know how many times this function is executed per minute
For example, write every 1 minute :
204 hash/m
This is my function
def test_hash_abc(difficulty):
x = 0
while 1:
y = hashlib.sha256("hello world{}".format(x).encode('utf-8')).hexdigest()
if y[0:len(difficulty)] == str(difficulty) :
print(y)
x+= 1
else : x+= 1
test_hash_abc('ffff')
Your function contains while 1 which is an infinite loop in your case (as you never break out of the loop). I assume you want to see how many times per minute the code under while 1 runs. In that case, try the following:
import hashlib
import time
def test_hash_abc(difficulty):
x = 0
counter = 0
while 1:
start = time.time()
while time.time() - start < 60:
y = hashlib.sha256("hello world{}".format(x).encode('utf-8')).hexdigest()
if y[0:len(difficulty)] == str(difficulty) :
print(y)
x+= 1
else:
x+= 1
counter += 1
print('{} hash/m'.format(counter))
test_hash_abc('ffff')
Note that removing print(y) will result in a higher execution number per minute.
cant say about per minute but you can use line_profiler module which have time per hit table on line basis
import time, itertools, win32com.client
print("Ctrl+C to start...")
while True:
try:
time.sleep(0.01)
except KeyboardInterrupt:
print("BruteForcing will start after 3 seconds...")
time.sleep(3)
break
shell = win32com.client.Dispatch('WScript.Shell')
msgs = 0
#here we go!
chrs = '0123456789'
min_length, max_length = 6, 6
file = open('data.di', 'a')
for n in range(min_length, max_length+1):
for xs in itertools.product(chrs, repeat=n):
x = ''.join(xs)
for m in range(0, len(x)):
shell.SendKeys(x[m])
shell.SendKeys("{ENTER}")
well, this programe gonna make a random number (Lenth = 6 digits) x and write them in a box and then press enter (As a bot). it works in the 1st fine but for some reasons, it starts giving random symboles and numbers later.
Example:
13&&
001
2121521
7-011
à'&é-é2
I would like to know if there are any bugs in the script and why this is happening. Thanks
Use random.choice(seq):
import random
for n in range(min_length, max_length+1):
for _ in range(n):
shell.SendKeys(random.choice(chrs))
shell.SendKeys("{ENTER}")
Sends 6 random digits followed by enter.
I'm trying to write a function that calls a function (roll die() which rolls a die 1000 times and counts on a list [1,2,3,4,5,6] so an outcome might be [100,200,100,300,200,100]) and tells it to run it x amount of times. It seems my code is printing it over and over again x times
#simulate rolling a six-sided die multiple tiems, and tabulate the results using a list
import random #import from the library random so you can generate a random int
def rollDie():
#have 6 variables and set the counter that equals 0
one = 0
two = 0
three = 0
four = 0
five = 0
six = 0
#use a for loop to code how many times you want it to run
for i in range(0,1000):
#generate a random integer between 1 and 6
flip = int(random.randint(1,6))
# the flip variable is the the number you rolled each time
#Every number has its own counter
#if the flip is equal to the corresponding number, add one
if flip == 1:
one = one + 1
elif flip == 2:
two = two + 1
elif flip == 3:
three = three + 1
elif flip == 4:
four = four + 1
elif flip == 5:
five = five + 1
elif flip == 6:
six = six + 1
#return the new variables as a list
return [one,two,three,four,five,six]
the new function that I am having problems with is:
def simulateRolls(value):
multipleGames = rollDie() * value
return multipleGames
I would like to see a result like this if you typed in 4 for value
[100,300,200,100,100,200]
[200,300,200,100,100,100]
[100,100,100,300,200,200]
[100,100,200,300,200,100]
Can someone guide me in the right direction?
You can get what you want like this:
def simulateRolls(value):
multipleGames = [rollDie() for _ in range(value)]
return multipleGames
By the way, your original function seems to work perfectly fine, but if you're interested, you can remove some redundancy like this:
def rollDie():
#have 6 variables and set the counter that equals 0
results = [0] * 6
#use a for loop to code how many times you want it to run
for i in range(0,1000):
#generate a random integer between 1 and 6
flip = int(random.randint(1,6))
# the flip variable is the the number you rolled each time
results[flip - 1] += 1
return results
The line
multipleGames = rollDie() * value
will evaluate rollDie() once and multiply the result by value.
To instead repeat the call value times do this.
return [rollDie() for i in xrange(value)]
You can also simplify your rollDie function by working with a list throughout
import random #import from the library random so you can generate a random int
def rollDie():
result = [0] * 6
for i in range(0,1000):
result[random.randint(0,5)] += 1
return result