TAGS :Viewed: 7 - Published at: a few seconds ago

[ Python: alphabet count ]

I need someone to help me with the explaination for the below code. After looking at the solution, it took me some time to figure out that the number actually represents the humber of times the alphabet being counted. However, am very weak in python.

So, could someone explain to me in plain English how the alphabet count is tied to the number list please?

line = 'abcdef'
count = [3,4,7,1,2,5]
index = 0
while index < len(line):
  print(count[index], end=' ')
  for k in range(0,count[index]):
    print(line[index],end='')
  print()
  index = index + 1

OUTPUT

3 aaa
4 bbbb
7 ccccccc
1 d
2 ee
5 fffff

Answer 1


The loop generates an index between 0 and len(line) - 1, using that index both on line and count. As such, count is expected to be the same length.

To follow this through:

  1. As long as index is smaller than len(line), keep looping.
  2. print count[index], with a space after it, no newline.
  3. loop from 0 to count[index] - 1. This'll loop count[index] times. In this for loop, print line[index] with no newline, resulting in the character being printed count[index] times.
  4. Print a newline
  5. Increment index.

The first iteration, index is 0, which is smaller than len(line). line[0] is a, count[0] is 3, so after printing 3, a is printed 3 times.

The second iteration, index is 1, which is smaller than len(line). line[1] is b, count[1] is 4, so after printing 4, b is printed 4 times.

etc. until index is 6, at which point the while loop ends.

The code could be simplified to:

for char, c in zip(line, count):
    print(c, c * char)

Answer 2


Lets go through it one iteration at a time:

  • 1st iteration: index is 0, count[0] is 3, line[0] is 'a'. So we print 3, and then print 'a' 3 times
  • 2nd iteration: index is 1, count[1] is 4, line[1] is 'b'. So we print 4, and then print 'b' 4 times

Hopefully that is enough to make it clear what is happening.