Conversion of strings in list to int - not converting - python

I am trying to convert a list which previously has some integer values, strings and floats all to integers, however am running into some issues during the conversion. Here is what I have done:
class NumbersIterable:
def __init__(self, numbers):
self.numbers = numbers
print(self.numbers)
def runConversion(self):
return NumbersIterator.convertNumbers(self.numbers)
class NumbersIterator:
def convertNumbers(numbers):
print('in numbers')
for i in numbers:
int(i)
print(numbers)
return numbers
niterable = NumbersIterable(["1", 2.0, "4",5,6.1,"7",8,9.2])
niterable = niterable.runConversion()
sum = 0
for i in niterable:
print(i)
sum += i
print("sum =", sum)
I have some print statements along the way to verify the process, however after it runs through the for loop in NumbersIterator, the print statement shows the values in the list are not converted to integers and as such a error is thrown when running the for loop further down.
Is there anything I might be missing/spelling incorrectly here?
Thanks

You can use a simple list comprehension to convert all numbers:
def convertNumbers(numbers):
return [int(i) for i in numbers]

In your code, int(i) converts i into an integer, and then throws it away. You need to store the converted value in a list. One way of doing so, among many others, is initializing an empty list and then appending int(i):
class NumbersIterator:
def convertNumbers(numbers):
print('in numbers')
output = []
for i in numbers:
output.append(int(i))
print(numbers)
return output
Alternatively, list comprehension (as proposed by Pedro Maia) or using map would be more concise.

Related

Why doesn't my code generate random numbers without str?

Can someone explain to me why when I remove 'str' from 7 line of code "myset.add(str(i))", do I get the same numbers every time I hit run and get random numbers with 'str' included?
def RandomFunction(x, y):
myset = set()
mylist = []
listofnumbers = []
for i in range(x, y):
myset.add(str(i))
for x in myset:
mylist.append(int(x))
if len(mylist) <= 5:
print('In order to generate 5 numbers, the range of input needs to be higher')
else:
for y in mylist:
listofnumbers.append(y)
if len(listofnumbers) >= 5:
print(listofnumbers)
break
RandomFunction(10, 20)
Set keeps the elements in hash table, it uses default python's hash() function. Its implementation for numeric types looks like this:
def hash(number):
return number % (2 ** 61 - 1)
So, if the numbers aren't huge, hash value of an integer will be equal to the same integer. Because of this integers in python's set will be kept in ascending order (for also reads hash table in ascending order).
But string is a sequense of unicode characters with \0 at the end and python has another implementation of hash() for strings, so it won't work the same way for them.

Python Error. Trying to convert number into list and pull out first digit

So this:
for n in range (500):
lst = [int(i) for i in str(n)]
first_n = int(n[0])
list = lst
print list
print first_n
Is giving me the TypeError: 'int' object has no attribute 'getitem'.
But if I change the 3rd line from n into i then this:
for n in range (500):
lst = [int(i) for i in str(n)]
first_n = int(i[0])
list = lst
print list
print first_n
Gives me the list and the last number on that list. I need the first number not the last.
It gives me the first if instead I replace n in range (500): with n = raw input()
n = raw_input()
lst = [int(i) for i in str(n)]
first_n = int(n[0])
list = lst
print list
print first_n
But this is single number and need to have run thousands of numbers. (As you can see I change the i on the 3rd line back into n)
Please can you help?
Your issue lies with the raw_input. In python 2, it returns a string, not an integer. What you need is input(), which just returns an integer:
n = input()
lst = [int(i) for i in str(n)]
first_n = int(lst[0]) #also, need lst here, not n, as it is now an integer
list = lst
print list
print first_n
Probably an easier solution here is to instead convert it to a string:
>>> str(123)[0] # Convert to string and take 1st character
'1'
If you need it as a number, you can int it back. This feels inefficient, but you're trying to solve a problem strongly related to the written representation of a number, so strings feel like the appropriate solution. You can however use solutions related to taking the place value. If you are looking for the number of hundreds in the above, for example, you could % 100. This requires a little more work to make general, though.

Function to find the max of 3 numbers in Python

I'm trying to write a function that takes the inputs and puts them into a list, then sorts the list, and finds the greatest number. I keep getting errors and I'm not really sure what's wrong. I'll post the current code that I have typed up already. Any help or advice would be greatly appreciated, thank you.
Code:
def findMax3():
y = list(lst)
y.sort(lst)
y[0] == y[-1]
lst = int(input())
print(findMax3())
You need to pass in a variable - lst maybe?
You need to return value if you want your main to print something.
You need a constant input format for integer arrays, I will suggest 1 2 3 4 5 (space separated), that can be reversed to list using map(int, input().split())
Use the built-in max.
Do you want to limit yourself to 3 number arrays? if yes, use assertion.
That should be enough:
def findMax3(lst):
assert len(lst) == 3
lst.sort()
return max(lst)
lst = map(int, input().split())
print(findMax3(lst))
This is the corrected code:
def findMax3(lst):
y = lst[:]
y.sort()
return y[-1]
lst = [int(x) for x in input().split()]
print(findMax3(lst))
I'd say findMax() would be a better name as this could find the maximum of lists of any length.
Bear in mind the following does the same thing:
lst = [int(x) for x in input().split()]
print(max(lst))
Put the numbers in a list, then use max() function to get the maximum value in a list, like this:
#create an empty numbers list
lst=[]
#loop for getting input numbers
for i in range(1,4):
try:
#here we get the input number
my_new_number=int(raw_input("Please input the number "+str(i)+"/3 :\n"))
except:
#in case of it is not a number raise an alert
print "not regular integer number"
#here we check that number not exist
if my_new_number not in lst:
#add the current input number to the list
lst.append(my_new_number)
else:
print "the number",my_new_number,"already exist in this list"
#show the maximum number of the list
print "The maximum number is",max(lst)
You might be interested in typing your list items one by one instead of using split() function to split your input. Also, to retrieve your list max, you have already a built-in max() function that you can use:
>>> num_list = []
>>>
>>> for i in range(3):
... num = input("Enter number {}: ".format(i + 1))
... num_list.append(int(num))
...
Enter number 1: 3
Enter number 2: 6
Enter number 3: 2
>>>
>>> max_num = max(num_list)
>>> print(max_num)
6
First off, Ebe Isaac gave a good explanation and you should look at his solution and understand why it works.
There's a few issues with your code.
lst = int(input())
print(findMax3())
You're inputting a list of numbers that need to be separated by some non-numeric character, so you cannot use int() on your input value.
lst = [int(x) for x in input().split()]
should give you what you want (with default separator being blank space). To learn more about this format, see list comprehensions.
Next, you call findMax3() but this function does not return a value so it will not have anything to print (see below). Additionally, it would be better to send it your list as an argument, this will save you from another line copying it later (see below).
lst = input().split()
print(findMax3(lst))
Now for your function:
def findMax3():
y = list(lst)
You should probably send an argument (the inputted list) to the function. This argument can be renamed whatever you put in the parentheses after the name of the function. You are using y here so we can rewrite it as:
def findMax3(y):
and delete the y = list(lst) line.
y.sort(lst)
When using a method or function, it's a good idea to look up the documentation to identify what arguments it takes. You'll see that sort can take two arguments (key and reverse) neither are needed here so we can fix this line by changing it to:
y.sort()
The next line:
y[0] == y[-1]
is a Boolean expression and returns either True or False if the first element of the sorted list (y[0]) is equal to the last element of the sorted list (y[-1]). To be honest, I'm not really sure what you were trying to do here. Since the function is designed to find the max value of the list, it needs to return that value so we need to use return(). The max value will be the last of the list so you can do:
return(y[-1])
So if you want to keep the flow of your original code, it can work by changing it to:
def findMax3(y):
y.sort()
return(y[-1])
lst = [int(x) for x in input().split()]
print(findMax3(lst))
I hope this helps. Best of luck.
As many have mentioned, you need to let your function know what list to find the max of. To do that, you need to put the name of the list in the parameter list of the function i.e. findMax3(lst).
Your function will still not work because you are not returning anything from it. You need to use the return keyword followed by what to return in order to have the function give you a response. For example, return 1 will return the value of 1 to anyone who called this function. Using that example, you need to decide what to return to the caller.
My version of findMax3 without any other function calls:
def findMax3(*args):
max3 = args[0]
for n in args[1:3]:
if n > max3:
max3 = n
return max3
This is pretty close to what the built in max function will do given those same 3 inputs
If you already have a list then you can simply use the max function to get the highest number among 3 numbers in the list.
lst = [5, 2, 9]
print(max(lst))
# output
9
Or I assume you have three different numbers as input and then you can pass them to your desired method to get the highest number.
# function to get max among 3 integers
find_max(x, y, z):
return max([x, y, z])
# take input
num1 = int(input("enter num1: "))
num2 = int(input("enter num2: "))
num3 = int(input("enter num3: "))
# call your function
print(find_max(num1, num2, num3))
If we do not want to use the built in function for solving the problem we could always follow the below simple approach.
Using max() to find maximum of numbers is already shown in above few solutions.
Posting a sample solution without use of max()
num1=51
num2=6
num3=72
def find_max(num1,num2,num3):
if (num1 > num2) and (num1 > num3):
largest = num1
elif (num2 > num1) and (num2 > num3):
largest = num2
else:
largest = num3
return largest
print(find_max(num1,num2,num3))

Add all numbers that are in a list

So if I have a list, let's say: [1,2,'hello'] and I want to add all the numbers in a list, (strings should be ignored). I want it to return the number 3 (1+2). And the function must be recursive.
This is what I have come up with:
import numbers
def isnumber(x):
return isinstance(x, numbers.Number)
def sum_first(list):
if not list:
return 0
elif isnumber(list[-1]):
return list[-1] + sum_first(list[:-1])
list=eval(input("Enter a list: "))
print(sum_first(list))
This only works if the last element in the list is a number. Let's assume it's a string, how could I change it?
You are only handling two cases:
the list is empty
the last element is a number
Your example list doesn't fit either case, so you end up returning None.
Add a third branch:
def sum_first(lst):
if not lst:
return 0
elif isnumber(lst[-1]):
return lst[-1] + sum_first(lst[:-1])
else:
return sum_first(lst[:-1])
Now you handle the case where the last element is not a number; you handle it by ignoring it; recursing with the list without that one element.
I renamed your list variable to lst to avoid masking the built-in type.
reduce can be seen as a form of recursive function. If you don't intend to write your own recursive function then may be you could do this
import operator as op
def silent_int(v):
try:
return int(v)
except ValueError:
return 0
xs = [1, 2, 'hello', '4']
print reduce(op.add, map(silent_int, xs))
Obviously the correct way of counting numbers should be using sum but with the recursion restriction you could use reduce or build your own trampoline!

Writing a custom sum function that sums a list of numbers

I am new to Python and need some help writing a function that takes a list as an argument.
I want a user to be able to enter a list of numbers (e.g., [1,2,3,4,5]), and then have my program sum the elements of the list. However, I want to sum the elements using a for loop, not just by using the built in sum function.
My problem is that I don't know how to tell the interpreter that the user is entering a list. When I use this code:
def sum(list):
It doesn't work because the interpreter wants just ONE element that is taken from sum, but I want to enter a list, not just one element. I tried using list.append(..), but couldn't get that to work the way I want.
Thanks in anticipation!
EDIT: I am looking for something like this (thanks, "irrenhaus"):
def listsum(list):
ret=0
for i in list:
ret += i
return ret
# The test case:
print listsum([2,3,4]) # Should output 9.
I'm not sure how you're building your "user entered list." Are you using a loop? Is it a pure input? Are you reading from JSON or pickle? That's the big unknown.
Let's say you're trying to get them to enter comma-separated values, just for the sake of having an answer.
# ASSUMING PYTHON3
user_input = input("Enter a list of numbers, comma-separated\n>> ")
user_input_as_list = user_input.split(",")
user_input_as_numbers_in_list = map(float, user_input_as_list) # maybe int?
# This will fail if the user entered any input that ISN'T a number
def sum(lst):
accumulator = 0
for element in lst:
accumulator += element
return accumulator
The top three lines are kind of ugly. You can combine them:
user_input = map(float, input("Enter a list of numbers, comma-separated\n>> ").split(','))
But that's kind of ugly too. How about:
raw_in = input("Enter a list of numbers, comma-separated\n>> ").split(',')
try:
processed_in = map(float, raw_in)
# if you specifically need this as a list, you'll have to do `list(map(...))`
# but map objects are iterable so...
except ValueError:
# not all values were numbers, so handle it
The for loop in Python is exceptionally easy to use. For your application, something like this works:
def listsum(list):
ret=0
for i in list:
ret+=i
return ret
# the test case:
print listsum([2,3,4])
# will then output 9
Edit: Aye, I am slow. The other answer is probably way more helpful. ;)
This will work for python 3.x, It is similar to the Adam Smith solution
list_user = str(input("Please add the list you want to sum of format [1,2,3,4,5]:\t"))
total = 0
list_user = list_user.split() #Get each element of the input
for value in list_user:
try:
value = int(value) #Check if it is number
except:
continue
total += value
print(total)
You can even write a function that can sum elements in nested list within a list. For example it can sum [1, 2, [1, 2, [1, 2]]]
def my_sum(args):
sum = 0
for arg in args:
if isinstance(arg, (list, tuple)):
sum += my_sum(arg)
elif isinstance(arg, int):
sum += arg
else:
raise TypeError("unsupported object of type: {}".format(type(arg)))
return sum
for my_sum([1, 2, [1, 2, [1, 2]]])
the output will be 9.
If you used standard buildin function sum for this task it would raise an TypeError.
This is a somewhat slow version but it works wonders
# option 1
def sumP(x):
total = 0
for i in range(0,len(x)):
total = total + x[i]
return(total)
# option 2
def listsum(numList):
if len(numList) == 1:
return numList[0]
else:
return numList[0] + listsum(numList[1:])
sumP([2,3,4]),listsum([2,3,4])
This should work nicely
user_input = input("Enter a list of numbers separated by a comma")
user_list = user_input.split(",")
print ("The list of numbers entered by user:" user_list)
ds = 0
for i in user_list:
ds += int(i)
print("sum = ", ds)
}
Using accumulator function which initializes accumulator variable(runTotal) with a value of 0:
def sumTo(n):
runTotal=0
for i in range(n+1):
runTotal=runTotal+i
return runTotal
print sumTo(15)
#outputs 120
If you are using Python 3.0.1 or above version then use below code for Summing list of numbers / integer using reduce
from functools import reduce
from operator import add
def sumList(list):
return reduce(add, list)
def oper_all(arr, oper):
sumlist=0
for x in arr:
sumlist+=x
return sumlist
Here the function addelements accept list and return sum of all elements in that list only if the parameter passed to function addelements is list and all the elements in that list are integers. Otherwise function will return message "Not a list or list does not have all the integer elements"
def addelements(l):
if all(isinstance(item,int) for item in l) and isinstance(l,list):
add=0
for j in l:
add+=j
return add
return 'Not a list or list does not have all the integer elements'
if __name__=="__main__":
l=[i for i in range(1,10)]
# l.append("A") This line will print msg "Not a list or list does not have all the integer elements"
print addelements(l)
Output:
45
import math
#get your imput and evalute for non numbers
test = (1,2,3,4)
print sum([test[i-1] for i in range(len(test))])
#prints 1 + 2 +3 + 4 -> 10
#another sum with custom function
print math.fsum([math.pow(test[i-1],i) for i in range(len(test))])
#this it will give result 33 but why?
print [(test[i-1],i) for i in range(len(test))]
#output -> [(4,0), (1, 1) , (2, 2), (3,3)]
# 4 ^ 0 + 1 ^ 1 + 2 ^ 2 + 3 ^ 3 -> 33

Categories