I'm attempting to change a flag to True when a nested dictionary has more than one key. The code currently counts the number of keys correctly, but it is not changing the flag to true.
I've done both the condensed version below and the more broken out version to no avail. I've also rearranged the statement in multiple ways, but cannot get it to trigger.
for page in sd:
chartcount = len(sd[page])
print '\n', 'Slide no.', page, '--There is/are', chartcount, 'Chart(s).'
[combinecheck is True if chartcount > 0 else False]
print combinecheck
I expect:
Slide no. 1 --There is/are 2 Charts.
True
I get:
Slide no. 1 --There is/are 2 Charts.
False
Not sure what are you trying to do with [] part. That looks like list comprehension (that would be useful if you would be creating a list, which you aren't. And you are not assigning that list anywhere either way.), you dont need that.
Instead put there:
combinecheck = chartcount > 0
[combinecheck is True if chartcount > 0 else False]
isn't assigning to combinecheck.
Try:
combinecheck = False
if chartcount > 0:
combinecheck = True
Related
I am trying to implement turning of front wheels in PyBox2D, for now, I was able to make it turn left/right but I am not able to stop it when the angle reaches zero (to make the car to go straight)
My goal is to stop turning when the angle of a wheel reaches zero or value similar to zero, but not on the beginning (sometimes when the angles are zero they do not move at all, and if possible I would like to make it independent from pressing key on a keyboard (moving those two nested if statements out of the if keyboard_is_pressed(hotkey) part did not help
I hope I made myself clear and thank you very much for any help
EDIT I tried to implement solution given in the answer, it kind of worked but I tried to improve it and now I am stuck again, the wheels turn, but when they return to their initial position they stop moving. One of problems can be that when I press "a" or "d" key my variable self.ticking changes by more than just one, because I am not able to press the key for such a short period of time.
variable self.on_the_beginning is equivalent to on_starting_race from the answer below:
def control(self): # This makes control independent from visualisation
#Front left suspension: index 2
#Front right suspension: index 3
print(self.ticking)
if keyboard.is_pressed("a"):
self.suspensions[2].motorSpeed = -5
self.suspensions[3].motorSpeed = -5
self.ticking -= 1
if keyboard.is_pressed("d"):
self.suspensions[2].motorSpeed = 5
self.suspensions[3].motorSpeed = 5
self.ticking += 1
if self.ticking <= -3:
self.ticking = -3
self.on_the_beginning = True
elif self.ticking >= 3:
self.ticking = 3
self.on_the_beginning = True
if np.radians(-5) <= self.tires[2].wheel.angle <= np.radians(5) and self.on_the_beginning == True and self.ticking !=0:
self.suspensions[2].motorSpeed = 0
self.suspensions[3].motorSpeed = 0
self.tires[2].SetAngularVelocity = 0
self.tires[3].SetAngularVelocity = 0
self.ticking = 0
on_the_beginning = False
If i understand correctly, you can have a variable, say on_starting_race, set to false, then check whenever it is above a set number (say, when it's above 10 you know for a fact that the race has already started and the car moved at least for a few seconds), then change that value to True, now add an if statement to determine whether the value is close to 0 (say val<5) AND on_starting_race is True.
There might be a more elegant way, but this is pretty straight forward(assuming you check the state of the car every frame or a set period of time).
Sorry, because I am not 100% sure of your problem without the whole code.
I think the solution could be using an input parameter in you function, let's say first_run, that you can control from inside and outside the function.
def control(self, first_run=True):
This way, you may start the race (from your main program) setting first_run to True, so you don't care about the angle. And use this same function setting first_run to False the rest of the times.
You can also use a self.first_run variable that you may set to True in the init, then setting self.first_run to False if it is True (which is really the first time you use your control() function).
Does or condition work in a while loop in python? I can't seem to make it work. This is the sample of how my code works.
newslot = 3
moved = False
while newslot > 0 or moved != True:
enabled = query something on the database where slot = newslot
if enabled:
print 'do something here'
moved = True
else:
newslot-=1
print 'slot disabled'
So when the newslot gets to value of zero it still proceeds to go inside the while loop.
I seem to be missing something here.
or is working as should be expected. A while loop will continue until its condition is false. If its condition is two separate conditions connected with an or, it will only be false when the two conditions are both false.
Your loop will continue repeating until moved is false and newslot is <= 0. I'm guessing you actually want to use and in this case, as you want the loop to stop once either condition is met.
I'm trying to write a code that will check if an inputted word can be made with the letters of another word.
So far, I have:
def is_made_from(wordA,wordB):
for l in wordA:
if wordA.count(l) <= wordB.count(l):
return True
else:
return False
I'm not sure if what I mean is being translated to code. The loop goes through every letter in wordA to check if wordB has at least the same quantity of that letter as in wordA. However, when I run a free trials, the code seems to work when it should work but it also works when it shouldn't work. For example, if I made wordA == 'whiter' and wordB == 'white', it would return True, despite wordB not having the 'r.'
At the moment you return True even if only the 1st letter matches, because if the code enters the if on the first iteration, it returns True and the loop is exited.
You are looking for something like this
def is_made_from(wordA,wordB):
for l in wordA:
if not wordA.count(l) <= wordB.count(l):
return False
return True
It works the other way round.
Pedantically-awesome version:
from collections import Counter
def is_made_from(first, second):
return len(Counter(first) - Counter(second)) == 0
(this honestly suffers from being "too clever"; calling .count() in a loop is probably more readable and performs just fine unless your words are tens of thousands of characters long)
As I know, "continue" will jump back to the top of the loop. But in my case it's not jumping back, continue don't like me :(
for cases in files:
if ('python' in cases.split()):
execute_python_scripts(cases.split())
elif run_test_case(cases.split()):
continue
else:
logger("I am here")
break
In my case run_test_case() gives 1, 2, 3, 4 etc... But it always performs first(1) and jump to the else part. So I am getting the "I am here" message. It should not work like this. As I am using "continue", it should jump to the for loop.
Following is the run_test_case():
def run_test_case(job):
for x in job:
num_of_cases = num_of_cases - 1
test_type = x.split('/')
logger(log_file,"Currently "+ x +"hai!!")
if test_type[0] == 'volume':
backdoor = test_type[1].split("_")
if backdoor[0] == 'backdoor':
return get_all_nas_logs()
else:
if perform_volume_operations(x,num_of_cases) == False:
return False
else:
logger(log_file,"wrong ha!!")
Why is it always going to the else part, without jumping back to the for loop? Thanks in advance.
Here elif run_test_case(cases.split()): you are calling the run_test_case method, that will run your code to evaluate the result for the elif condition.
It only enters the block delimited by elif (in your case, continue), if the result of that method evaluates to True, otherwise it will jump to the else clause.
The problem is probably in your run_test_case code, that is never returning True, and so you'll never get the behavior that you're expecting.
It's hard to say without knowing exactly what you want to accomplish, but I'd say that you're missing a return True in the end of that code, meaning, if everything executes correctly right until the end, you want it to return True... but I'm only guessing here, you need to think about what that method is supposed to do.
In python an if or elif clause is evaluated for not only the True and False constants, but more generally for True-like and False-like values. None, for instance, is a false-like value, a non-empty string is a true-like value, etc.
Check this from the documentation on values that are considered true or false:
http://docs.python.org/library/stdtypes.html
For my software major work I have to create a program. In summary, the high scores list needs to be sorted before it can be written to file. To do this, I am using a bubble sort and I can't use the inbuilt sort function. The text file that the data is being read from is stored in a nested list. The text file looks like this:
NameOne
10
NameTwo
15
NameThree
9
This is the bubble sort code I have but does not work:
b_not_sorted = True
while b_not_sorted:
counter = 0
b_not_sorted = False
for counter in range(len(highest_scores) - 1):
if highest_scores[counter] < highest_scores[counter + 1]:
b_not_sorted = True
highest_scores[counter], highest_scores[counter+1] = highest_scores[counter+1], highest_scores[counter]
counter = counter + 1
I need the scores to be sorted from highest to lowest. Any help would be greatly appreciated and you will be credited appropriately in my program credits :). Thanks.
Here's a hint:
Check how many times your outer while loop is running. It should be running more than once, correct? What will always happen that causes the loop to exit, no matter what?
Try going through the code line by line and seeing what happens at every point.
The statement b_not_sorted = False at the end of the outer loop results in the outer loop exiting after executing only once. You need to move that statement to another part of your code. Try changing the name of b_not_sorted to I_still_need_to_go_through_the_list in your head:
Obviously in the first line:
while I_still_need_to_go_through_the_list:
it should be True, since you haven't gone over the list at all. You don't know if it's in order or not.
and after the line:
if highest_scores[counter] < highest_scores[counter + 1]:
Of course then we still need to make another pass, since we just made a change to the list and need to make sure no further changes are needed.
But what if no changes are made? I_still_need_to_go_through_the_list should be False then. Hmmm. If we put I_still_need_to_go_through_the_list = False right before the for loop, then it will be False unless we make changes to the list, which is exactly what we want.
You're doing b_not_sorted = False right after the first iteration, but it shouldn't be there! The algorithm just stops before it finishes the sorting.
You should instead do b_not_sorted = True only if highest_scores[counter] < highest_scores[counter + 1]
Also, the swapping code can look much nicer in Python. Instead of using temp_var just do this:
highest_scores[counter], highest_scores[counter+1] = highest_scores[counter+1], highest_scores[counter]
Python style guide suggests that you shoudn't write == True or == False in if statements. Do it like this:
while b_not_sorted: