Python Forum
Could somebody help a beginner? :)
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Could somebody help a beginner? :)
#1
HI, I am a real beginner, so please, be gentle:)
I wrote a short programm:

bits_string = "01010102"
bits = ["0", "1"]
bits_list = []

for i in bits_string:
    bits_list.append(i)

result = all(i in bits_list for i in bits)
print(result)
And the outcome is:
Output:
['0', '1', '0', '1', '0', '1', '0', '2'] True
I mean, why is it "TRUE"? "2" is not present in list "bits".

Thanks in advance Smile
buran write Jan-29-2021, 11:36 AM:
Please, use proper tags when post code, traceback, output, etc. This time I have added tags for you.
See BBcode help for more info.
Reply
#2
because both '0' and '1' are present in bits_list
Your expected output is consistent with all(i in bits for i in bits_list) - this will be False, because of 2 not present in bits.

That said there is no need to convert the string to list you can iterate over str just fine.
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#3
Your logic is backward. If you want verify that all the characters from bits_string are in bits, the test should be:
result = all(i in bits for i in bits_list)
As buran mentioned there is no need to convert bits_string to bits_list, or to have a list at all. Iterators and "in" for str work very similar to how they work for list. You could write the code like this:
def valid_binary_string(binary_string):
    return all(bit in "01" for bit in binary_string)

print(valid_binary_string("01010100"))
print(valid_binary_string("01010102"))
There are other ways to solve this problem that may be more efficient. For example, you could use sets to reduce the number of comparisons.
def valid_binary_string(binary_string):
    return all(i in '01' for i in set(binary_string))

print(valid_binary_string("01010100"))
print(valid_binary_string("01010102"))
If you use sets you can use set operations. For example, set(binary_string) - set('01') will return an empty set for any vailid binary string.
binary_digits = set('01')

def valid_binary_string(binary_string):
    return not set(binary_string)-binary_digits

print(valid_binary_string("01010100"))
print(valid_binary_string("01010102"))
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020