Python Forum
Could somebody help a beginner? :)
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Could somebody help a beginner? :)
#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


Messages In This Thread
Could somebody help a beginner? :) - by bigmis72 - Jan-29-2021, 11:32 AM
RE: Could somebody help a beginner? :) - by buran - Jan-29-2021, 11:40 AM
RE: Could somebody help a beginner? :) - by deanhystad - Jan-29-2021, 08:26 PM

Forum Jump:

User Panel Messages

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