numbers into symbols (Python) - python

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?

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)
...
$
$$
$$$
$$$$
$$$$$
>>>

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)
$
$$$$$
$$$
$$

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)

numbers = raw_input("input :")
for number in [li for li in numbers.split(" ") if li.isdigit()]:
print('$' * int(number))

Related

How do I take out the 2 or more-digit numbers in a python string?

I am trying to add up the numbers in the string like such: 76 977
I need to add up these numbers, but I get a 1st+2nd digit sum.
My code:
a = list(input())
a.remove(' ')
print(a)
print(int(a[0])+int(a[1]))
use the split function:
a = "76 977"
b=a.split(" ")
sum = 0
for num in b:
sum += int(num)
print(sum)
Try a.split(' '), it takes a string and returns a list of strings seperated by that string.
a = input()
b = a.split(' ')
print(b)
print(int(b[0])+int(b[1]))
Slightly different answer :
string = '76 977'
print(sum([int(x) for x in string.split()]))
print('Enter string of numbers : ')
a = list(input())
print('\nThis is character list of entered string : ')
print(a)
numbers = []
num = 0
for x in a:
# ord() is used to get ascii value
# of character ascii value of
# digits from 0 to 9 is 48 to 57 respectively.
if(ord(x) >= 48 and ord(x) <= 57):
#this code is used to join digits of
#decimal number(base 10) to number
num = num*10
num = num+int(x)
elif num>0 :
# all numbers in string are stored in
# list called numbers
numbers.append(num)
num = 0
if num>=0:
numbers.append(num)
num = 0
print('\nThis is number list : ', numbers)
sum=0
for num in numbers:
# all numbers are added and and sum
# is stored in variable called sum
sum = sum+num
print('Sum of numbers = ', sum)

The fastest and most efficient way to get max number from a list of numbers

How can I improve the code and make it the fastest and most efficient way to take 10 numbers from the user, and then calculate the highest number from the list ? It can be anything, Pythonic, etc..
I have this code, and I want you please to improve it.
numbers = []
for _ in range(11):
numbers.append(input('Enter Num: '))
result = max(numbers)
print(result)
I have not included the program execution time because I'm taking inputs.
Most compact way I could think of:
result = max([input("Enter num: ") for _ in range(11)])
print(result)
You can simply:
max = 0
for _ in range(11):
next = input('Enter Num: ')
if next > max:
max = next
print(max)
numbers = []
for _ in range(11):
numbers.append(input('Enter Num: ')
numbers.sort()
print("Largest element is:", numbers[-1])
numbers = raw_input("Enter 10 numbers seperated by a comma (IE 1,2,3,..,..): ")
numbers = [int(i) for i in numbers.split(",")]
results = set()
for _ in range(len(numbers)+1):
results.add(_)
print(max(results))
Demo:
>>> numbers = raw_input("Enter 10 numbers seperated by a comma (IE 1,2,3,..,..): ")
Enter 10 numbers seperated by a comma (IE 1,2,3,..,..): 1,2,3,4,5,6,7,8,9,10
>>> numbers = [int(i) for i in numbers.split(",")]
>>> results = set()
>>> for _ in range(len(numbers)+1):
... results.add(_)
...
>>> results
set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
>>> print(list(results).sort())
None
>>> print(max(results))
10
>>>

Multiplying corresponding elements from 2 lists in Python

I'm new to Python and I was wondering if anyone could help explain how to code the following task in Python using stdin
Programming challenge description:
You have 2 lists of positive integers. Write a program which multiplies corresponding elements in these lists.
Input:
Your program should read lines from standard input. Each line contains two space-delimited lists. The lists are separated with a pipe char (|). Both lists have the same length, in range [1, 10]. Each element in the lists is a number in range [0, 99].
Output:
Print the multiplied list.
Test Input:
9 0 6 | 15 14 9
Expected Output:
135 0 54
Try this:
input_string = input().strip()
list1 = map(int, input_string.split("|")[0].split())
list2 = map(int, input_string.split("|")[1].split())
result = " ".join([str(n1*n2) for n1, n2 in zip(list1, list2)])
OR,
input_string = input().strip()
list1 = input_string.split("|")[0].split()
list2 = input_string.split("|")[1].split()
result = " ".join([str(int(n1)*int(n2)) for n1, n2 in zip(list1, list2)])
OR,
import operator
input_string = input().strip()
list1 = map(int, input_string.split("|")[0].split())
list2 = map(int, input_string.split("|")[1].split())
result = " ".join(map(str, map(operator.mul, list1, list2)))
OUTPUT of print(result):
135 0 54
Since you are asking for help and not just a solution, here are some useful functions that should give you some inspiration:)
input("give me some") #reads a string from stdin.
"abcabcbbbc".split("c") #splits the string on "c" and returns a list.
int("123") #converts the string to an int object.
#Input comma seperated values
a = input("Values of first list: ")
a = a.split(",")
b = input("Valies of second list: ")
b = b.split(",")
c = []
counter = 0
for each in a:
c.append(int(each) * int(b[counter]))
counter += 1

Equivalent of java.util.Scanner in python

In Java, one can write something like this:
Scanner scan = new Scanner(System.in);
x = scan.nextInt();
y = scan.nextDouble();
etc.
What is the equivalent of this in Python 3? The input is a list of space separated integers and I do not want to use the strip() method.
Use the input() method:
x = int(input())
y = float(input())
If you're looking to take a list of space separated integers, and store them separately:
`input: 1 2 3 4`
ints = [int(x) for x in input().split()]
print(ints)
[1, 2, 3, 4]
After you get your input using "input" function you could do :
my_input = input("Enter your input:")
# my_input = "1, 2"
def generate_inputs(my_input):
yield from (i for i in my_input.split())
inputs = generate_inputs(my_input)
x = int(next(inputs))
y = int(next(inputs)) # you could also cast to float if you want
If you want less code :
scan = (int(i) for i in input().split())
x = next(scan)
y = next(scan)

multiply the every second digit in list in python

I've tried to get numbers' list between 0 and100,000. and then i want to multiply every second digits of the list. I have no idea how to get the ervery second digit of the numbers.
def breakandSum():
if 0<=x<100000:
digits=(map(int,str(x)))
return digits
To get the second digit from the right in base 10, you would first mod the number by 100 to truncate the leading digits, then take the integer result and divide by the integer 10 to truncate the trailing digits.
Here's a quick example where x = 4567 which extracts the second base 10 digit from the right, or the "tens" digit, which is "6" in this example:
>>> x = 4567
>>> x = x % 100
>>> x = x / 10
>>> print x
6
If you wanted to put all the digits in a list, you could just extract the right-most digit, append it to the list, then truncate and continue the loop as shown here:
>>> x = 4567
>>> xdigit = []
>>> while x > 0:
... xdigit.append(x % 10)
... x = x / 10
...
>>> print xdigit
[7, 6, 5, 4]
>>>
From here you can then get every second digit using a list comprehension and filter:
>>> every_other_digit = [xdigit[i] for i in filter(lambda j: j % 2 == 0, range(len(xdigit)))]
>>> print every_other_digit
[7, 5]
Which if you need to multiply these digits you can now just iterate over this list to get the final product:
>>> answer = 1
>>> for k in every_other_digit: answer *= k
...
>>> print answer
35
There is a more concise way of doing it:
digitSum = sum(x * 2 for x in list(map(int, str(num)))[::2])
Where:
str(num) turns num into a string
list(map(int, str(num))) for every element in string turn it back to an int and put it in a list
list(...)[::2] for every other element in the list starting from the leftmost element
x * 2 for x in list(...)[::2] for each element in the list multiply it by 2
sum(...) add every element from the iteration
Edit: sorry I thought you wanted to multiply each by a specific number if you want to multiply every other you just go:
import math
digitSum = math.prod(x for x in list(map(int, str(num)))[::2])

Categories

Resources