I am trying to run the following:
def count_small(numbers):
total = 0
for n in numbers:
if n < 10:
total = total + 1
return total
lotto = [4, 8, 15, 16, 23, 42]
small = count_small(lotto)
print(small)
Here I have defined a function 'count_small(numbers)'
it starts with a total of 0,
then checks each item in the list, to check that it is less than 10, if the item is less then 10, then 1 will be added to the total. I am running the function on the list 'lotto', as you can see 'lotto' has two numbers less than 10 '4' and '8' hence it should return 2, however, when I run the code it returns 1 instead.
Your return statement is inside the for-loop, so that the function is left after the first number.
def count_small(numbers):
total = 0
for n in numbers:
if n < 10:
total += 1
return total
When you use a generator expression, you can write this in one line:
def count_small(numbers):
return sum(n<10 for n in numbers)
Your indentation is incorrect. Place the return statement outside of your for loop.
Related
def factorList(num):
listOfFactors = []
for i in range <= num:
if num / i == 0:
listOfFactors.append(i)
print(listOfFactors)
factorList(36)
I want the function to go through each number between 1 and the number input until it finds a factor and adds it to a list
range() is a function (it needs parens), and it starts at zero, rather than 1...
You seem to have tried to combine range with a while loop logic, like so
i = 1
while i <= num:
# if ... append ...
i += 1
But you can do the same with list-comprehension
def factorList(num):
return [i for i in range(1, num+1) if num % i == 0]
print(factorList(36))
Output
[1, 2, 3, 4, 6, 9, 12, 18, 36]
side-note: For factorization, you only need to loop up to the square-root of the number.
range() is a function that returns a sequence of numbers, so you need to call it like a function.
for i in range(num):
See some documentation here: https://www.w3schools.com/python/ref_func_range.asp
Currently I am trying to make a function that returns the digital root and persistence of an integer, for example: digitalRootAndPersistence(9879) returns [6, 2]. Only built in function I can use is sum, and can use another function I made before called toDigitList which must be implemented into the digitalRoot function.
toDigitList function:
def toDigitList(n):
while n < 10:
return [n]
else:
return toDigitList(n // 10) + [n % 10]
My digitalRoot function: (I do not know what I am doing wrong, Im getting no errors, but also no output.)
def digitalRootAndPersistence(n):
x = (n)
count = 0
while n > 1:
x = sum(toDigitList(n))
count += 1
return (x), count
print(digitalRootAndPersistence(9879))
You have a couple of syntactic confusions. The parentheses in these lines of
code are not doing anything.
x = (n)
return (x), count
As noted in comments, n needs to decrease. Specifically, n should become the sum
of the digits. Which means no need for x. Also, the break point is 9, not 1.
def digitalRootAndPersistence(n):
count = 0
while n > 9:
n = sum(toDigitList(n))
count += 1
return n, count
I wanted to write a program which adds the digits until it becomes a single digit number, here is my code
n=int(input(""))
b=10**18
while not 1<=n<=b:
n=int(input(""))
else:
tot=0
while(n!=0):
dig=n%10
tot=tot+dig
n=n//10
s=0
if tot>=10:
while (tot!=0):
tot2=tot%10
s=s+tot2
tot=tot//10
else:
s=tot
print(s)
I thinked that it works correctly but when I type 88888888888 it gives me 16 as output not 7 ...but every thing is correct ...How can I fix that?
You can simply do
s = n % 9
Because from math we know that sum of digits of any number and a number itself has the same remainder when divided by 9. The only corner case is when n is divisible 9, in this case, you want s=9.
The final code would be:
n=int(input())
b=10**18
while not 1 <= n <= b:
n=int(input())
if (n%9 == 0):
s = 9
else:
s = n % 9
You could approach this recursively.
def sumDigits(N): return N if N<10 else sumDigits(sum(divmod(N,10)))
sumDigits(88888888888) # 7
If you want a mathematical solution:
def sumDigits(N): return (N+8)%9+1
the problem is simple that you don't do enough iterations, as Daniyar Aubekerov commented you need 3 round for 88888888888 (88888888888->88->16->7 ) but you only do 2
one way to solve it is simple factor out the commons parts into their own functions and use them as needed, for example
def digits(n):
"digits of the number n"
dig = []
while n>0:
n,d = divmod(n,10) # this do both n//10 and n%10
dig.append(d)
return dig
def sum_digits(n):
s = sum(digits(n)) #sum add together all the elements in the list
while s>10:
s = sum(digits(s))
return s
or even more simple, use a more direct approach to get it, as this is also know as the digital root of the number
def digital_root(n):
if n==0:
return 0
else:
return 1 + (n-1)%9
and some quick test
>>> digits(100)
[0, 0, 1]
>>> digits(88888888888)
[8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8]
>>> sum_digits(88888888888)
7
>>> digital_root(88888888888)
7
>>>
What is wrong with this code please:
from array import array
import math
def solution(A):
A = array('i')
for i in A:
if i > 0:
digits = int(math.log10(i))+1
elif i == 0:
digits = 1
else:
digits = int(math.log10(-i))+2
if digits == 2:
sum += i
return sum
The task is to write a function that given an array A consisting of N integers, returns the sum of all two digit numbers
This will do the job
import math
def solution(A):
#A = array('i')
sumofarr=0
for i in A:
if i != 0:
digits = int(math.log10(math.fabs(i)))+1
if digits == 2:
sumofarr += i
return sumofarr
solution([12,3,45]) #output 57
Note that there is no need to separate between positive and negative numbers. Just take the absolute value. Also, you need to initialize the sumofarr variable at the beginning. Also it is better not to use sum as a name for variable, as this is already used as a name of function in python.
the problem with your code is that you don't initialize sum, don't have the correct indentation, overwrite the input argument and the check if a number is of 2 digit is more complicate that it need to be
here is a more simple version
def mysum(A):
total = 0
for i in A:
if 10 <= abs(i) < 100: # abs if you want to include negative numbers
total += i
return total
test
>>> test = [1, 2, 10, 80, 20, -10, -20, 500]
>>> mysum(test)
80
or with the build-in sum and a generator expression
>>> sum( i for i in test if 10 <= abs(i) < 100 )
80
>>>
I'm trying to find the avg of list but only when n >= 10 (two digit numbers, my original list is limited to 100).
Here's what I have right now:
# Calculate average of all two-digit numbers (10-99)
grade_list = [10, 11, 12, 13, 14, 15]
def calcAvg(grade_list):
while n > 10:
total = sum(grade_list)
n = total % len(grade_list)
print_list = n
return print_list
I get that I have to find the total sum of the list when n > 10 and then dividing by the length (only > 10, my original list has single digit elements, so I'd like to avoid them).
But when I run it, I get an error saying: local variable 'n' referenced before assignment
Any help on how to structure this function to achieve the end results (sum/total of only 2-digit elements = avg)
Thanks!
I'd either collect the good grades and use sum/len, or use the mean function:
>>> grade_list = [1, 2, 10, 11, 12, 13, 14, 15]
>>> good = [g for g in grade_list if g > 10]
>>> sum(good) / len(good)
13.0
>>> import statistics
>>> statistics.mean(g for g in grade_list if g > 10)
13.0
def calcAvg(grade_list):
my_list = []
total, count = 0,0
for n in grade_list:
if 10 <= n <= 99:
total += n
if not total:
return None
return total/count
Here is a clean way of doing it:
def calc_avg(lst):
filtered_lst = filter(lambda x: 10 < x < 100, lst)
return sum(filtered_lst) / len(filtered_lst)
So you should use a for loop instead of a while loop. Instead of having two for loops and making a new list, you could just account for the sum inside the first for loop. I demonstrate this below.
def calcAvg(grade_list):
sum = 0;
count = 0;
for n in grade_list:
if 10 <= n <= 99:
sum = sum + n
count = count + 1
return sum/count
I think you should manually go over the code step by step and try to understand what is wrong. Meanwhile this may give you some hints
# Calculate average of all two-digit numbers (10-99)
def calcAvg(alist):
count=total=0
for i in alist:
if 9 < i < 100:
total += i
count += 1
return total/count
Since Python 3.4 there is a statistics module.
So you just need to filter out numbers in range <10,100), for example with a list comprehension, and then pass this filtered list to the mean function. Simple as that.
from statistics import mean
numbers = [1, 20, 30, 50]
mean([n for n in numbers if n >= 10 and n < 100])
>>> 33.333333333333336
You could do this fairly simply with a list comprehension
>>> grades = [1, 2, 10, 11, 12, 13, 14, 15, 120, 122, 320]
>>> lst = [v for v in grades if 10 <= v < 100]
>>> sum(lst)/len(lst)
12