Skip to content
Advertisement

Hacker rank string seperated challenge

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)

Advertisement

Answer

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}")
4 People found this is helpful
Advertisement