2

I don't understand this code

print(*map(input().find,map(chr,range(97,123))))

This code is written by someone to find the position of each character's (a - z) first appearance when the user type in words. And if the character is not consisted in the word the position will be -1.

so for example if the input is

baekjoon

the output will be

1 0 -1 -1 2 -1 -1 -1 -1 4 3 -1 -1 7 5 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1

`I've written code for this but it is really long compared to the one at the top

a = [i for i in input()]
result = 0

for i in range(ord('a'), ord('z')+1):
  for j in range(len(a)):
    if i == ord(a[j]):
      result = j
      break
    else:
      result = -1
  print(result, end=" ")

With this code i get the same output but i think it's not well written code. So i really want to understand this code to improve my coding skill

print(*map(input().find,map(chr,range(97,123))))

what does that star do in front of map function and i just don't know what how that code works.

HI YUM
  • 75
  • 1
  • 1
  • 7
  • Basically, print function takes endless parameters. Adding the star will "expand" the generator of the map function into multiple parameters – OneCricketeer Apr 29 '18 at 07:53
  • Its a one-liner - better? well ... it asks for input and issues the `string.find()` method on each character between ascii 97 and 123 for your given input. `find` returns -1 if not found, else the first(!) occurence of the character in your input. the result of map is a generator in python3 - the * just unpacks each value and provides it to print. `print(* [1,2,3]) == print(1,2,3)` – Patrick Artner Apr 29 '18 at 07:55

0 Answers0