This question already has answers here:
How to split an integer into a list of digits?
(10 answers)
Closed 5 years ago.
for example i have this variable:
x=123
how can i convert it to a tuple or each digit into separate variables?:
x=(1,2,3)
or
x1=1
x2=2
x3=3
>>> x=123
>>> tuple(map(int, str(x)))
(1, 2, 3)
You can use a comprehension with a tuple after casting the value to a string:
x=123
x = tuple(int(i) for i in str(x))
Output:
(1, 2, 3)
Convert to a string, convert each digit to an int, then unpack directly into variables:
x = 123
x1, x2, x3 = [int(i) for i in str(x)]
This requires that you know in advance how many digits are present in the string. Better to just use a tuple or list to hold the digits and reference them by index.
t = tuple(int(i) for i in str(x))
t[0]
# 1
etc.
Code:
x = 1234567
digits = []
print("number: " + str(x))
while x > 0:
digits.append(x % 10)
x = int(x / 10)
# To put it back in order
digits.reverse()
for i in range(len(digits)):
print(digits[i])
Output:
number: 1234567
1
2
3
4
5
6
7
Related
This question already has answers here:
Changing one character in a string
(15 answers)
Closed 2 years ago.
In this code here
x = '123'
How can I addition let's say 5 to the second index. So x would be '173'.
x = '123'
n = 5
result = x[:1] + str(int(x[1]) + n) + x[2:]
print(result)
Prints:
173
For n=9:
1113
Split it into a list, try to turn them into ints or floats, and do your math.
x = "123"
x = list(x)
for i in range(0, len(x)):
try:
x[i] = int(x[i])
except:
x[i] = x[i]
x[1] += 5
print(x)
It returns [1.0, 7.0, 3.0].
Split the string into a list, modify the element at the desired index, then join the list back into a string.
x = '123'
i = 1
n = 5
y = list(x)
y[i] = str(int(y[i]) + n)
print(''.join(y)) # -> 173
Based on scvalex's answer on Changing one character in a string in 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))
This question already has answers here:
accepting multiple user inputs separated by a space in python and append them to a list
(4 answers)
Closed 7 years ago.
I am trying to create a function that calculates the sum of an artithmetic sequence. I know how to set up the mathematical calculations but I don't know how to take input from the user to actually perform them.
How can I take user input (like below) such that the three ints on each line are read as A, B, N, with A being the first value
of the sequence, B being the step size and N the number of steps.
8 1 60
19 16 69
17 4 48
What should come next?
def arithmetic_progression():
a = raw_input('enter the numbers: ')
with raw_input you generally get a string
>> a = raw_input('enter the numbers')
you enter the numbers 8 1 60, so a will be a string '8 1 60'. Then you can split the string into the 3 substrings
>> b = a.split()
This will return you a list ['8', '1', '60']. Out of this you can get your numbers
>> A = int(b[0])
>> B = int(b[1])
>> N = int(b[2])
To read multiple lines you could add a function similar to this
def readlines():
out = raw_input('enter the numbers\n')
a = 'dummy'
while(len(a)>0):
a = raw_input()
out += '\n' + a
return out
This function would read any input and write it to the out string until you have one empty line. To get the numbers out of the string just do again the same as for a single line.
Sum to n terms of AP is: Sn = (n/2) [ 2a + (n-1)d ]
def arithmetic_progression():
inp = raw_input('enter the numbers: ').split(' ')
if not len(inp) == 3: # in case of invalid input
return arithmetic_progression() # prompt user to enter numbers again
a = float(inp[0])
d = float(inp[1])
n = float(inp[2])
s = ( (2 * a) + ((n - 1) * d) ) * (n / 2)
print('Sum to n terms of given AP is: ' + str(s))
arithmetic_progression()
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])
I'm a few weeks into learning python and I am trying to write a script that takes an input of any length of numbers and splits them in one-character lengths. like this:
input:
123456
output:
1 2 3 4 5 6
I need to do this without using strings, and preferably using divmod...
something like this:
s = int(input("enter numbers you want to split:"))
while s > 0:
s, remainder = divmod(s, 10)
I'm not sure how to get the spacing right.
Thank you for the help.
As your priority is to use divmod, you can do it like this:
lst=[]
while s>0:
s, remainder = divmod(s, 10)
lst.append(remainder)
for i in reversed(lst):
print i,
Output:
enter numbers you want to split:123456
1 2 3 4 5 6
You can use join() to achieve that. Cast to string if your are using python 2.*
s = input("enter numbers you want to split:")
s= str(s)
digitlist=list(s)
print " ".join(digitlist)
In case, you are in need of integers, just do it.
intDigitlist=map(int,digitlist)
What about the following using the remainder:
s = 123456
output = []
while s > 0:
s, r = divmod(s, 10)
output.append(r)
fmt='{:<12d}'*len(output)
print fmt.format(*output[::-1])
Output:
1 2 3 4 5 6
This also uses some other useful Python stuff: the list of digits can be reversed (output[::-1]) and formatted into 12-character fields, with the digit aligned on the left ({:<12d}).
Try it with mod:
while x > 0:
x = input
y = x % 10
//add y to list of numbers
x = (int) x / 10
e.g. if x is 123:
123 % 10 is 3 -> you save 3.
the Integer value of 123 / 10 is 12.
Then 12 % 10 is 2 -> you save 2
Int of 12 / 10 is 1.
1 % 10 = 1 -> you save 1
Now you have all numbers. You can invert the list after that to have it like you want.
You can iterate over Python string amd use String.join() to get result:
>>>' '.join(str(input("Enter numbers you want to split: ")))
Enter numbers you want to split: 12345
1 2 3 4 5