这是编码chucknorris游戏的一部分,当我们想要开始一个字符串,然后将其转换为“一元”时,一个只有0和空格的代码。 这是我的代码,我的问题是没有任何东西可以解决我的问题。 例如: CC => 10000111000011:
0 0 (one 1)
00 0000 (four 0)
0 000 (three 1)
00 0000 (four 0)
0 00 (two 1)
CC给出:0 0 00 0000 0 000 00 0000 0 00
import sys
import math
# Auto-generated code below aims at helping you parse
# the standard input according to the problem statement.*
message = input()
# message to binary (01001)
bimsg = str([ bin(ord(ch))[2:].zfill(8) for ch in message ])[2:-2]
# function
to_chuck = ''
for n in bimsg:
index = bimsg.index(n)
if index >= 1 and bimsg[index] == bimsg[index-1]:
to_chuck+='0'
else:
if n == 1:
to_chuck+='0 0'
elif n == 0:
to_chuck+='00 0'
print(to_chuck)
答案 0 :(得分:0)
您的代码中有4个错误。
将输入字符串转换为二进制文件的方式不正确。您将每个字符填充为8位而不是7位,并且由于您在列表上调用str
,因此具有多个字符的字符串将在字符之间显示逗号。正确的转变是
bimsg = ''.join(format(ord(x), 'b').zfill(7) for x in message)
index = bimsg.index(n)
将始终为您提供输入中n
的第一次出现的索引。如果您的输入为1010
,则bimsg.index('1')
将始终返回0,bimsg.index('0')
将始终返回1.这不是您想要的。
要获得正确的索引,请使用enumerate
函数:
to_chuck = ''
for index, n in enumerate(bimsg):
if index >= 1 and bimsg[index] == bimsg[index-1]:
to_chuck+='0'
else:
if n == 1:
to_chuck+='0 0'
elif n == 0:
to_chuck+='00 0'
由于bimsg
是一个字符串,n
也是一个字符串。当您执行if n == 1
或if n == 0
时,您需要将字符串与数字进行比较 - 这将始终评估为False
。您必须将n
与字符串进行比较:
to_chuck = ''
for index, n in enumerate(bimsg): # use enumerate here
if index >= 1 and bimsg[index] == bimsg[index-1]:
to_chuck+='0'
else:
if n == '1':
to_chuck+='0 0'
elif n == '0':
to_chuck+='00 0'
您的代码不会在这里的0和0之间放置任何空格:
if n == '1': # changed 1 to '1' here
to_chuck+='0 0'
elif n == '0': # changed 0 to '0' here
to_chuck+='00 0'
你添加的零只是在to_chuck
的末尾与零一起融合,给你错误的输出。要解决此问题,只需添加一个空格:
to_chuck = ''
for index, n in enumerate(bimsg):
if index >= 1 and bimsg[index] == bimsg[index-1]:
to_chuck+='0'
else:
if n == '1':
to_chuck+=' 0 0' # added leading space here
elif n == '0':
to_chuck+=' 00 0' # added leading space here
to_chuck = to_chuck[1:] # get rid of the leading space
现在我们得到正确的输出:
print(to_chuck)
# 0 0 00 0000 0 000 00 0000 0 00
答案 1 :(得分:-1)
def firstBlock(x):
if x == "1":
return "0"
return "00"
def getBlock(x, counter):
return firstBlock(x) + " " + ("0" * counter)
message = input()
result = ""
binaryString = ""
for x in message:
binaryChar = format(ord(x), 'b')
paddedChar = binaryChar.zfill(7)
binaryString += paddedChar
counter = 1
currentChar = binaryString[0]
for x in binaryString[1:]:
if x == currentChar:
counter += 1
continue
result += getBlock(currentChar, counter) + " "
counter = 1
currentChar = x
result += getBlock(currentChar, counter)
print(result)