5

today I bring you an apparently simple question, that it's not so simple as it seems(for me at least)!

Imagine I have the following list of integers:

num = [3,1,1,2]

And I want to print "$" corresponding with the height i.e:


&
&     & 
& & & &



for i in num:
    print("#"*i)


prints this:


& & &
&
&
& &


However I want the former displayed!

I tried this:


for i in range(1, max(num)+1): # loops through the rows 
   for j in num:
       if j == i:
            print("#")
       else:
            print("")

But after a while I understood that the condition doesn't make any sense, because I'm comparing row numbers with the height!

I tried other stuff but none of them worked properly, I would appreciate if someone could help me out! Thanks

yatu
  • 86,083
  • 12
  • 84
  • 139
José Rodrigues
  • 467
  • 3
  • 12

2 Answers2

5

I would just iterate backwards from the max number, checking each element in your list if it is greater to or equal to that number, and printing the desired character, else printing a space.

>>> for x in range(max(num), 0, -1):
...     print(''.join(['&' if i >= x else ' ' for i in num]))
...
&
&  &
&&&&
Chris
  • 15,819
  • 3
  • 24
  • 37
1

A great question! Here is my take on it without using any packages

def printH(nList):
    m = max(nList)
    while m > 0:
        for l in nList:
            if(l>=m):
                print('#',end = ' ')
            else:
                print(' ',end = ' ')
        print('')
        m-=1
num = [5,3,1,1,2]
printH(num)

Expected output:

#
#
# #
# #     #
# # # # #
Harsha
  • 353
  • 1
  • 15
  • I'm only comparing max value in the first pass of the loop (so the max height). In this pass: all columns with max height are printed with '#'. In the next run I'm checking it with max height -1 (refer to m-=1), this prints out all '#' with max height -1. This goes on until we reach m =0 (i.e., no more height). Try modifying my code by print(m) after 'for l in nList' so that you can track m. Let me know if this explanation does not make sense. – Harsha Sep 10 '19 at 16:23