I need help with this challenge, I keep getting an error with this hacker rank challenge comes out right with jupyter notebook but not in hacker rank console.
Task Given a string, of length that is indexed from to, print its even-indexed and odd-indexed characters as space-separated strings on a single line (see the Sample below for more detail).
Note: is considered to be an even index.
Example
s = adbecf
Print abc def
Input Format
# Enter your code here. Read input from STDIN. Print output to STDOUT
t = input()
p = len(t)
for i in range(p):
s = t[i]
n = len(s)
even = []
odd = []
for j in range(n):
if j % 2 == 0:
even.append(s[j])
for j in range(n):
if j % 2 != 0:
odd.append(s[j])
first_join=''.join(even)
second_join = ''.join(odd)
print("{} {}".format(first_join,second_join)
CodePudding user response:
No need to use complex ways. here is a easy way to do it.
t = input()
p = len(t)
ans = "" # create empty string
for i in range(0,p,2):
ans = t[i] # Add even characters
ans = " " # Add space.
for j in range(1,p,2):
ans = t[j] # Add odd characters
print(ans)
Input: adbecf
Output: abc def
CodePudding user response:
You're iterating over s
, where s = t[i]
, which is incorrect.
t = input()
p = len(t)
even = []
odd = []
for j in range(p):
if j % 2 == 0:
even.append(t[j])
for j in range(n):
if j % 2 != 0:
odd.append(t[j])
first_join=''.join(even)
second_join = ''.join(odd)
print("{} {}".format(first_join,second_join)
You can use list comprehension to make it easier.
t = ""
p = len(t)
even = ''.join([t[i] for i in range(0,p,2)])
odd = ''.join([t[i] for i in range(1,p,2)])
print(f"{even} {odd}")