How to count the length of integer using recursion - python

I've been trying to find how do I do check the length of integer using recursion. For example: 100, it will say that there's 3 number. 12, it will say that there's 2 number.
What I've saw online is all about the summation of the last digit. I couldn't source for help on the length of an integer.
can someone help me out on this?
I've tried to use lens to count, but my output is always 0.
def num(x):
if x == 0:
return 0
else:
return num(x / 10)
print len(str(num(100)))
I've also tried this
def num(x):
if x == 0:
return 0
else:
return num(x / 10) + len(str(x % 10))
print num(100)

You need to add 1 with num(N/10) if N is not 0 :
>>> def num(N):
... if N==0:
... return 0
... return 1+num(N/10)
...
>>> num(100)
3
This code will add ones in each calling the function with N/10 until it get to 0, so at the end based on what time your number can bi divide by 10 you'll have 1's which have been sum together, and at last for 0 they eill be add with 0.
For example for 100 your function will do the following :
1+(100/10)
^
1+1+(10/10)
^
1+1+1(1/10)
^
1+1+1+0

Are you looking for this -
def numlen(i):
if i:
return numlen(i//10) + 1
return 0

Related

How can I reduce my execution time for this code?

import math
class Solution:
def countSquares(self, N):
list = []
count = 0
for i in range(1,(int)(math.sqrt(N))):
square = i ** 2
list.append(square)
count = count + 1
return count
I am trying to count the number of perfect squares that are less than a given 'N'.
For example, if N = 9, the output is 2. Because only 1 & 4 are the perfect squares present.
list(map(lambda x:x*x, range(1,1+int(math.sqrt(n-1)))))
I think this should do it.
math.ceil(math.sqrt(n)) - 1
math.sqrt will output the square root of the current number.
math.ceil converts that number into the next whole number.
- 1 gives you the previous whole number, which is also the (inclusive) count of whole numbers which can be squared to a number less than n.
If you need to get the list of the square roots instead of the count the modifications are simple.
list(range(1, math.ceil(math.sqrt(n))))
In this case - 1 doesn't need to be performed so range ends with the correct number.
count = 0
for i in range(1, X):
#...
count = count + 1
ends with count == X - 1. Therefore, you don't really need a loop. You also never actually use the list, so storing it will slow down the program further.
sq = math.sqrt(N)
if math.floor(sq) < sq <= math.ceil(sq):
return int(sq)
return int(sq) - 1
Try this:
import math
class Solution:
def countSquares(self, N):
n = math.floor(math.sqrt(N))
if n * n == N:
return n - 1
else:
return n

Print all the 3 consecutive digits that can be equal to a given number

How can I write a recursive backtracking function count(N,S) in which it prints all N-digit numbers such that the sum of each 3 consecutive digits in the number is exactly equal to S where N will be less than or equal to 10, and is from 0 to 27.
Code:
def count(S):
n = int(S)
if n % 3 == 0:
print(int(n / 3 - 1),int(n / 3),int(n / 3 + 1))
else:
print(None)
S = 27
count(S)
Sample Output:
8 9 10
I'm quite confused on how can I write this recursively.
Your current function is not recursive. To make it recursive, you'd basically have to call count(n-1, s) somewhere within the execution of count(n, s). One way to do it would be like this:
if n > 1, get possible solutions for n-1 and append any digit that still satisfied the condition
if n == 0 just return "" (it's a bit easier if the function returns strings, not actual integers)
As a generator function, this could look somewhat like this. Of course, you can just as well collect the results in a list and return them, or just get the count of such numbers and return that.
def count(n, s):
if n > 0:
for x in count(n-1, s):
for d in range(10):
y = str(d) + x
if len(y) < 3 or sum(map(int, y[:3])) == s:
yield y
else:
yield ""
for x in count(5, 15):
print(x)

How computes the number of integers from start up to

Write a function div_3_5(start, end) that computes the number of integers from start up to, but not including end that are divisible by 3 or 5 using a while loop.
NOTE: I must use a while loop inside a function for this exercise (i understand that a for loop is best).
Examples:
div_3_5(7, 27) evaluates to 9 ( numbers divisible by 3 or 5 in that range: 9,10,12,15,18,20,21,24,25)
I really don't understand why or what I'm doing and can someone to explain where i went wrong.
This is my code so far:
count = 0
def div_3_5(start, end):
while start < end:
if start%3 == 0 or start%5 == 0:
count + 1
start = start + 1
start + 1
return count
This obviously isn't complete or correct and the current error I'm getting is:
Expected Output:
div_3_5(7, 27) -> 9
Test Result: 0 != 9
There a few tips that would help here.
The mod operation % will return the remainder of an object so it a number is divisible by another the mod will be 0, for example 6 % 3 == 0 returns true.
A while loop isn't the best for this opertation, better would be a for loop
for i in range(start, end+1):
This wil fix the infinite loop.
This is how I would write it:
def div_3_5(start, end):
count = 0
for i in range(start, end + 1):
if i % 3 == 0 or i % 5 == 0:
count += 1
return count
start = 1
end = 10
count = div_3_5(start, end)
print(count)
Python has a modulus operator (%) which returns the remainder of A/B (10%4 == 2).
In your case, you would be looking for numbers which have a remainder of 0 when divided by 3 or 5
(i.e x%3 == 0 OR x%5 == 0).
Finally, the last elif where you ask elif start >= end is unnecessary because you stated that as the condition when you created the loop. Instead, try replacing those 2 lines with start = start + 1
The answer i found was:
def div_3_5(start, end):
count = 0
while start < end:
if start % 3 == int() or start % 5 == int():
count += 1
start = start + 1
return count
You need no loops to accomplish this task, here is simple -and fun- mathematical method that Python allows us to implement easily:
- One, create a set from 0 to the end with steps of 3s, i.e. {0,3,6,...end} this will get you all the elements that are divisible 3 within the boundary of your end (while keeping the end not included), in Python, this is done this way: set_of_3=set(range(0,b,3)) simple eh?
- Two, do the same but for the 5s, set_of_5=set(range(0,b,5))
- Three, add these sets together: set_of_all=set_of_3.union(set_of_5)
Now you got all the elements divisible by 3 and 5 from 0 to end, but you don't want that, you want from beginning to end, simply, just remove all numbers from 0 to your beginning from the set_of_all, by: result = set_of_all - set(range(0,a)) and just return the len() of that result. Your complete code:
def div_3_5(start,end):
set_of_3 = set(range(0,end,3))
set_of_5 = set(range(0,end,5))
set_of_all = set_of_3.union(set_of_5)
result = set_of_all - set(range(0,start))
return len(result)
A bit convoluted I know, but fun! At least for me. Hope this helps.
EDITED
Yeah I didn't notice you said you must use while loop, you can do this version of your code:
def div_3_5(start,end):
list = []
while start<end:
if start%3==0 or start%5==0:
list.append(start)
start+=1
return len(list)
Use the power of Python and forget these C-ish methods, and regarding what is wrong with your code, the line:
count + 1 doesn't work in Python, you have to do this: count+=1

Invalid syntax Sum += 1

It says I have invalid syntax at Sum += 1. If my code is incorrect what is a better way to go about counting how many even numbers are in a list?
def countEvens(listOfInts):
'''
- Returns an integer value representing the number of even numbers that
exist in listOfInts.
- Return 0 if listOfInts is not a list type or if no even number exists
in listOfInts.
- Note: elements in listOfInts can contain any data type.
'''
Sum = 0
for x in listOfInts:
if x % 2 == 0:
return Sum += 1
if type(listOfInts) != list:
return 0
In Python you cannot return assignments. And Sum += 1 is an assignment, it assigns Sum + 1 to Sum.
In fact the return isn't just a SyntaxError it's also wrong (in a logical sense), so just remove it:
Sum = 0
for x in listOfInts:
if x % 2 == 0:
Sum += 1
return Sum
Alternatively you can use sum with a generator:
return sum(1 for value in listOfInts if value % 2 == 0)
The syntax error comes from this line, as you say
return Sum += 1
That's because (Sum += 1) is not a valid value to return from a function. It's a separate statement
Keeping your code as close as possible, try this
Sum += 1
return Sum
or, more simply
return Sum+1
As for a more pythonic approach
def countEvens(listOfInts):
return sum( x % 2 == 0 for x in listOfInts )
does the entire thing

Sum of odd numbers using while loop in python

I'm new to programming and was asked to sum odd numbers from 1 to (2*n)-1 using a while loop.
This is my attempt:
def sum_odd_n(n):
while n<2*n:
sum = 0
if n%2==1:
sum = sum+n
return (sum)
May i know my mistake? Any help will be appreciated
The condition while n<2*n: is always true while n >= 0, you'll have an infinite loop. Try the following
def sum_odd(n):
value = 1
total = 0
while value < (2*n) - 1:
if value % 2 == 1:
total += value
value += 1
return total
>>> sum_odd(25)
576
For completeness the more pythonic way to handle this would be using sum with a generator expression
def sum_odd(n):
return sum(i for i in range(1, 2*n -1) if i%2 == 1)
The first hint would be to take a look at your condition in while loop:
while n < 2*n
Notice that this will always be true, because if n>0, then 2*n is always greater. If you need more help, write a comment ;)
UPDATE: I will just tell you what is wrong so if you want to try it out first on your own, stop reading. So basically you need another variable, let's say i that will loop through integers. Then you can do something like this:
def sum_odd_n(n):
i = n
sum = 0
while i < 2*n:
if i % 2 == 1:
sum += i
i += 1
print sum # for python3: print(sum)
>>> def sum_odd_n(n):
... return sum([2 ** i for i in range(0,n,1) ])
...
>>> sum_odd_n(2)
3
>>> sum_odd_n(5)
31
>>>
I'll try to point out the mistakes you have done, and try to offer corrections.
def sum_odd_n(n):
while n<2*n: # n will always be less than ('<') 2*n. For eg, if n=5, 5<10.
sum = 0 # you are resetting the sum at every iteration. We need to take this outside.
if n%2==1:
sum = sum+n
return (sum)
Here's what I think should work.
def sum_odd_n(n):
sum = 0 # sum is initialized here, so that it doesn't reset inside the loop
iterator = 0
while iterator<2*n
if iterator%2==1:
sum = sum+iterator # or sum += iterator
iterator = iterator + 1 # otherwise this will be an infinite loop, as iterator will always be 0.
return sum
Hope this works for you. :-)
This worked for me:
def sum_odd(n: int):
total = 0
for x in range(2*n):
if x%2==1:
total += x
return total

Categories