Difficulty with listing function - python

Write a function named "counting" that takes a list of numbers as a parameter and returns the number of values in the input that are between 29.88 and 48.05 not including these end points. (My code below)
def counting(number):
sum = 0
for x in number:
if (29.88 < x < 48.05):
sum = sum + x
return sum
How do I return the number of values in the input instead of the first number of an input?

your return statement is indented too deep; you should return it after the for loop. also sum is not a good name as it is a built-in function that you overwrite.
and you should add 1 to the sum (you are counting) and not x itself.
you could also try this using the built-in function sum:
def counting(number):
return sum(29.88 < x < 48.05 for x in number)
(this is actually short for sum(1 for x in number if 29.88 < x < 48.05) and works because True is basically 1 and False is basically 0).

Or to be similar to yours:
def counting(number):
c = 0
for x in number:
if 29.88 < x < 48.05:
c += 1
return c
Or can do one-liner, len:
def counting(number):
return len([29.88 < x < 48.05 for x in number])

You could also use filter() on your list to keep only elements that the given function evaluates to true.
def counting(number):
return len(list(filter(lambda x: 29.88 < x < 48.05, number)))

Related

If number is not in list return next highest number + python

I need method of checking whether a number exists is a list/series, and if it does not returning the next highest number in the list.
For example:- in the list nums = [1,2,3,5,7,8,20] if I were to enter the number 4 the function would return 5 and anything > 8 < 20 would return 20 and so on.
Below is a very basic example of the premise:
nums = [1,2,3,5,7,8,20]
def coerce_num(x):
if x in nums:
return print("yes")
else:
return ("next number in list")
coerce_num(9)
If there was a method to do this with pandas dataframe, that would be even better.
Here's one way using standard Python (nums doesn't need to be sorted):
def coerce_num(x):
return min((n for n in nums if n >= x), default=None)
>>> coerce_num(4)
5
>>> coerce_num(9)
20
(added default=None in case no numbers are greater than x)
You can achieve this using the recursive function coerce_num(x + 1) it will add 1 and try to search again.
Method 1
nums = [1,2,3,5,7,8,20]
def coerce_num(x):
if x > max(nums):
return None
if x in nums:
return print("yes", x)
else:
coerce_num(x + 1)
coerce_num(6)
Method 2
nums = [1,2,3,9,7,8,20]
nums.sort()
def coerce_num(x):
for i in nums:
if x == i:
return print("yes", x)
if x < i:
return print("next highest", i)
Assuming a sorted list, use bisect for an efficient binary search:
import bisect
nums = [1,2,3,5,7,8,20]
def coerce_num(nums, x):
return x[bisect.bisect_left(x, nums)]
coerce_num(8, nums)
# 8
coerce_num(20, nums)
# 20
coerce_num(0, nums)
# 1
Assuming input list is pre-sorted prior to passing into the function below.
import numpy as np
def check_num(list_of_nums, check):
# use list comprehension to find values <= check
mask=[num <= check for num in list_of_nums]
# find max index
maxind = np.max(np.argwhere(mask))
# if index is last num in list then return last num (prevents error)
# otherwise, give the next num
if maxind==len(list_of_nums)-1:
return list_of_nums[-1]
else:
return list_of_nums[maxind+1]
nums = [1,2,3,5,7,8,20]
print(check_num(nums, 6))

Creating a function that checks perfect numbers python

I've been trying to create a function that checks for perfect numbers, I've used many of the resources I found here, but they don't seem to work for some reason. In my assignment, I'm required to find different types of numbers in a given range input, but this is the only function that doesn't work properly. This is what I have:
def is_perfect(a): #creates a perfect number checker
sum=0
for i in range(1,a):
if a%1==0:
sum += i
if sum==a:
return True
else:
return False
Change the line from a%1==0 to a%i==0 and your code will work perfectly. Because you've to check that the number is divisible from 1 to a and not only 1. It will return always True until it is not integer. Hence, it will keep adding all nos from 1 to a
A perfect number is any number that has the sum of it's devisors, excluding itself, equal to this number. Like the number six that is divided by 1, 2 and 3 and 1 + 2 + 3 = 6.
def is_perfect(number):
sum_ = sum([x for x in range(1, number) if number % x == 0])
return sum_ == number
is_perfect(6) # Returns True
is_perfect(10) # Returns False
is_perfect(28) # Returns True
I called the variable that sum all the divisors with a underscore because sum is already a function keyword in Python
def isPerfect( n ):
sum = 1
i = 2
while i * i <= n:
if n % i == 0:
sum = sum + i + n/i
i += 1
# If sum of divisors is equal to
# n, then n is a perfect number
return (True if sum == n and n!=1 else False)

Digital Root and Persistence Function

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

Reversing an integer using recursion in Python

While practicing recursion I came across a question to reverse an integer using recursion. I tried to do the question without converting the integer into a string.
I was able to solve the question partially but the output would always come without any of the zeroes from the original input. Below is the code I came up with:
def reverseNumber(n):
if (n//10) == 0:
return n
lastDigit = n%10
ans = reverseNumber(n//10)
nod = 0
for i in str(ans):
nod += 1
return (10**nod)*lastDigit + ans
Upon inspection I could see that this was happening because when lastDigit is 0 it only returned the reversed integer from the recursive call i.e input 4230 will give 324.
But this also meant that all zeroes between the original input would also get removed as we went deeper in the recursive calls.
So please tell me how to modify this code so that zeroes in the original input are not removed while reversing.
You probably need just this:
def rev(n):
if n>0:
return str(n%10)+rev(n//10)
else:
return ''
reverseNumber should return an int and accept positive and negative numbers.
The simplest way to fix your code, without handling negative numbers, is:
def reverseNumber(n):
if n == 0:
return 0
lastDigit = n%10
n //= 10
return int(str(lastDigit) + str(reverseNumber(n))) if n else lastDigit
for test in (0, 123, 120):
print(test, reverseNumber(test))
Prints:
0 0
123 321
120 21
Yes! The reverse of 120 is 21 when you are dealing with int types as opposed to str types.
Another implementation that does handle negative numbers takes a whole different approach:
I have broken this out into two functions. Function rev is a generator function that assumes that it is being called with a positive, non-negative number and will recursively yield successive digits of the number in reverse. reverseNumber will join these numbers, convert to an int, adjust the sign and return the final result.
def reverseNumber(n):
def rev(n):
assert n >= 0
yield str(n % 10)
n //= 10
if n != 0:
yield from rev(n)
if n == 0: return 0 # special case
x = int(''.join(rev(abs(n))))
return x if n >= 0 else -x
tests = [0, 132, -132, 120]
for test in tests:
print(test, reverseNumber(test))
Prints:
0 0
132 231
-132 -231
120 21
For all non-negative n, when n < 10 it is a single digit and already the same as its reverse -
def reverse(n = 0):
if n < 10:
return str(n)
else
return str(n%10) + rev(n//10)
you can also try the following Python3 code. It will cover positive and negative integers to be reversed as integers - not as strings ...
x = int(input("What integer shall be reversed? "))
n = abs(x) # ... to handle negative integers
r = 0 # ... will hold the reversed int.
while n > 0: # Recursion part reversing int.
r = (r * 10) + (n % 10) # using '%' modulo
n = int(n / 10) # and a 'dirty way' to floor
if x < 0: # Turn result neg. if x was neg.
return (r * -1)
else:
return r # Keep result pos. if x was pos.
This approach will leave your zeros in the middle of the integer intact, though it will make any zero at the end of the initial number vanish - rightfully so as integers do not start with a zero. ;))

Chained comparison number range in Python

I have the following function:
def InRange(number):
return 5 <= number >= 1
I want this to say false if the number is not within the range of 1 to 5 using a chain comparison, but cannot seem to get this right.
Any suggestions?
You want it like this:
def InRange(number):
return 1 <= number <= 5
Note that you could also do:
def InRange(number):
return 0 < number < 6
Use this:
1 <= number <= 5
From docs:
x < y <= z is equivalent to x < y and y <= z, except that y is
evaluated only once (but in both cases z is not evaluated at all when
x < y is found to be false).
Your (incorrect)expression is actually equivalent to:
number >=5 and number >= 1
So, it is going to be True for any number between 1 to infinity:
Alternatively you can do (it seemed appropriate based on the function's name):
def InRange(number):
return number in range(1, 6)
For large numbers you should use:
def InRange(number):
return number in xrange(1, 10000000)

Categories

Resources