How to add inputed numbers in string.(Python) - python

How do i add all imputed numbers in a string?
Ex:
input:
5 5 3 5
output
18
and it must supports ('-')
Ex.
input
-5 5 3 5
output
8
I write something like this:
x = raw_input()
print sum(map(int,str(x)))
and it adds normally if x>0
But what to do with ('-') ?
I understand that i need to use split() but my knowledge is not enough (

You're close, you just need to split the string on spaces. Splitting will produce the list of strings ['-5', '5', '3', '5']. Then you can do the rest of the map and sum as you intended.
>>> s = '-5 5 3 5'
>>> sum(map(int, s.split()))
8

its simple
>>> input = raw_input('Enter your input: ')
Enter your input: 5 5 10 -10
>>> list_numbers = [int(item) for item in input.split(' ')]
>>> print list_numbers
[5, 5, 10, -10]
And after what you want :)

You can use the following line:
sum(map(int, raw_input().split()))

Related

Printing the number of different numbers in python

I would like to ask a question please regarding printing the number of different numbers in python.
for example:
Let us say that I have the following list:
X = [5, 5, 5]
Since here we have only one number, I want to build a code that can recognize that we have only one number here so the output must be:
1
The number is: 5
Let us say that I have the following list:
X = [5,4,5]
Since here we have two numbers (5 and 4), I want to the code to recognize that we have only two numbers here so the output must be:
2
The numbers are: 4, 5
Let us say that I have the following list:
X = [24,24,24,24,24,24,24,24,26,26,26,26,26,26,26,26]
Since here we have two numbers (24 and 26), I want to the code to recognize that we have only two numbers here so the output must be:
2
The numbers are: 24, 26
You could keep track of unique numbers with a set object:
X = [1,2,3,3,3]
S = set(X)
n = len(S)
print(n, S) # 3 {1,2,3}
Bear in mind sets are unordered, so you would need to convert back to a list and sort them if needed.
you can change this list into set, it will remove duplicate, then you can change it again into list.
list(set(X))
You can try numpy.unique, and use len() on the result
May I ask you please if we can use set() to read the data in a specific column in pandas?
For example, I have the following the DataFrame:
df1= [ 0 -10 2 5
1 24 5 10
2 30 3 6
3 30 2 1
4 30 4 5 ]
where the first column is the index..
I tried first to isolate the second column
[-10
24
30
30
30]
using the following: x = pd.DataFrame(df1, coulmn=[0])
Then, I transposed the column using the following XX = x.T
Then, I used set() function.
However, instead of obtaining
[-10 24 30]
I got the following [0 1 2 3 4]
So set() read the index instead of reading the first column

Python splitting an int based on the char length

I’m new to python and would like to do a simple function. I’d like to read the input array and if the value is more than 4 digits, to then split it then print the first value then the second value.
I’m having issues splitting the number and getting rid of 0’s inbetween; so for example 1006, would become 1, 6.
Input array:
a = [ 1002, 2, 3, 7 ,9, 15, 5992]
Desired output in console:
1, 2
2
3
7
9
15
59,92
You can abstract the splitting into a function and then use a list comprehension to map that function over the list. The following can be tweaked (it matches more of what you had before one of your edits). It can be tweaked of course:
def split_num(n):
s = str(n)
if len(s) < 4:
return 0, n
else:
a,b = s[:2], s[2:]
if a[1] == '0': a = a[0]
return int(a), int(b)
nums = [1002, 2, 3, 7 ,9, 15, 5992]
result = [split_num(n) for n in nums]
for a,b in result:
print(a,b)
Output:
1 2
0 2
0 3
0 7
0 9
0 15
59 92
If you just want a list of the non-zero digits in the original list, you can use this:
a = [ 1002, 2, 3, 7 ,9, 15, 5992]
strings = [str(el) for el in a]
str_digits = [char for el in strings for char in el if char != '0']
and if you want the digits as ints, you can do:
int_digits = [int(el) for el in str_digits]
or go straight to
int_digits = [int(char) for el in strings for char in el if char != '0']
I'm not sure what the logic is behind your desired output is, though, so if this isn't helpful I'm sorry.

Remove last digit from String depending on length

I am trying to remove the last digit in the df[4] string if the string is over 5 digits.
I tried adding .str[:-1] to df[4]=df[4].astype(str) this removes the last digit from every string in the dataframe.
df[3]=df[3].astype(str)
df[4]=df[4].astype(str).str[:-1]
df[5]=df[5].astype(str)
I tried several different combinations of if statements but none have worked.
I'm new to python and pandas so any help is appreciated
You can filter first on the string length:
condition = df[4].astype(str).str.len() > 5
df.loc[condition, 4]=df.loc[condition, 4].astype(str).str[:-1]
For example:
>>> df
4
0 1
1 11
2 111
3 1111
4 11111
5 111111
6 1111111
7 11111111
8 111111111
>>> condition = df[4].astype(str).str.len() > 5
>>> df.loc[condition, 4]=df.loc[condition, 4].astype(str).str[:-1]
>>> df
4
0 1
1 11
2 111
3 1111
4 11111
5 11111
6 111111
7 1111111
8 11111111
If these are natural integers, it is however more efficient to divide by 10:
condition = df[4].astype(str).str.len() > 5
df.loc[condition, 4]=df.loc[condition, 4] // 10
Accessing Elements of a Collection
>>> x = "123456"
# get element at index from start
>>> x[0]
'1'
# get element at index from end
>>> x[-1]
'6'
# get range of elements from n-index to m-index
>>> x[0:3]
'123'
>>> x[1:-2]
'234'
>>> x[-4:-2]
'34'
# get range from/to index with open end/start
>>> x[:-2]
'1234'
>>> x[4:]
'56'
List Comprehension Syntax
I haven't see the pythons list comprehension syntax which really cool and easy.
# input data frame with variable string length 1 to n
df = [
'a',
'ab',
'abc',
'abcd',
'abcdf',
'abcdfg',
'abcdfgh',
'abcdfghi',
'abcdfghij',
'abcdfghijk',
'abcdfghijkl',
'abcdfghijklm'
]
# using list comprehension syntax: [element for element in collection]
df_new = [
# short hand if syntax: value_a if True else value_b
r if len(r) <= 5 else r[0:5]
for r in df
]
Now df_new contains only string up to a length of 5:
[
'a',
'ab',
'abc',
'abcd',
'abcdf',
'abcdf',
'abcdf',
'abcdf',
'abcdf',
'abcdf',
'abcdf',
'abcdf'
]
cause [-1]removes last numbers or change number to -1
try str df[4]=-1

Slicing large lists based on input

If I have multiple lists such that
hello = [1,3,5,7,9,11,13]
bye = [2,4,6,8,10,12,14]
and the user inputs 3
is there a way to get the output to go back 3 indexes in the list and start there to get:
9 10
11 12
13 14
with tabs \t between each space.
if the user would input 5
the expected output would be
5 6
7 8
9 10
11 12
13 14
I've tried
for i in range(user_input):
print(hello[-i-1], '\t', bye[-i-1])
Just use negative indexies that start from the end minus the user input (-user_input) and move to the the end (-1), something like:
for i in range(-user_input, 0):
print(hello[i], bye[i])
Another zip solution, but one-lined:
for h, b in zip(hello[-user_input:], bye[-user_input:]):
print(h, b, sep='\t')
Avoids converting the result of zip to a list, so the only temporaries are the slices of hello and bye. While iterating by index can avoid those temporaries, in practice it's almost always cleaner and faster to do the slice and iterate the values, as repeated indexing is both unpythonic and surprisingly slow in CPython.
Use negative indexing in the slice.
hello = [1,3,5,7,9,11,13]
print(hello[-3:])
print(hello[-3:-2])
output
[9, 11, 13]
[9]
You can zip the two lists and use itertools.islice to obtain the desired portion of the output:
from itertools import islice
print('\n'.join(map(' '.join, islice(zip(map(str, hello), map(str, bye)), len(hello) - int(input()), len(hello)))))
Given an input of 3, this outputs:
5 6
7 8
9 10
11 12
13 14
You can use zip to return a lists of tuple where the i-th element comes from the i-th iterable argument.
zip_ = list(zip(hello, bye))
for item in zip_[-user_input:]:
print(item[0], '\t' ,item[1])
then use negative index to get what you want.
If you want to analyze the data
I think using pandas.datafrme may be helpful.
INPUT_INDEX = int(input('index='))
df = pd.DataFrame([hello, bye])
df = df.iloc[:, len(df.columns)-INPUT_INDEX:]
for col in df.columns:
h_value, b_value = df[col].values
print(h_value, b_value)
console
index=3
9 10
11 12
13 14

Why is Python's max() function not accurate? [duplicate]

This question already has answers here:
Find highest and lowest number from the string of numbers
(5 answers)
Sorting numbers in python
(3 answers)
Closed 4 years ago.
I tried to use the max() function but I can't get the right max with it.
Example:
numbers = "4 5 29 54 4 0 -214 542 -64 1 -3 6 -6"
a = max(numbers.split(" "))
b = min(numbers.split(" "))
print a
print b
Output:
6
-214
It's obviously wrong, the max should be 542. Does anyone know why max() fails to find the correct max value? How to get the correct answer?
numbers.split(" ") gives you a list of strings, not integers.
If you want max() and min() to find the highest and lowest integers, then you need to convert your list of strings to a list of integers using map(int, your_array).
Example
numbers = "4 5 29 54 4 0 -214 542 -64 1 -3 6 -6"
numbers = numbers.split(" ") # Splits your string into a list of strings
numbers = map(int, numbers) # Converts each element in your list to int
a = max(numbers)
b = min(numbers)
print a # Outputs 542
print b # Outputs -214
In the other hand, you don't need to use map or other function to convert your string list to integer list, because it iterates over the list one more time, max function accepts key parameter, you can put a callable there, like this:
a = max(numbers.split(), key=int)
b = min(numbers.split(), key=int)
also in this case split() is same with split(" ").
Python max() function is accurate.
You should have a look at numbers.split(" ").
It returns a list of strings. Hence, the max compares and gives the max of the strings in the list.
>>> numbers.split(" ")
>>> ['4', '5', '29', '54', '4', '0', '-214', '542', '-64', '1', '-3', '6', '-6']
And, as string comparisons go, it will compare the first letter of each string, and the max would be: 6.
Because a and b are of type string, not an int.
numbers="4 5 29 54 4 0 -214 542 -64 1 -3 6 -6"
a = max(map(int, numbers.split(" ")))
b = min(map(int, numbers.split(" ")))
print a
print b
# 542
# -214
Try this:
numbers="4 5 29 54 4 0 -214 542 -64 1 -3 6 -6"
a = max(list(map(int, numbers.split(" "))))
b = min(list(map(int, numbers.split(" "))))
print a
print b

Categories

Resources