Checking if List of Strings exists in a String - python-3.x

The following code executes sucessfully
excluded_strings = ['excluded', 'decrypted', 'extracted_pdf_text.txt']
def excl_file_with_str(rec_file_name):
string_match = [True for excluded_string in excluded_strings if excluded_string in rec_file_name]
if True in string_match:
return None
else:
return rec_file_name
However, the below not. Throwing error UnboundLocalError: local variable 'string_match' referenced before assignment
excluded_strings = ['excluded', 'decrypted', 'extracted_pdf_text.txt']
def excl_file_with_str(rec_file_name):
for excluded_string in excluded_strings:
if excluded_string in rec_file_name:
string_match = True
if True in string_match:
return None
else:
return rec_file_name

You can give a try to below untested code.
excluded_strings = ['excluded', 'decrypted', 'extracted_pdf_text.txt']
def excl_file_with_str(rec_file_name):
string_match = False
for excluded_string in excluded_strings:
if excluded_string in rec_file_name:
string_match = True
break
if string_match:
return None
else:
return rec_file_name

Related

my defined python class method does not work

class QuizBrain:
def __init__(self,question_list):
self.question_list = question_list
self.question_number = 0
self.score = 0
def still_has_questions(self):
if len(self.question_list) == self.question_number:
return False
return True
def check_the_answer(self,user,answer):
if user.lower() == answer.lower():
self.score += 1
print("Correct answer ...")
else:
print("Thats wrong")
print(f"Score: {self.score}/{self.question_number}")
print("n/")
def next_question(self):
question = self.question_list[self.question_number].text
answer = self.question_list[self.question_number].answer
self.question_number += 1
user = input(f"Q.{self.question_number}: {question} (True/False) --> ")
check_the_answer(user,answer)
NameError: name 'check_the_answer' is not defined
I get this error when ı try the run the program ıdk why ı defined that
I just started to learn if you can explain with details it would be nice

How to create a perfect number function using lists

My perfect number function is not working as intended :(. It prints false even though it should print true :(
def perfect_check(number):
z = []
for i in range(1, number):
if number % i == 0:
z.append(i)
if sum(z) == number:
return True
else:
return False
print(perfect_check(6))
def perfect_check(number):
z = []
for i in range(1, number):
if number % i == 0:
z.append(i)
if sum(z) == number:
return True
else:
return False
print(perfect_check(6))
You have put the if-else statement inside your for loop. It should be outside the for loop. Then, your code will work correctly.

How to solve this hsl to rgb vise versa color conversion error in python?

yesterday I tried to made a simple library to convert HSL to RGB color space and vise-versa program in python.
but when I tried to run everything seems normal but sometimes on some input they miss by the one digit difference.
here is my code and result.
import re
# helper hsl functions
hslString=r'^hsl\((\d+)\,(\d+)%\,(\d+)%\)$'
hslaString=r'^hsla\((\d+)\,(\d+)%\,(\d+)%\,(0?\.?\d+)\)$'
wrongHslaString=r'^hsl\((\d+)\,(\d+)%\,(\d+)%\,(0?\.?\d+)\)$'
wrongHslString=r'^hsla\((\d+)\,(\d+)%\,(\d+)%\)$'
def hasall(obj,*args):
return False if False in [True if i in obj else False for i in args] else True
def ishsl(*hsl):
rl=len(hsl)
if rl==1:
arg=hsl[0]
if isinstance(arg,dict):
a=hasall(arg,'h','s','l','a') or hasall(arg,'h','s','l')
return [*arg.values()] if a else False
elif isinstance(arg,str):
values=re.findall(hslaString,arg) or re.findall(hslString,arg) or re.findall(wrongHslaString,arg) or re.findall(wrongHslString,arg)
return [float(v) for v in values[0]] if values else False
elif isinstance(arg,(list,tuple)):
return [*arg] if len(arg) in [3,4] else False
elif rl in [3,4]:
return [*hsl]
return False
def typehsl(*hsl):
check=ishsl(*hsl)
if check:
return 'hsla' if len(check)==4 else 'hsl'
else:
return False
# helper rgb functions
rgbString=r'^rgb\(\s*?(\-?\d+)\s*?\,\s*?(\-?\d+)\s*?\,\s*?(\-?\d+)\s*?\)$'
rgbaString=r'^rgba\(\s*(\-?\d+)\s*\,\s*(\-?\d+)\s*\,\s*(\-?\d+)\s*\,(\-?0?\.?\d+)\)$'
wrongRgbaString=r'^rgba\(\s*(\-?\d+)\s*\,\s*(\-?\d+)\s*\,\s*(\-?\d+)\)$'
wrongRgbString=r'^rgb\(\s*(\-?\d+)\s*\,\s*(\-?\d+)\s*\,\s*(\-?\d+)\s*\,(\-?0?\.?\d+)\)$'
# sampleRgbString='rgb(150,150,252)'
# compiled=re.compile(rgbString).findall(sampleRgbString)
def hasall(obj,*args):
"""check if given object has all property name or not"""
value=False
for i in args:
if obj.get(i):
value=True
else:
value=False
return value
def getinorder(obj,*args):
all=hasall(obj,*args)
vals=[]
if all:
for i in args:
vals.append(obj.get(i))
return vals
def isrgb(*rgb):
rl=len(rgb)
if rl==1:
arg=rgb[0]
if isinstance(arg,dict):
a=hasall(arg,'r','g','b','a') or hasall(arg,'r','g','b')
values = getinorder(arg,'r','g','b','a') or getinorder(arg,'r','g','b')
return [int(v) for v in values] if a else False
elif isinstance(arg,str):
values=re.findall(rgbaString,arg) or re.findall(rgbString,arg) or re.findall(wrongRgbaString,arg) or re.findall(wrongRgbString,arg)
return [int(v) for v in values[0]] if values else False
elif isinstance(arg,(list,tuple)):
return [*arg] if len(arg) in [3,4] else False
elif rl in [3,4]:
return [*rgb]
return False
def typergb(*rgb):
check=isrgb(*rgb)
if check:
rl=len(check)
return 'rgba' if rl==4 else 'rgb' if rl==3 else False
def RGB2HSL(*rgb):
check=isrgb(*rgb)
if check:
h=s=l=0
tr=typergb(check)
A=float(check.pop()) if tr=='rgba' else False
check=[0 if v<0 else 255 if v>255 else v for v in check]
r,g,b=[int(v)/255 for v in check]
maxi,mini=max(r,g,b),min(r,g,b)
l=(maxi+mini)/2
if maxi==mini:
h=s=0
return [h,s,l,A] if tr=='rgba' else [h,s,l]
else:
s=(maxi-mini)/(1-abs(2*l-1))
if maxi==r:
h=((g-b)/(maxi-mini))%6
if maxi==g:
h=(b-r)/(maxi-mini)+2
if maxi==b:
h=(r-g)/(maxi-mini)+4
h=cr(h*60)
return [h,s,l,A] if tr=='rgba' else [h,s,l]
else:return False
def cr(n):
from math import ceil,floor
return floor(n) if (n-floor(n))<0.5 else ceil(n)
def HSL2RGB(*hsl):
check=ishsl(*hsl)
if check:
r=g=b=0
tl=typehsl(check)
A=float(check.pop()) if len(check)==4 else False
h,s,l=[v for v in check]
s,l=s if s<=1 else s/100,l if l<=1 else l/100
c=(1-abs((2*l)-1))*s
x=c*(1-abs((h/60)%2-1))
m=l-(c/2)
if h>=0 and h<60:
r,g,b=c,x,0
elif h>=60 and h<120:
r,g,b=x,c,0
elif h>=120 and h<180:
r,g,b=0,c,x
elif h>=180 and h<240:
r,g,b=0,x,c
elif h>=240 and h<300:
r,g,b=x,0,c
elif h>=300 and h<360:
r,g,b=c,0,x
R,G,B=(r+m)*255,(g+m)*255,(b+m)*255
R,G,B=[cr(v) for v in [R,G,B]]
return [R,G,B,A] if tl=='hsla' else [R,G,B]
print(HSL2RGB(RGB2HSL(6,50,90)))
I think the result should be [6,50,90] but it print [6,49,90]. Why? how can I solve this?

Why is it returning None instead of True or False?

this code is for checking if a word is a palindrome or not, and the decorator check if the word is a string
def check(func):
def string(w):
if w != str(w):
print('no')
else:
print('yes')
func(w)
return string
#check
def palindrome(w):
print(w)
inverse = ''
inverse = w[::-1]
if inverse == w:
print('1')
return True
else:
print('2')
return False
print(palindrome("test"))
After running it:
yes
test
2
None
At this point, everything should be ok, but I don't know why it is returning None instead of True or False.
Your check decorator ignores return value from decorated function. You need explicit return in wrapper function:
def check(func):
def string(w):
if w != str(w):
print('no')
else:
print('yes')
return func(w)
return string

Write a Python function squareprime(l)

Write a Python function squareprime(l) that takes a non-empty list of integers and returns True if the elements of l alternate between perfect squares and prime numbers, and returns False otherwise. Note that the alternating sequence of squares and primes may begin with a square or with a prime.
Here are some examples to show how your function should work.
>>> primesquare([4])
True
>>> primesquare([4,5,16,101,64])
True
>>> primesquare([5,16,101,36,27])
False
Function prime_checker checks if a number is prime or not.
Function is_square checks if a number is prefect_square or not.
If the number at index 0 is square, then the chain is like [square, prime, square...]
else the sequence goes like [prime, square, prime, square..]
If the input sequence is not either of the two, then it is not a valid sequence and it will return False.
import math
def prime_checker(num):
flag = True
if num == 2:
return True
elif num < 2:
return False
else:
for i in range(2, int(num/2)):
if num % i == 0:
flag = False
break
return flag
def is_square(integer):
if integer == 0:
return false
root = math.sqrt(integer)
if int(root + 0.5) ** 2 == integer:
return True
return False`
def primesquare(list_nums):
if len(list_nums) == 0:
return False
if len(list_nums) == 1:
if (is_square(list_nums[0]) or prime_checker(list_nums[0])):
return True
else:
return False
else:
flag = True
if is_square(list_nums[0]):
check_for = 'prime'
elif prime_checker(list_nums[0]):
check_for = 'square'
else:
return False
for i in range(1,len(list_nums)):
if (check_for == 'prime' and prime_checker(list_nums[i])):
check_for = 'square'
elif (check_for == 'square' and is_square(list_nums[i])):
check_for = 'prime'
else:
flag = False
break
if flag:
return True
else:
return False
Update:
As the element at the 0th index has already been checked, we are not concerned about that number anymore. Hence, if the 0th element is a prime number, then the sequence will be [prime, square, prime, square,...].
If it is a perfect square, then the sequence will be [square, prime, square, prime...].
If it is neither of the two, then it is not a valid sequence and hence, false is returned.
Now, if the first number was either of the two, and the length of the list is greater than 1, then we will iterate over the remaining elements and check if they are similar to what we expected, but changing the value of check_for variable.
If the value of check_for is prime and the value that we encountered is also prime, then we know that the next number of the sequence should be a square number for the sequence to be a valid sequence. The similar thing happens when a square number is encountered.
from math import sqrt
def square(n):
if(sqrt(n) % 1 == 0):
return True
else:
return False
def isprime(n):
for i in range(2,int(n**0.5)+1):
if n%i==0:
return False
return True
def primesquare(list_nums):
if len(list_nums) == 0:
return False
if len(list_nums) == 1:
if (square(list_nums[0]) or isprime(list_nums[0])):
return True
else:
return False
else:
flag = True
if square(list_nums[0]):
check_for = 'prime'
elif isprime(list_nums[0]):
check_for = 'square'
else:
return False
for i in range(1,len(list_nums)):
if (check_for == 'prime' and isprime(list_nums[i])):
check_for = 'square'
elif (check_for == 'square' and square(list_nums[i])):
check_for = 'prime'
else:
flag = False
break
if flag:
return True
else:
return False
from math import sqrt
def isprime(n):
for i in range(2,int(n**0.5)+1):
if n%i==0:
return False
return True
def primesquare(l):
flag=0
if len(l)==1:
n=l[0]
if(sqrt(n)%1==0):
return True
else:
for i in range(0,len(l)):
if(sqrt(l[i])%1==0):
if(i==0):
if(isprime(l[i+1])==True):
flag=1
else:
if(isprime(l[i-1])==True):
if(isprime[i+1]==True):
flag=1
else:
flag=0
else:
flag=0
if(flag==0):
return False
else:
return True
from math import sqrt
def square(n):
if(sqrt(n) % 1 == 0):
return True
else:
return False
def isprime(n):
if (n == 1):
return(False)
for i in range(2,int(n**0.5)+1):
if n%i==0:
return False
return True
def squareprime(l):
s=l[0]
if(isprime(s)):
for i in range(0,len(l),2):
if(isprime(l[i])==False):
return False
for i in range(1,len(l),2):
if(square(l[i])==False):
return False
return True
elif(square(s)):
for i in range(0,len(l),2):
if(square(l[i])==False):
return False
for i in range(1,len(l),2):
if(isprime(l[i])==False):
return False
return True
else:
return False

Resources