I want to use 3 variables in one for loops.
This is what I tried:
def loop_player_listbox():
global bol_loop, count
bol_loop = True
while True:
time.sleep(1)
str_libo_p = listbox.get(0,tk.END)
str_libo_r = listboxr.get(0,tk.END)
str_libo_price = listboxprice.get(0,tk.END)
for i,r,p in itertools.product(str_libo_p, str_libo_r, str_libo_price):
text_playername = wait.until(EC.element_to_be_clickable((By.XPATH,('/html/body/main/section/section/div[2]/div/div[2]/div/div[1]/div[1]/div[1]/div/input'))))
text_playername.click()
time.sleep(1)
text_playername.clear()
time.sleep(1)
text_playername.click()
text_playername.send_keys(i)
user_input_max_price = p
try:
choose_player = wait.until(EC.element_to_be_clickable((By.XPATH,("//span[#class='btn-text' and contains(text(),'"+i+"')]")))) and wait.until(EC.element_to_be_clickable((By.XPATH,("//span[#class='btn-subtext' and contains(text(),'"+r+"')]"))))
choose_player.click()
count = 0
while count < 5:
while True:
# some unimportant code
# set speed
# some unimportant code
# set max BIN price
while True:
#user_input_max_price = input('Enter max buy now price (>250):')
user_input_max_price = p
if user_input_max_price.isdigit():
int_user_input_max_price = int(user_input_max_price)
if int_user_input_max_price > 250:
break
else:
print('Max buy now price must be >250')
continue
else:
continue
# set max price
# some unimportant code
# Buy until 100 players were bought
while count < 5:
# some unimportant code
count +=1
The problem is, variable r and p do update after count = 5.
But i is always only showing the first item from my listbox and does not update. Every time my loop is coming back to the line for i,r,p ... I see in debug that only the variables r and p updated.
I have no idea why. While searching for how to combine more than one forloops I found itertoolsand so I used it.
Maybe anyone sees whast wrong?
Changed from itertools to zip fixed the issue.
for i,r,p in zip(str_libo_p, str_libo_r, str_libo_price):
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.
MAX_STUDENTS = 50
def get_student_ids():
student_id = 1
while student_id <= MAX_STUDENTS:
# Write your code below
n = yield student_id
if n != None:
student_id = n
continue
student_id += 1
student_id_generator = get_student_ids()
for i in student_id_generator:
# Write your code below
if i == 1:
i = student_id_generator.send(25)
print(i)
Im quite confused, when i run the code below, i understand the the send function gives 25 as the yield value and assigns it to n, however when entering the if statement, checking if n is not None, wouldnt this create an infinite loop, since n is not none, would take us to the continue statement, which takes us back to the next iteration of the while loop, completely skipping the incrementing of student id
The first thing one can notice is that n will always be of type none except when you send 25 into the generator.
Let's look at the flow of the program
this is the driver code at the start of the program
student_id_generator = get_student_ids() #creates a generator class
for i in student_id_generator: #interates through the generator class
if i == 1: # note that the first i == 1, so the first time the code hits
#this condition, it will be true
i = student_id_generator.send(25) #sets n to be 25
print(i) #for the first iteration, will return 1, as the first yield is 1
now, since n=25 (you just sent 25 into the generator code), let's look at the generator
n = yield student_id # n=25
if n != None: #since n==25, n is not none
student_id = n #student_id = 25
continue #go back to the while loop
student_id += 1 # will not be run
Now that student_id = 25, for the next iteration in the driver code, it will yield 25, so 25 will be printed. But n will be None as nothing is sent to the generator, so student_id += 1 will be run. From there, the while loop kicks in and it will continue until 'student_id == 50', where the loop breaks.
Will there be an infinite loop? No. Because the condition 'n != None' only occurs once.
I hope this helps. If you are still confused, my suggestion is to take out a pen and paper and work out what happens to the code step by step. I did that to help myself understand it.
%%sim_magic_preloaded --background Coloured_bands -R
# Program to count the bands aloud
# Start the robot moving
tank_drive.on(SpeedPercent(15), SpeedPercent(15))
# Initial count value
count = 0
# Initial sensor reading
previous_value = colorLeft.reflected_light_intensity_pc
# Create a loop
while True:
# Check current sensor reading
current_value = colorLeft.reflected_light_intensity_pc
# Test when the robot has entered a band
if previous_value==100 and current_value < 100:
# When on a new band:
# - increase the count
count = count + 1
# - display the count in the output window
print(count)
# - say the count aloud
say(str(count))
# Update previous sensor reading
previous_value = current_value
Need some help with this coding,im trying to make to make the robot stop after it goes over the black band which is the forth band and also it doesnt say out loud number 4 once it goes over the black band
import time
previous_value = colorLeft.color
tank_drive.on(SpeedPercent(15), SpeedPercent(15))
count = 1
while True:
current_value = colorLeft.color
print(current_value)
if previous_value==6 and current_value != 6:
print(count)
say(str(count))
count += 1
#Now it should stop at band 4
if count > 4 and current_value==6:
time.sleep(1)
tank_drive.off()
break
previous_value = current_value
I'm creating a function (using python) to automatically buy and sell a crypto, and automatically calculate the cumulative profit after each trade was done. I also want to see the profit for each trade in a list, this is how my function looks so far:
def tradingstrat(symbol, open_position = False):
total = 0
trade = []
while True:
#pulling data all the time because of the loop
df = getminutedata(symbol)
#check whether we have an opening position
if not open_position:
buyprice = df.Close[-1]
qty = money/buyprice
print('Bought', qty,"amount of", symbol,"#",buyprice)
open_position = True
break
if open_position:
while True:
#pulling data all the time because of the loop
df = getminutedata(symbol)
sellprice = df.Close[-1]
profit = (sellprice-buyprice)*qty
print('Sell', qty,"amount of", symbol,"#",sellprice)
open_position = False
break
total += profit
trade.append(profit)
print(trade)
print("Cummulative profit:",total)
With this, somehow the profit and cumulative profit always show the same value (as if the cumulative profit value is being reset after each loop), and the profit for each trade is also not appended to the list.
I wonder where did I do wrong? thank you!
def tradingstrat(symbol, open_position = False):
total = 0
trade = []
#check whether we have an opening position
if not open_position:
df = getminutedata(symbol)
buyprice = df.Close[-1]
qty = money/buyprice
print('Bought', qty,"amount of", symbol,"#",buyprice)
else:
df = getminutedata(symbol)
sellprice = df.Close[-1]
profit = (sellprice-buyprice)*qty
print('Sell', qty,"amount of", symbol,"#",sellprice)
total += profit
trade.append(profit)
print(trade)
print("Cumulative profit:",total)
I removed your while loops as you immediately break out of them. I also moved the total += profit and trade.append(profit) inside the loops so they will be updated. Some code reformatting was done as well
I'm not really new to python but I came across this problem that has just puzzled me.
So I was solving the maze runner problem, using A* and then was finding the hardest possible maze for a given dimension. For this purpose, I created a function called generateHardMaze() that is called from the main function and takes an attribute newMaze.
Now here is where things get weird, when I change the value of newMaze in the if condition within the while loop the hardMaze value changes without the code entering the second if condition. I'm not really sure why this happening was hoping someone could help me.
I'm using pycharm as my IDE and python3.6.* if that makes any difference.
I'm sure this isn't how oops works but I'm thinking this is a python thing. Has anyone ever come across anything like this? If yes please sympathize.
Thanks in advance.
def solveMazeAManH(newMaze,rows,cols):
startTime = time.time()
backTrackPriority = []
setup_cells(rows, cols)
# start and end points of the maze
start = (0, 0)
end = (rows - 1, cols - 1)
current = start
print("The path to be take is: ")
print(current)
frinLength = 0
# traversing the neighbours
while current != end:
unvisited.remove(current)
neighboursDFSandA(newMaze, current, rows, cols)
heuristic = calManhattanDis(current, end) # finding the heuristic for every traversal
try:
if not currentNeighbours:
if not backTrackPriority:
print("No path available!")
return 0
else:
while not currentNeighbours:
current = nextPopMan(backTrackPriority, end)
backTrackPriority.remove(current)
neighboursDFSandA(newMaze, current, rows, cols)
neighbor = leastPathChildMan(heuristic, current, end)
backTrackPriority.append(current)
current = neighbor
print(current)
frinLength += 1
except:
print("No path Found!")
return 0
return frinLength
endTime = time.time()
print("The time taken to solve the maze using A* with manhattan distance: ")
print(startTime - endTime)
def generateHardMaze(newMazes):
rows = len(newMazes)
cols = len(newMazes[0])
hardMaze = newMaze
print("Solving the original maze!")
fringLength = solveMazeAManH(newMazes, rows, cols)
print("Creating new harder Maze:")
pFlag = True
pCout = 0
while pFlag:
count = 0
flag = True
while flag:
point = choice(setup_cells(rows, cols))
if (newMazes[point[0]][point[1]] == 1):
newMazes[point[0]][point[1]] = 0
else:
newMazes[point[0]][point[1]] = 1
if (fringLength < solveMazeAManH(newMazes, rows, cols)):
print("Harder Maze--------------------")
hardMaze = newMaze
fringLength = solveMazeAManH(newMazes, rows, cols)
count = 0
else:
count += 1
if count >= 10:
flag = False
print("one")
newMazes = creatMaze(rows)
pCout += 1
if pCout >= 100:
pFlag = False
print(hardMaze)