How to interpret boolean operation on integers?
Let's say we want to perform a "bitwise and" operation on two integers, say, 5 and 7. It makes sense that the result should be 5 because a union of 111 and 101 should return 101 and this is of course what I get in Python:
5 & 7
Out: 5
I though that boolean and
should not apply to non-boolean values, but to my surprise:
5 and 7
Out: 7
1.5 and 1.7
Out: 1.7
[1,2,3] and [4,5]
Out: [4, 5]
Now I'm confused. This works for some reason, but what does it mean? How are these values produced?
1 answer
-
answered 2020-11-25 06:43
gilch
Python's
and
returns its left operand if it evaluates false, its right operand otherwise.Python's
or
returns its left operand if it evaluates true, its right operand otherwise.Note that with boolean operands, this produces the proper truth table. They're also guaranteed to not evaluate the right operand at all when they pick the left one.
Objects in Python are true unless it's a "zero", including collections of zero length.
See also questions close to this topic
-
Error non-linear-regression python curve-fit
Hello guys i want to make non-linear regression in python with curve fit this is my code:
#fit a fourth degree polynomial to the economic data from numpy import arange from scipy.optimize import curve_fit from matplotlib import pyplot import math x = [17.47,20.71,21.08,18.08,17.12,14.16,14.06,12.44,11.86,11.19,10.65] y = [5,35,65,95,125,155,185,215,245,275,305] # define the true objective function def objective(x, a, b, c, d, e): return ((a)-((b)*(x/3-5)))+((c)*(x/305)**2)-((d)*(math.log(305))-math.log(x))+((e)*(math.log(305)-(math.log(x))**2)) popt, _ = curve_fit(objective, x, y) # summarize the parameter values a, b, c, d, e = popt # plot input vs output pyplot.scatter(x, y) # define a sequence of inputs between the smallest and largest known inputs x_line = arange(min(x), max(x), 1) # calculate the output for the range y_line = objective(x_line, a, b, c, d, e) # create a line plot for the mapping function pyplot.plot(x_line, y_line, '--', color='red') pyplot.show()
this is my error :
Traceback (most recent call last): File "C:\Users\Fahmi\PycharmProjects\pythonProject\main.py", line 16, in popt, _ = curve_fit(objective, x, y) File "C:\Users\Fahmi\PycharmProjects\pythonProject\venv\lib\site-packages\scipy\optimize\minpack.py", line 784, in curve_fit res = leastsq(func, p0, Dfun=jac, full_output=1, **kwargs) File "C:\Users\Fahmi\PycharmProjects\pythonProject\venv\lib\site-packages\scipy\optimize\minpack.py", line 410, in leastsq shape, dtype = _check_func('leastsq', 'func', func, x0, args, n) File "C:\Users\Fahmi\PycharmProjects\pythonProject\venv\lib\site-packages\scipy\optimize\minpack.py", line 24, in _check_func res = atleast_1d(thefunc(((x0[:numinputs],) + args))) File "C:\Users\Fahmi\PycharmProjects\pythonProject\venv\lib\site-packages\scipy\optimize\minpack.py", line 484, in func_wrapped return func(xdata, params) - ydata File "C:\Users\Fahmi\PycharmProjects\pythonProject\main.py", line 13, in objective return ((a)-((b)(x/3-5)))+((c)(x/305)**2)-((d)(math.log(305))-math.log(x))+((e)(math.log(305)-(math.log(x))**2)) TypeError: only size-1 arrays can be converted to Python scalars
thanks before
-
beautifulsoup (webscraping) not updating variables when HTML text has changed
I am new to python and I cant understand why this isn't working, but I've narrowed down the issue to one line of code.
The purpose of this bot is to scrape HTML from a website (using beautiful and post to discord when the text changes. I use FC2 and FR2 (flightcategory2 and flightrestrictions2) as memory variables for the code to check against every time it runs. If they're the same, the code waits for _ minutes and checks again, if they're different it posts it.
However when running this code, the variables "flightCategory" "flightRestrictions" change the first time the code runs, but for some reason stop changing when the HTML text on the website changes. the line in question is this if loop.
if 1==1: # using 1==1 so this loop constantly runs for testing, otherwise I have it set for a time flightCategory, flightRestrictions = und.getInfo()
When debugging mode, the code IS run, but the variables in the code don't update, and I am confused as to why they would update the first time the code is run, but not sequential times. This line is critical to the operation of my code.
Here's an abbreviated version of the code to make it easier to read. I'd appreciate any help.
FC2 = 0 FR2 = 0 flightCategory = "" flightRestrictions = "" class UND: def __init__(self): page = requests.get("http://sof.aero.und.edu") self.soup = BeautifulSoup(page.content, "html.parser") def getFlightCategory(self): # Takes the appropriate html text and sets it to a variable flightCategoryClass = self.soup.find(class_="auto-style1b") return flightCategoryClass.get_text() def getRestrictions(self): # Takes the appropriate html text and sets it to a variable flightRestrictionsClass = self.soup.find(class_="auto-style4") return flightRestrictionsClass.get_text() def getInfo(self): return self.getFlightCategory(), self.getRestrictions() und = UND() while 1 == 1: if 1==1: #using 1==1 so this loop constantly runs for testing, otherwise I have it set for a time flightCategory, flightRestrictions = und.getInfo() (scrape the html from the web) if flightCategory == FC2 and flightRestrictions == FR2: # if previous check is the same as this check then skip posting Do Something elif flightCategory != FC2 or flightRestrictions != FR2: # if any variable has changed since the last time FC2 = flightCategory # set the comparison variable to equal the variable FR2 = flightRestrictions if flightRestrictions == "Manager on Duty:": # if this is seen only output category Do Something elif flightRestrictions != "Manager on Duty:": Do Something else: print("Outside Time") time.sleep(5) # Wait _ seconds. This would be set for 30 min but for testing it is 5 seconds. O
-
Need to reload vosk model for every transcription?
The vosk model that I'm using is vosk-model-en-us-aspire-0.2 (1.4GB). Every time need quite amount of time to load the vosk model. Is it necessary to recreate the vosk object for every time? It take many time to load the model, if we only load model once. It can save up at least half of the time.
-
the variable is set to false inside my method, once the method runs it should change to True. But it does not
def checkPassword (password): upper = False lower = False number = False special = False for i in range (len(password)): if ((ord(password[i]) >= 65) and (ord(password[i]) <= 90)): upper = True elif ((ord(password[i]) >= 97) and (ord(password[i]) <= 122)): lower = True elif ((ord(password[i]) >= 0) and (ord(password[i]) <= 9)): number = True elif ((ord(password[i]) >= 0) and (ord(password[i]) <= 9)) : special = True if ((upper == True) and (lower == True) and (number == True) and (special == True)): print ("Your password is strong") else: print ("Your password is not strong. Make sure to make it a mix between upper and lower case letters, number, and special characters.") def main(): password = input("Enter a password: ") checkPassword (password)
Input:
running99*FAST
Output:
Your password is not strong. Make sure to make it a mix between upper and lower case letters, number, and special characters.
Problem: This password should come back as a strong password but it does not. I honestly don't know what I did wrong.
P.S. I am using the ASCII table to identify whether the letters are lowercase, uppercase, or numbers, and special characters.
-
Why dosen't my boolean change its value to true after meeting the conditions?
I'm trying to make a simple customer registration system and a certain textfield has a label beside it that changes whenever it validates a good birthday format(mm/dd/yyyy) I did a switch statement to invalidate if they got the format wrong, but the boolean value I have set remains to be false even though the conditions are met for it to be true
int month = 0, day, year; Boolean vmonth = false, vday = false, vyear = false; for(int x = 1; x<=txt_customerbday.getText().length(); x++){ if(txt_customerbday.getText().length() != 10){ lbl_bdaycheck.setForeground(Color.red); lbl_bdaycheck.setText("Bad Format"); } else if(10 == txt_customerbday.getText().length() && vyear == true && vmonth == true && vday == true){ lbl_bdaycheck.setForeground(Color.green); lbl_bdaycheck.setText("Good Format"); }
Above is the code that will change the label if the conditions are met
if(txt_customerbday.getText().length() == 2){ month = Integer.parseInt(txt_customerbday.getText().substring(0)); System.out.print(month); if(month > 12){ vmonth = false; }else{ vmonth = true; System.out.print(vmonth); } }
The code above is the validation of the month (ignore the print statement I just did that to check their values)
if(txt_customerbday.getText().length() == 5){ day = Integer.parseInt(txt_customerbday.getText().substring(3,5)); System.out.print(day); System.out.print(vday); switch(month){ case 1: if(day > 31 || day <= 0){ vday = false; }else{ vday = true; } break; case 2: if(day > 28 || day <= 0){ vday = false; }else{ vday = true; } break; case 3: if(day > 31 || day <= 0){ vday = false; }else{ vday = true; } break; case 4: if(day > 30 || day <= 0){ vday = false; }else{ vday = true; } break; case 5: if(day > 31 || day <= 0){ vday = false; }else{ vday = true; } break; case 6: if(day > 30 || day <= 0){ vday = false; }else{ vday = true; } break; case 7: if(day > 31 || day <= 0){ vday = false; }else{ vday = true; } break; case 8: if(day > 31 || day <= 0){ vday = false; System.out.print(vday); }else{ vday = true; System.out.print(vday); } break; case 9: if(day > 30 || day <= 0){ vday = false; }else{ vday = true; } break; case 10: if(day > 31 || day <= 0){ vday = false; }else{ vday = true; } break; case 11: if(day > 30 || day <= 0){ vday = false; }else{ vday = true; } break; case 12: if(day > 31 || day <= 0){ vday = false; }else{ vday = true; } break; default: vday = false; break; } System.out.print(vday); }
The code above is the code for the day validation this is the one where I think I have the problem
if(txt_customerbday.getText().length() == 10){ year = Integer.parseInt(txt_customerbday.getText().substring(6,10)); System.out.print(year); vyear = true; }
The last one is unfinished but this is for the year validation
-
Determine if values are different
Let's say I have 4 variables
bool value1 = false; bool value2 = false; bool value3 = true; bool value4 = false;
and they all don't have the same value (all are true
||
all are false)I have found 2 approaches, anyway none of them looks easy to understand.
bool areDifferent = !(value1 == value2 == value3 == value4);
and
bool areDifferent = new[] { value1, value2, value3, value4 }.Distinct().Count() > 1;
Question: Is there a other approach, which is better in terms of readability / understandability?