-2

I have a problem with the task, I need to input numbers and print it like a histogram with symbol ($). One unit is one ($) symbol.

For example:

input

1 5 3 2

print

$
$$$$$
$$$
$$

The code at the moment:

number = int(input())
while (number > 0):
    print('$' * number)
    number = 0

This works only with one number.

What need to do to code work properly?

U13-Forward
  • 69,221
  • 14
  • 89
  • 114
AdernZ
  • 1
  • 1
  • 2
  • You need to [`split`](https://docs.python.org/3/library/stdtypes.html#str.split) the string `"1 5 3 2"`. – Matthias Mar 05 '19 at 09:42
  • 6
    Possible duplicate of [Get a list of numbers as input from the user](https://stackoverflow.com/questions/4663306/get-a-list-of-numbers-as-input-from-the-user) – Georgy Mar 05 '19 at 09:42

4 Answers4

1

You're close and your thinking is right.

When you input() a string a numbers separated by a space, you need to convert each number into an integer, because by default all arguments are string for input.

You can use the map function to convert each input to integer.

inp = map(int, input().split())

Here input().split() converts 1 5 3 2 to ['1', '5', '3', '2']

Then applying map(int, [1, 5, 3, 2]) is equivalent to doing int(1), int(5) to each element.

Syntax of map: map(function, Iterable) function is int() in out case.

Then as you have the integers, all you need to do is take each value and print the number of '$'

for val in inp:
    print('$'*val)

Here's the complete code:

inp = map(int, input().split())
for val in inp:
    print('$'*val)

$
$$$$$
$$$
$$
Mohit Motwani
  • 4,662
  • 3
  • 17
  • 45
1

You can do that like the follwoing,

>>> x = input("Enter the numbers: ") # use `raw_input` if `python2`
Enter the numbers: 1 2 3 4 5
>>> x
'1 2 3 4 5'
>>> y = [int(z) for z in x.split()]
>>> y
[1, 2, 3, 4, 5]
>>> for i in y:
...   print('$' * i)
... 
$
$$
$$$
$$$$
$$$$$
>>> 
han solo
  • 6,390
  • 1
  • 15
  • 19
0
numbers = raw_input("input :")
for number in [li for li in numbers.split(" ") if li.isdigit()]:
    print('$' * int(number))
paras chauhan
  • 777
  • 4
  • 13
0

You could try this

#get numbers as string
numbers = input('Enter numbers separated by <space> :')
# split numbers (create list)
nums = numbers.split(' ')
#loop each number
for num in nums:
    print_num = ''
    #create what to print
    for i in range(int(num)):
        print_num = print_num + '$'
    #print
    print(print_num)
bojan
  • 56
  • 1
  • 3