The task is to find the number of odd numbers in an integer.
count_odd_digits(n):
Given a non-negative integer, count how many digits of it are odd numbers.
example:
count_odd_digits(123450) → 3 #digits 1,3, and 5 are odd
I have so far:
def count_odd_digits(n):
ans = 0
for i in str(n):
if int(n) %2 == 1:
ans += 1
elif n[i]==0:
return None
But I am still failing my tests, what is going wrong in my code?
You have several problems:
elif n[i] == 0: return None is completely useless. You never want to return None; you just want to continue. Since all you are doing is continuing, it can just be removed.
if int(n) % 2 == 1 is testing the wrong thing. You want to check int(i), not int(n).
Change the code to this:
def count_odd_digits(n):
ans = 0
for i in str(n):
if int(i) % 2:
ans += 1
return ans
It would be easier to use a generator expression:
def count_odd_digits(n):
return sum(int(i) % 2 for i in str(n))
The return None part will immediatly terminate your function. Also you should convert i to an integer not the complete string.
A working function could look like this:
def count_odd_digits(n):
ans = 0
for i in str(n):
if int(i) %2 == 1:
ans += 1
# drop the elif part
# return after the for loop
return ans
count_odd_digits(123450)
Change int(n) to int(i)
def count_odd_digits(n):
ans = 0
for i in str(n):
if int(i) %2 == 1:
ans += 1
return ans
Another solution is to avoid converting to strings at all, and only use integers:
def count_odd_digits(n):
ans = 0
while n:
digit = n % 10
if digit % 2:
ans += 1
n //= 10
return ans
Related
I've worked a lot on this but I can't figure out the problem. Can you help me?
The code should print numbers from 0 to 100 and print next to the prime numbers "Prime". The first function works but if I try to print the numbers all togheter the "prime" tag gets misplaced.
def testPrime(numTest):
if numTest <= 1:
return False
if numTest == 2:
return True
for i in range(2, numTest):
if (numTest % i) == 0:
return False
else:
return True
def printPrimes (lenght):
i = 0
while i <= lenght:
if testPrime(i):
print(str(i) + "Prime")
else:
print(str(i))
i += 1
printPrimes(100)
The logic in testPrime() is flawed. There are faster techniques but here's a trivial approach that may help:
def testPrime(n):
if n < 2:
return False
if n == 2:
return True
if n % 2 == 0:
return False
for i in range(3, int(n**0.5)+1, 2):
if n % i == 0:
return False
return True
Since a prime number is defined a number a natural number greater than 1 that is not a product of two smaller natural numbers
I think this is the only lines you need.
def testPrime(n):
for i in range(2,n):
if n%i == 0:
return False
return True
def prime(upper):
while upper >=2:
for num in range(2, upper + 1):
prime = True
for i in range(2, num):
if (num % i == 0):
prime = False
if prime:
print(num, end=",")
if num == upper: #I think there is a problem here
break
prime(7)
How can I stop this function when it reachs 7 value
PS: I want to execute this codes with while loop.
BTW if you can make it this codes without for-loop please do it for me :)
I appreciate you...
EDIT:
I guess my previous is_prime function is problematic. This way is quicker and works well:(Source)
def is_prime(n):
""""pre-condition: n is a nonnegative integer
post-condition: return True if n is prime and False otherwise."""
if n < 2:
return False;
if n % 2 == 0:
return n == 2 # return False
k = 3
while k*k <= n:
if n % k == 0:
return False
k += 2
return True
You should use this function.
BEFORE EDIT:
I would use the is_prime function from here. You can use another way.
And, I would suggest this code for you:
def is_prime(Number):
return 2 in [Number, 2**Number%Number]
def prime(upper):
print([num for num in range(2, upper + 1) if is_prime(num)])
prime(7)
Output:
[2, 3, 5, 7]
But if you insist on using only while loop, you can modify your prime function as:
def prime(upper):
num = 2
while num <= upper:
if is_prime(num):
print(num, end = ",")
num += 1
Then, output will be:
2,3,5,7,
I'm trying to write a program that finds if a given number is in the Fibonacci sequence and I keep getting recursion that doesn't terminate and I'm not sure why. Line 17 seems to be the big problem. When I input 0 or 1 I get the desired answers. Just looking for help getting to an answer, I'm trying to learn so just telling me the answer doesn't help me much.
number = int(input("Enter your number:"))
def fib(n):
if n == 0 or n == 1:
return 1
else:
return (fib(n-1) + fib(n-2))
def isfib(number):
n = 0
if number < 0:
print("Invalid input")
elif number == fib(n):
print("Number is in the sequence")
elif number < fib(n):
print("Number is not in the sequence")
elif number > fib(n):
n = n +1
isfib(number) #where the problem occurs
isfib(number)
There are many little mistakes so i corrected those(I have added a better implementation of Fibonacci code with simple addition too):
number = int(input("Enter your number:"))
def fib(n):
if n == 0 or n == 1: return 1
else:
temp1=1
temp=2
temp3=0
for z in range(n-2):
temp3=temp
temp+=temp1
temp1=temp3
return temp
def isfib(number): #it is ok not to return anything unless you need to stop the function in between
done=0
n=0
while done!=1:
if number < 0:
print("Invalid input")
done=1
elif number == fib(n):
print("Number is in the sequence")
done=1
elif number < fib(n):
print("Number is not in the sequence")
done=1
elif number > fib(n):
n = n +1
#i have used done instead of return to show the function can exit even if you dont return a value
#you can just 'return' instead of changing done variable and making the loop infinite
isfib(number)
Since you have used lot of recursions, i am guessing you want to do it only by using recursions. So, the code will be like this:
number = int(input("Enter your number:"))
def fib(n):
if n == 0 or n == 1: return 1
else: return (fib(n-1) + fib(n-2))
def isfib(number,n=0):
if number < 0: print("Invalid input")
elif number == fib(n): print("Number is in the sequence")
elif number < fib(n): print("Number is not in the sequence")
elif number > fib(n):
n = n +1
isfib(number,n)
isfib(number)
Tested of course, it works(but again i wouldn't recommend it this way :D)
Your fib function is wrong (one of the terms should be n-2)
The last elif of the isfib() function is not returning a call of itself,i.e it is calling itself and not doing anything with that result.
Put simply, you are calling isfib(number) with the very same number you were given originally. Your "n = n + 1" just before that suggests that maybe you wanted to call isfib(n) not isfib(number).
Basically isfib(number) is just an infinite loop.
I don't really know why you want to use recursive to solve this question. When you get a number, you don't know what are n-1 and n-2. Therefore, you cannot recursive on n-1 and n-2. The following example can easily check the number is in Fibonacci sequence or not:
number = int(input("Enter your number:"))
def fib(n):
ni = 1
ni_minus_1 = 0
while ni + ni_minus_1 < n:
temp = ni_minus_1
ni_minus_1 = ni
ni = ni + temp
if ni + ni_minus_1 == n:
return True
return False
print(fib(number))
update
I guess you want to build the sequence by recursive. For example, given number is 5, you want to return the 5th element in Fibonacci sequence. Then the code would be like the following:
def build_fib(n):
if n == 0:
return 0
if n == 1:
return 1
return build_fib(n-1) + build_fib(n-2)
print(build_fib(6))
I'm a beginning programmer in python and have a question about my code I'm writing:
number = int(input("Enter a random number: "))
for num in range(1, number + 1) :
for i in range(2, num) :
if (num % i) == 0 :
break
else :
print(num)
break
When I run this program I also get 9, 15 21 as output. But these are not prime numbers.
What is wrong with my code?
Thanks!
With if (num % i) == 0: you go to the else block for every num, which is not a multiply of 2, as you start i with 2, thus printing num. I got all odd numbers printed with your code.
You can use something like this:
number = int(input("Enter a random number: "))
for num in range(1, number + 1):
prime = True
for i in range(2, num):
if (num % i) == 0:
prime = False
break
if prime:
print(num)
It sets prime to False when it encounters a divisor without rest.
the trouble is in your else: statement which has to run outside of the first loop. I recommend the following:
def isprime(num):
for i in range(2, num):
if (num % i) == 0:
return False
return True
for num in range(1, number + 1) :
if isprime(num):
print num
Your problem
The else statement that you put inside the for loop means that if that number(num) is divisible by this current no represented by i, return true considering it as a prime which IS NOT CORRECT.
Suggestion
Your outer loop starts with 1 which should change to 2, as 1 is not a prime number
Solution
def fun(number):
#Not counting 1 in the sequence as its not prime
for num in range(2, number + 1) :
isPrime = True
for i in range(2, num) :
if (num % i) == 0 :
isPrime = False
break
if isPrime:
print num
fun(10)
Output
1
2
3
5
7
I am assuming the random number is the range you want the numbers to be within.
I found that the variable i is always equal to 2 in your code.This destroys the purpose of having a second for loop
Prime numbers are numbers that cannot be divisible by 2, 3 or 7, excluding 2, 3 or 7!
With this knowledge I adapted your code to show the true prime numbers.
solution
number = int(input("Enter a random number: "))
for num in range(2,number +1) :
printnum = True
if num == 2:
printnum = True
elif num == 3:
printnum = True
elif num == 7:
printnum = True
elif num % 2 == 0:
printnum = False
elif num % 3 == 0:
printnum = False
elif num % 7 == 0:
printnum = False
if printnum == True:
print(num)
This is my method to generate first ten prime numbers with no imports, just simple code with components we are learning on college. I save those numbers into list.
def main():
listaPrim = []
broj = 0
while len(listaPrim) != 10:
broj+= 1
brojac = 0
for i in range(1,100):
if broj % i == 0:
brojac += 1
if brojac == 2:
listaPrim.append(broj)
print(listaPrim)
if __name__=='__main__':
main()
I wrote a code in python to find the nth prime number.
print("Finds the nth prime number")
def prime(n):
primes = 1
num = 2
while primes <= n:
mod = 1
while mod < (num - 1):
ptrue = 'true'
if num%(num-mod) == 0:
ptrue = 'false'
break
mod += 1
if ptrue == 'true':
primes += 1
return(num)
nth = int(input("Enter the value of n: "))
print(prime(nth)
The code looked fine to me, but it returns an error when I run it:
Traceback (most recent call last):
File "C:/Users/AV/Documents/Python/nth Prime.py", line 17, in <module>
print(prime(nth))
File "C:/Users/AV/Documents/Python/nth Prime.py", line 13, in prime
if ptrue == 'true':
UnboundLocalError: local variable 'ptrue' referenced before assignment
It appears to me as if it is trying to say that I am referring to ptrue in the last line even though I am not. What is the problem here... Can anyone help?
how about using Boolean ? and initalize ptrue out of while loop
print("Finds the nth prime number")
def prime(n):
primes = 1
num = 2
while primes <= n:
mod = 1
ptrue = True
while mod < (num - 1):
if num%(num-mod) == 0:
ptrue = False
break
mod += 1
if ptrue == True:
primes += 1
return(num)
nth = int(input("Enter the value of n: "))
print prime(nth)
ptrue is local to your while loop which goes out of scope as soon as the while loop ends. so declare ptrue before the start of your inner while loop
Get rid of ptrue entirely and use else with your inner loop. For example:
while mod < (num - 1):
if num % (num - mod) == 0:
break
mod += 1
else:
primes += 1 # only executes if loop terminates normally, without `break`
You can try this:
#This program finds nth prime number
import math
def is_prime(number):
if number < 2:
return False
if number % 2 == 0:
return False
else:
for i in range(3, number):
if not number % i:
return False
return True
n = input('Enter n: ')
#This array stores all the prime numbers found till n
primes = []
for i in range(100000):
if is_prime(i):
primes.append(i)
if len(primes) == n:
break
print("nth prime number is: " + str(primes[n-1]))
The first part is define a function that calculates the next prime number given any number.
import math
def is_prime(x): # function
for i in range(2,int(math.sqrt(x))+1):
if x%i == 0:
return is_prime(x+1)
return x
For example, is_prime(10) will return 11.
The next step is to write a generator that returns a list of prime numbers.
def get_prime(k): # generator
cnt = 1
n = 2
while cnt <= k:
yield(is_prime(n))
n = is_prime(n) + 1
cnt += 1
For example, get_prime(5) will return [2,3,5,7,11].
The code below can help you test the results.
a = get_prime(50)
lists = list(a)[:]
for idx, value in enumerate(lists):
print("The {idx}th value of prime is {value}.".format(idx = idx+1, value = value))
All answers depends on user input, but here is a simple code to give nth number, no matter how big the n is ....
def isprime(n): # First the primality test
if n<2:
return False
for i in range(2,n):
if n%i==0:
return False
break
else:
return True
def nthprime(n): # then generic code for nth prime number
x=[]
j=2
while len(x)<n:
if (isprime(j)) == True:
x.append(j)
j =j+1
print(x[n-1])
n=int(input('enter n'))
a=[2,3,5,7]
i=3
j=9
while i<n:
flag=0
j=j+2
for k in range(len(a)):
if (a[k]<=int(j**0.5) and j%a[k]==0):
flag=1
break
if flag==0:
a=a+[j]
i=i+1
print(a[n-1])
Try this.
n = int(input())
count=1
u=2
prime=[]
while(count<=n):
temp=0
for i in range(2,u):
if(u%i==0):
temp=1
if(temp==0):
count+=1
prime.append(u)
u+=1
print(prime[-1])
Program to find nth Prime Number.
def nth_Prime(num):
Semi = num*num
Res_1 = [True for i in range(Semi+1)]
prime = 2
while prime*prime <= Semi:
if Res_1[prime] == True:
for i in range(prime*prime, Semi+1, prime):
Res_1[i] = False
prime += 1
Res_2 = []
for i in range(2, Semi+1):
if Res_1[i]:
Res_2.append(i)
return Res_2[num-1]
if __name__ == "__main__":
num = int(input("Enter nth Number: "))
print(nth_Prime(num))
Try this out ,I just made few changes in yours.
Here I am checking for each prime number using all(num%i!=0 for i in range(2,num)) checking its remainder not equal to zero so if it is true for that range (starting from 2 and less than itself) it is a prime and for that all() function helps me later if its a prime I increment the 'p' count and check till 'p' is less than the 'n'(Input Number) so when it equates the condition its the nth prime we are looking for.
n=raw_input("enter the nth prime ")
num=4
p=2
while p <int(n):
if all(num%i!=0 for i in range(2,num)):
p=p+1
num=num+1
print "nTH prime number: ",num-1