Python function to sum digits - python

I want function to take the last digit of each number in the list and sum them up all together. So forexample, the function below would return "10".
def getSumOfLastDigits(numList):
x = sum(int(num[-1:]) for num in numList)
print x
getSumOfLastDigits([1, 23, 456])
>>>10
Here is what i receive instead of the expected out "10"
def getSumOfLastDigits(numList):
x = sum(int(num[-1:]) for num in numList)
print x
getSumOfLastDigits([1, 23, 456])

Too much work.
def getSumOfLastDigits(numList):
return sum(x % 10 for x in numList)

x = sum(num%10 for num in numList)

You can't index into a number; a number isn't a sequence of digits (internally, it isn't represented in base 10). You can obtain the last digit of a number using mathematical manipulation instead: take the remainder when dividing by 10. We do this with the % operator.
Also:
Don't print the value in your function, return it. Let the calling code decide what to do with the value. Calculation and output are separate tasks, and should be kept separate.
Avoid indicating data types in variable names - yes, even in Python. It's not a good idea to build in assumptions that aren't actually necessary. You could use any kind of sequence here, for example. The simplest way to indicate that you have more than one number is to use the plural, numbers. That also means you use a full word, and people don't have to think about what 'num' is short for.
There is no need to assign the result of an expression to a temporary variable, if you are just going to use it once, and right away. The name x doesn't tell us anything, so cut it out.
get is considered an ugly prefix for function names by most Pythonistas. It should already be obvious that the function calculates and returns a value. Use noun-type names for those functions, and verb-type names for functions that are primarily intended to manipulate some existing data.
Thus:
def sum_of_last_digits(numbers):
return sum(number % 10 for number in numbers)

def getSumOfLastDigits(numList):
total=0
for item in numList:
newItem=str(item)
length=newItem[len(newItem)-1]
total+=int(length)
return total

Related

How to write a function with a list as parameters

Here is the question, I'm trying to define a function sample_mean that takes in a list of numbers as a parameter and returns the sample mean of the the numbers in that list. Here is what I have so far, but I'm not sure it is totally right.
def sample_mean(list):
""" (list) -> number
takes in a list of numbers as a parameter and returns the sample mean of the the numbers in that list
sample_mean =
sample_mean =
"""
mean = 0
values = [list]
for list in values:
print('The sample mean of', values, 'is', mean(list))
Firstly, don't use list as a name because it shadows/hides the builtin list class for the scope in which it is declared. Use a name that describes the values in the list, in this case samples might be a good name. The function could be implemented with something like this:
def sample_mean(samples):
total = 0
for value in samples:
total = total + value
return total / float(len(samples))
Or a shorter version which avoids writing your own loop by making use of Python's sum() function :
def sample_mean(samples):
return sum(samples) / float(len(samples))
Call the function like this:
>>> print(sample_mean([1,2,3,4,5]))
3.0
Note the use of float() to ensure that the division operation does not lose the fractional part. This is only an issue in Python 2 which uses integer division by default. Alternatively you could add this to the top of your script:
from __future__ import division
If you are sure that you only need to support Python 3 you can remove the float() and ignore the above.
As stated above by #idjaw, don't use list as a parameter instead use listr (for example). Your values = [list] is erroneous (also stated by #idjaw) and should be removed.
Also, according to PEP257, you should not use "(list) -> number" in your docstrings as that should only be used for builtins.
Finally, your loop should look like for l in listr: and then you add values to your mean variable. divide it by the number of values in the list and print the result.

Python Lists Append True Boolean

The following [incomplete] code is designed to take in an n to x number, of length x-n, and return the value of the next pandigital number. The code identifies which number between n and x is missing from the number passed in as an argument to the function, and returns (for the time being, until the function is further developed), two lists, the original number itself with its individual digits as members of a list, and a list, with the numbers n to x as members, with those numbers which are present in the original number of length x-n being replaced by the Boolean value True.
def nextPandigital(n,lower,upper):
digits = []
requiredDigits = []
#Completed loop
for digit in str(n):
digits.append(int(digit))
#Completed loop
for num in range(lower,upper+1):
requiredDigits.append(num)
for number in requiredDigits:
if str(number) in str(digits):
x = requiredDigits.index(number)
#requiredDigits[x] = 'True'
requiredDigits[x] = True
return digits, requiredDigits
Although, for the input parameters of nextPandigital(1023456789,0,9) in Enthought Canopy, the second list returned should read [True,True,True,True,True,True,True,True,True,True], the value of the second list returned is, in fact [True,1,True,True,True,True,True,True,True,True], with the 1 from the original requiredDigits list not being replaced by True.
I know that there is no issue with the loop, or the general flow of the code, for when the requiredDigits[x] = True line of code is commented, and the currently commented code is uncommented, the code works as it is intended to, with all digits in requiredDigits being replaced by the String value 'True.'
I have attempted to resolve this issue. However, I am not able to pinpoint its source. I have considered to fact that True == 1 returns True. However, when the value True is replaced by False, in the line requiredDigits[x] = True, the code still works as it is intended to.
Any answer/help/suggestion/advice on this matter would be highly appreciated. Thank you in advance.
The issue is with using index to find where to assign to. Since True is equal to 1, you're mistakenly thinking that the True you entered for 0 is the 1 you want to replace next.
A solution would be to use enumerate to get indexes as you iterate over your list, rather than needing to find them later using index:
for x, number in enumerate(requiredDigits):
if str(number) in str(digits):
requiredDigits[x] = True
A better solution in general would be to use a list comprehension to create the list in one go, rather than starting with numbers and replacing some of them later:
requiredDigits = [True if num in digits else num for num in range(lower,upper+1)]
I'm also getting rid of the unnecessary calls to str in the membership test against digits. You were doing substring testing, rather than testing if the numbers themselves were in the list. That probably wasn't going to cause errors, since the numbers you care about are all one digit long, and the string representation of a list doesn't have any extraneous digits. But in general, its not a good idea to use string operations when you don't need to.
You are checking the same list that you are updating and that is always dangerous.
At the second iteration your variables are:
number=1
requiredDigits = [True, 1, 2, 3, 4, 5, 6, 7, 8, 9]
So when you are doing requiredDigits.index(1) there is a match but it does not reach the 1 since it happens in True==1 so it returns that the index 0
But in general, this implementation is not much pythonic, better check Blckknght's answer

Numerical String Conversions in Python Function

I'm currently learning python so I apologize in advance for the messiness of my code. My function is meant to take in a single string and add the string numbers together. i.e. A string argument of 123 will become 1 + 2 + 3 and return 6.
My issue is when I iterate through my list - python keeps indicating that the variable has been referenced before any value has been assigned. However when I print out the values being calculated they are correct. Even more confusing is that when I return them - they are incorrect. I can't seem to work out where I'm going wrong. Could anyone tell me what the issue may be?
Thank you!
listy = []
global total
#Convert number to a list then cycle through the list manually via elements and add them all up
def digit_sum(x):
number= []
number.append(x)
print number
for i in range(len(number)):
result = str(number[i])
print result
#Now it has been converted to a string so we should be able to
#read each number separately now and re-convert them to integers
for i in result:
listy.append(i)
print listy
#listy is printing [5,3,4]
for i in listy:
total += int(i)
return total
print digit_sum(x)
I'm not really sure what's going on in your code there, especially with the messed up indentation, but your problem is easily sovled:
sum(map(int, str(534)))
It makes the number a string, then converts each digit to an int with map, then just sums it all.
If your concern is only about summing a string of numbers, then list comprehension itself would do or as #Maltysen suggested you could use map
sum([int(x) for x in "534"])
pretty simple:
You can use a map or a list comprehension. They are pretty much equivalent. Other people gave an answer using map but I decided to use a list comprehension.
s = "1234567"
sum([int(character) for character in s])
I believe I have worked out what was wrong with my code. As I am still new to Python, I made some very novice mistakes such as not realizing declaring a variable outside the local function would result in the solution not being what I had expected.
Due to my returns being placed incorrectly as well as my listy [] variable being instantiated outside my function, instead of reading each number once, it would read it three times.
This has now been corrected in the code below.
#Convert number to a list then cycle through the list manually via elements and add them all up
def digit_sum(x):
total = 0
number= []
number.append(x)
print number
for i in range(len(number)):
result = str(number[i])
print result
#Now it has been converted to a string so we should be able to
#read each number separately now and re-convert them to integers
for i in result:
listy = []
listy.append(i)
# print listy
#listy is printing [5,3,4]
for i in listy:
print i
total+= int(i)
print total
break
return total
print digit_sum(111)

Display the number of lower case letters in a string

This is what I have so far:
count=0
mystring=input("enter")
for ch in mystring:
if mystring.lower():
count+=1
print(count)
I figured out how to make a program that displays the number of lower case letters in a string, but it requires that I list each letter individually: if ch=='a' or ch=='b' or ch=='c', etc. I am trying to figure out how to use a command to do so.
This sounds like homework! Anway, this is a fun way of doing it:
#the operator module contains functions that can be used like
#their operator counter parts. The eq function works like the
#'=' operator; it takes two arguments and test them for equality.
from operator import eq
#I want to give a warning about the input function. In python2
#the equivalent function is called raw_input. python2's input
#function is very different, and in this case would require you
#to add quotes around strings. I mention this in case you have
#been manually adding quotes if you are testing in both 2 and 3.
mystring = input('enter')
#So what this line below does is a little different in python 2 vs 3,
#but comes to the same result in each.
#First, map is a function that takes a function as its first argument,
#and applies that to each element of the rest of the arguments, which
#are all sequences. Since eq is a function of two arguments, you can
#use map to apply it to the corresponding elements in two sequences.
#in python2, map returns a list of the elements. In python3, map
#returns a map object, which uses a 'lazy' evaluation of the function
#you give on the sequence elements. This means that the function isn't
#actually used until each item of the result is needed. The 'sum' function
#takes a sequence of values and adds them up. The results of eq are all
#True or False, which are really just special names for 1 and 0 respectively.
#Adding them up is the same as adding up a sequence of 1s and 0s.
#so, map is using eq to check each element of two strings (i.e. each letter)
#for equality. mystring.lower() is a copy of mystring with all the letters
#lowercase. sum adds up all the Trues to get the answer you want.
sum(map(eq, mystring, mystring.lower()))
or the one-liner:
#What I am doing here is using a generator expression.
#I think reading it is the best way to understand what is happening.
#For every letter in the input string, check if it is lower, and pass
#that result to sum. sum sees this like any other sequence, but this sequence
#is also 'lazy,' each element is generated as you need it, and it isn't
#stored anywhere. The results are just given to sum.
sum(c.islower() for c in input('enter: '))
You have a typo in your code. Instead of:
if my.string.lower():
It should be:
if ch.islower():
If you have any questions ask below. Good luck!
I'm not sure if this will handle UTF or special characters very nicely but should work for at least ASCII in Python3, using the islower() function.
count=0
mystring=input("enter:")
for ch in mystring:
if ch.islower():
count+=1
print(count)
The correct version of your code would be:
count=0
mystring=input("enter")
for ch in mystring:
if ch.islower():
count += 1
print(count)
The method lower converts a string/char to lowercase. Here you want to know if it IS lowercase (you want a boolean), so you need islower.
Tip: With a bit of wizardry you can even write this:
mystring= input("enter")
count = sum(map(lambda x: x.islower(), mystring))
or
count = sum([x.islower() for x in mystring])
(True is automatically converted to 1 and False to 0)
:)
I think you can use following method:
mystring=input("enter:")
[char.lower() for char in mystring].count( True ) )

print pattern recursion

I need to write a recursive function printPattern() that takes an integer n as a parameter and prints n star marks followed by n exclamation marks, all on one line. The function should not have any loops and should not use multiplication of strings. The printing of the characters should be done recursively only. The following are some examples of the behavior of the function:
>>>printPattern(3)
***!!!
>>>printPattern(10)
**********!!!!!!!!!!
This is what I have at the moment
def printPattern(n):
if n < 1:
pass
else:
return '*'*printPattern(n)+'!'*printPattern(n)
I know I am completely off, and this would be easier without recursion, but it is necessary for my assignment.
Q: What's printPattern(0)?
A: Nothing.
Q: What's printPattern(n), for n>=1?
A: *, then printPattern(n-1), then !.
Now you should be able to do it. Just remember to think recursively.
Recursion is based on two things:
a base case
a way to get an answer based off something closer to the base case, given something that's not the base case.
In your case, the simplest base case is probably 0 - which would print thing (the empty string). So printPattern(0) is ''.
So how do you get closer to 0 from your input? Well, probably by reducing it by 1.
So let's say that you are currently at n=5 and want to base your answer off something closer to the base case - you'd want to get the answer for n=5 from the one for n=4.
The output for n=5 is *****!!!!!.
The output for n=4 is ****!!!!.
How do you get from the output of n=4 to n=5? Well, you add a * on the front and a ! on the end.
So you could say that printPattern(5) is actually just '*' + printPattern(4) + '!'.
See where this is going?
Try this:
def printPattern(n):
if n <= 0:
return ''
return '*' + printPattern(n-1) + '!'
print printPattern(5)
> *****!!!!!

Categories