How to change a global variable from within a for if...? - python

My program tries to guess if an input number or letter is in a specific string. For that I have this simplified piece of code:
obtained = False
for i in range(6+len(chosen_set)):
try_let = input("Input something")
for index, letnum in enumerate(chosen_set):
if letnum == try_let:
obtained = True
else:
obtained = False
if obtained:
# do something
else:
# do something else
Say I input the letter "R" and the string I'm testing is XXXRXRX. When the inner for loop goes through its 4th iteration, the variable obtained will be True, and the same will happen for the 6th iteration, but not for the last one, which means the final value of obtained will be False. How should I change my code so that obtained will be True as long as it finds a coincidence regardless of when it finds it? Note that I can't use break in the for loop as soon as it finds a coincidence because the string could have more than one coincidence.

Maybe that?
for i in range(6+len(chosen_set)):
try_let = input("Input something")
obtained = False
for index, letnum in enumerate(chosen_set):
if letnum == try_let:
obtained = True
if obtained:
# do something
else:
# do something else

If you can't use a break, then change the logic of using an explicit True/False boolean as the primary decision factor and make use of a count as well.
For example:
count=0
if letnum == try_let:
count+=1
if count > 0:
obtained = True
else:
obtained = False

Related

Is there a concise way to program these two conditions?

exactSearch is a boolean variable. True means looking for an exact match with ==, False means looking for a like match with 'in'.
The resulting operations of appending to a DataFrame or continuing are the same regardless of the value of exactSearch, just that the operator will change depending on exactSearch.
The following code does indeed work, but I'm curious if there's a better way to program these conditions concisely.
if exactSearch:
if payerName == payer: # Look for exact match
result.loc[len(result)] = [provider,payer] + status.split(" ") # If located, add to results
else:
continue
else:
if payerName in payer: # Look for like match
result.loc[len(result)] = [provider,payer] + status.split(" ") # If located, add to results
else:
continue
How aboout:
match = (payerName == payer) if exactSearch else (payerName in payer)
if match:
result.loc[len(result)] = [provider,payer] + status.split(" ") # If located, add to results
else:
continue
Would this work?
if (payerName == payer) or (payerName in payer):
result.loc[len(result)] = [provider,payer] + status.split(" ")
else:
continue

I am creating a function that returns a tuple showing a boolean

I have to create a program that shows True or False if the elements from a list are palindromes or not.
I already has created the first part
def es_palindromo(texto):
rta = ""
for i in range(len(texto)):
rta += texto[i]
if (rta == texto):
print(True)
elif (rta != texto):
print(False)
return rta
es_palindromo("bob")
Now, I am trying to create a new function that shows me the amount of palindromes words and the ones that are not. Should be on a tuple and give something like this :(1, 2[True, False, True]) and the list would be
list = ["oso","hola","bob"]
if your texto is coming in form of a list, you can access the items outrightly. Try this
def es_palindromo(texto):
ans= [True if x ==x[::-1] else False for x in texto]
count = [ans.count(i) for i in set(ans) ]
print(count)
return (count,ans)
First of all in your code there is an indentation problem, also the output you are expecting is not valid in python. However, the below code will return a tuple with first element as number of palindrome strings and second element as a list stating if the given strings in the input list are palindrome or not.
list1 = ["oso","hola","bob"] #list variable
def es_palindromo(texto):
if texto == texto[::-1]:
return True
else:
return False
def return_tuple(input_list):
count = 0
ans = []
for i in list1:
if es_palindromo(i):
count+=1
ans.append(return_tuple(i))
return (count,ans)
return_tuple(list1)

Python: Verify Credit Card digits

I need to implement a function called “verify” that takes a single parameter
called “number” and then checks the following rules:
The first digit must be a 4.
The fourth digit must be one greater than the fifth digit; keep in mind that these
are separated by a dash since the format is ####-####-####.
The sum of all digits must be evenly divisible by 4.
If you treat the first two digits as a two-digit number, and the seventh and eighth
digits as a two-digit number, their sum must be 100
This is what I have come up with so far:
def verify(number): # do not change this line!
list_number=list(number.split(''))
Check=false
# write your code here so that it verifies the card number
if list_number[0]==4:
if list_number[3]==list_number[5]+1:
if list_number.sum() % 4==0:
if int(str(list_number[0])+str(list_number[1]))+int(str(list_number[7])+str(list_number[8])) ==100:
Check = true
else:
check = false
input = "4094-3460-2754" # change this as you test your function
output = verify(input) # invoke the method using a test input
print(output) # prints the output
this is what you need. each if statement in the function corresponds to condition that you have specified.
def verify(number): # do not change this line!
number_string = number.replace("-", "")
list_number = [int(n) for n in number_string]
if not list_number[0] == 4:
return False
if not list_number[3] - list_number[4] == 1:
return False
if not sum(list_number) % 4 == 0:
return False
if not int(number_string[0:2]) + int(number_string[6:8]) == 100:
return False
return True
input = "4094-3460-2754"
output = verify(input)
print(output)
# True
It seems like there are a few fundamental errors in your code. I will list them down for you:
Boolean values start with a capital
there are no indentations after your if and else statements
Your output will always print none as your function does not return anything.
def verify(number):
list_number=list(number)
if list_number[0]==4 and list_number[3]==list_number[5]+1 and list_number.sum() % 4==0 and int(str(list_number[0])+str(list_number[1]))+int(str(list_number[7])+str(list_number[8])) ==100:
return True
else:
return False
input = "4094-3460-2754"
output = verify(input)
print(output)```
Your code is way to poorly written
list_number = "4094-3460-2754"
list_number = list_number.replace('-','')
if list_number[0]=='4' and int(list_number[3])==int(list_number[5])+1 and list_number.sum() % 4==0 and int(list_number[0])+int(list_number[1])==int(list_number[7])+int(list_number[8]):
check = True
else:
check = False

How can I figure out what this Python code does?

I am learning Python and I'd like to know what this code does.
# This code is supposed to get an input of a word and not a sentence
def do_something(word):
index = len(word)/2
len_word = len(word)
if index == 0:
return True
elif len_word % 2 == 0:
return word[0:index] == word[-1:index-1:-1]
else:
return word[0:index+1] == word[-1:index-1:-1]
Now I tried to check but the variable index doesn't work to me maybe because I am using 3.7.
But I checked it without using the variable and just counting it and I think this code suppose to check if the first half is equal to the second half backwards or something like that.
And I am also not sure why there is this line:
if index == 0:
return True
Would someone explain it?
This code defines a function. The function does not run. It is apparently intended to check if it's a palindrome
If you ran the function it would return a boolean value of True or False based on the word.
index is defined as len(word)/2 (or len(word)//2 as mentioned in the comments) so it is apparently intended to catch the case where word is something like ""
The next elif checks if word is of even length. The code to check for a palindrome needs to be adjusted based on this. Hence the slight difference in return codes between the elif and else
return word[0:index] == word[-1:index-1:-1] (from the elif as an example) gets the first half of the word as word[0:index] and the second half in reverse by word[-1:index-1:-1] to check if they are identical. It reverses the second half of the word with that -1 at the end of the slicing.
if index == 0:
return True
Checks if the input is only 1 word. Like 1//2 == 0 but 2 or more is not equals to 0.
elif len_word % 2 == 0:
return word[0:index] == word[-1:index-1:-1] # will return True or False
If the length is even(2,4,6...) then compare characters of the string from 0 to index with characters of the string from the end till index-1 and if matchesreturn TrueotherwiseFalse`
return word[0:index+1] == word[-1:index-1:-1]
If the length is odd(1,3,5...) then compare characters of the string from 0 to index+1 with characters of the string from the end till index-1 and if matchesreturn TrueotherwiseFalse`.
Note: there is a mistake in the code index = len(word)/2 should have been with double slash index = len(word)//2. One slash is float dividing and will return 0.5 so the first case will never be true(index == 0).

Python, checking if string consists only of 1's and 0's

I'm trying to write a function that checks if given string is binary or not. I'm using a while loop to browse characters in string one by one. If all of them are 0's or 1's it's going to return True, if anything is not - break the loop and return False.
I've just written this tiny part of code, but it doesn't run. Why?
def fnIsBin(string):
count = 0
while count < len(string):
character = string[count]
if character == '0' or character == '1':
print (count, character[count], "OK")
count = count+1
continue
else:
print (count, character[count], "ERROR")
return False
break
EDIT:
I also tried using 'set' to elude iterating with loop, but i don't quite get how does "set(string)" work. I got error that i cant consider it as a list. So how can I compare elements to 0 & 1?
def fnIsBin(string):
charactersList = set(string)
if len(charactersList) > 2:
return False
else:
if (charactersList[0] == '0' or charactersList[0] == '1') and (charactersList[1] == '0' or charactersList[1] == '1'): #there i made error, how to deal with it?
return True
else:
return False
Your function fails because you never actually return True. That means if the string is actually binary, you'd return None which Python would consider as False in any boolean check.
Simply add return True at the end of the function.
As #Barmar mentioned in the comment, you also print the value of character[count] instead of string[count] which would cause IndexError.
An easier way to check if the string is binary would be:
test_string = '010101'
all_binary = all(c in '01' for c in test_string)
There are many ways to do this:
Set:
fnInBin(s):
return set(s).issubset({'0', '1'}) and bool(s)
Regular expression:
fnInBin(s):
return bool(re.fullmatch('[01]+', s))
Integer conversion:
fnIsBin(s):
try:
int(s, 2)
return True
except ValueError:
return False
The last one will strip whitespace from the input, though.
fnIsBin('\n 1 ') == True
You can use the int object and give it a base. It will fail if the object passed doesn't consist of a binary representation. Recall that a binary string is base 2.
def fnIsBin(string):
try:
binary_repr = int(string, 2)
except ValueError as err
print("error: {0}".format(err))
return False
return True
You're printing OK for each character that's 0 or 1, even though there may be a later character that isn't. You need to wait until the end of the loop to know that it's really OK.
def fnIsBin(string):
for character in string:
if character != '0' and character != '1':
print (character, "ERROR")
return False
print "OK"
return True
There's no need for break after return False -- returning from the function automatically breaks out of the loop.
Here's one of the ways you could rewrite your function and maintain a similar structure (looping through each character):
def fnIsBin(string):
for character in string:
if not character in '01':
return False
return True
You could also do it using regular expressions:
import re
def fnIsBin(string):
return re.match(r'^[10]+$', '01') is not None
My two cents (A short way):
test_string = '010101'
result = set(test_string) <= {'0','1'}
print(result)
Using set(test_string) converts the string into list of characters,
{0,1,0,1,0,1}
Using <= operator checks whether the set on the left-side is a proper subset of the set on the right-hand side
Ultimately checking whether there are only 0 and 1 are in the string or not in an in-direct and mathematical way.
Adding a XOR solution to the mix:
bin_string = '010101'
for j in range(0, len(bin_string)):
if int(bin_string[j]) != 0 ^ int(bin_string[j]) != 1:
break

Categories

Resources