how to make 1111 into 1 in python

140 Views Asked by At

i want to make function to make from 1111 into 1 and 0000 into 0.

for the example:

Input:
['1111', '1111', '0000', '1111', '1111', '0000', '1111', '0000', '0000', '1111', '0000', '0000', '0000', '0000', '0000', '0000', '0000', '1111', '0000', '0000', '1111', '1111', '0000', '0000', '0000', '0000', '1111', '0000', '1111', '1111', '0000', '0000']

Desired output:
11011010010000000100110000101100

But i don't know how to make it or the algorithm. Can you help me?

My attempt so far:

def bagiskalar(biner):
    print(biner)
    biner = str(biner)
    n = 4
    hasil = []
    potong = [biner[i:i+n] for i in range(0, len(biner), n)]
    for a in potong:
        hasil = potong.append(a)
    
    return hasil
4

There are 4 best solutions below

0
Abhinav Mathur On

You can easily use list comprehension and the join() method:

lst = ['1111', '1111', '0000', '1111', '1111', '0000', '1111', '0000', '0000', '1111', '0000', '0000', '0000', '0000', '0000', '0000', '0000', '1111', '0000', '0000', '1111', '1111', '0000', '0000', '0000', '0000', '1111', '0000', '1111', '1111', '0000', '0000']
s = ''.join(['1' if x == '1111' else '0' for x in lst ])
print(s)
# prints 11011010010000000100110000101100
0
Yaman Jain On

Another approach is to have pre-populated dictionary.

mapper = {'1111': '1', '0000': '0'}  # can be extended for other maps if needed

input_data = ['1111', '1111', '0000', '1111', '1111', '0000', '1111', '0000', '0000', '1111', '0000', '0000', '0000', '0000', '0000', '0000', '0000', '1111', '0000', '0000', '1111', '1111', '0000', '0000', '0000', '0000', '1111', '0000', '1111', '1111', '0000', '0000']

output_data = ''.join([mapper.get(item) for item in input_data]) 
0
Exu On

This looks like school assignment, so I'll make simple example. I assume, you really want to append result only from exact '0000' and '1111', and ignore other strings.

def bagiskalar(biner):
    result = ""
    for b in biner:
        if b == '0000' or b == '1111':
            result = result + b[0]
    return result

It just goes through your list of strings, checks each one of the that is it either '0000' or '1111'. And if it is, then add the first character ('0' or '1') to the result string.

0
0x0fba On

Assuming that your input is well-formatted, i.e. you don't expect other values than 1111 or 0000, you can optimize by taking only the first character.

output = "".join([x[0] for x in input])