Python Forum
Could somebody help a beginner? :) - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Could somebody help a beginner? :) (/thread-32232.html)



Could somebody help a beginner? :) - bigmis72 - Jan-29-2021

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


RE: Could somebody help a beginner? :) - buran - Jan-29-2021

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.


RE: Could somebody help a beginner? :) - deanhystad - Jan-29-2021

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"))