for loop - Bar Making - Python -
I am writing a function that takes a list variable and returns the vertical bars corresponding to each number in the list. I just have a simple problem, in fact, maybe I'm missing something.
def vBarMaker (nums): #Helper function output = "" while nums! = 0: nums - = 1 output = = "*" if nums = = 0: return output vBarGraphify def (nums): for numbers in nums: print vBarMaker (number) printed vBarGraphify ([0,1,3,2] ) # ^ This Return # # * # *** # # # # But I want to return it: # * # * * # * * * * Does anyone give me the function Can help in editing, which gives returns. Thanks in advance.
Currently you have a single loop that reaches the associated star until the number is reached goes. You should also keep in mind the different places. What I will do, the output is opposite to the current index number of an asterisk for that number.
It is to say that if the list passed in the function is [1, 2,3] then on the first iteration, two places and one * should be printed: '*' and on the next iteration, one place and two * should be printed: '**' on the third iteration, three * should be printed: '* ** ' Edit:
I went ahead and coded my implementation though corn3lius' answer was already brilliant I had them here and d Were also included Ctor test so you can see how it works.
The main difference between my answer and the Corn 3 Elias is that the left-hand white space is harder to the north of Corn 3 Elius is generated on the basis of maximum number inside my given list.
def BarGraphify1 (nums): see '' 'http://stackoverflow.com/a/23257715/940217 & gt; & Gt; & Gt; ("*" * Num) def BarGraphify2 (nums): '' ':: num:' 'num: in bar for barGraphify1 ([1,2,3]) * ** ***' '' '' & Gt; & Gt; & Gt; Bar graphite 2 ([1,2,3]) * ** *** & gt; & Gt; & Gt; BarGraphify2 ([1,3,2]) for n in nx * *** ** '' 'output = [] maxVal = max (nums): space = (maxVal-n) *' 'asterisk = n * '*' output.append (space + asterisks) print '\ n'.join (output) if __name__ ==' __main__ ': import doctest doctest.testmod () edit # 2 :
Now when I see that the OP The column is shown in the edit, I have resumed my solution to use the function. Most of this remains the same, but now I consider the whole thing as rows and columns, then move the 2-D array to get the desired column. '' '& Gt; & Gt; & Gt; Bar graphite 3 ([1,2,3]) * ** *** & gt; & Gt; & Gt; BarGraphify3 for n in num_ (* [1,3,2]) * ** *** '' 'grid = [] maxVal = max (nums): space = (maxVal-n) *' 'asterisks = n *' * 'grid.append (list (space + asterisks)) cols = [] for line in numpy.transpose (grid): cols.append (' '. join (row)) print' \ n '. Include (column)
Comments
Post a Comment