Why my code does't execute this statement : int(n)? - python-3.x

This code is to convert decimals to binary.
What I'm trying to do is to chop off the decimal part after diving by 2.
binary = []
n = 25
while n != 0:
binary.append(n % 2)
n = n / 2
int(n) #this part
print(binary)
print(n)
choose = input("continue?[Y/N]")
if choose == 'y':
continue
else:
break
print(list(reversed(binary)))

Is this what you want?
binary = []
n = 25
while n != 0:
binary.append(n % 2)
n = n / 2
n = int(n) #assign result to n
print(binary)
print(n)
choose = input("continue?[Y/N]")
if choose == 'y':
continue
else:
break
print(list(reversed(binary)))

Related

Prime counter program debug

I'm trying to write a program that counts the number of primes in a given interval
I came up with this:
def check_primes(numb):
if numb == 2 :
return True
n = 2
while n < numb:
if numb % n != 0:
return True
else:
return False
def count_primes(num) :
count = 0
for m in range(2,num) :
if check_primes(m) == True :
count += 1
return count
but when I try count_primes(100) I get 50 instead of 25, for some reason. Can anyone explain to me what's wrong in there?
In your while, you are not increasing n. Your method runs for just n=2 and that's it.
So, just add n += 1 to your while:
def check_primes(numb):
if numb == 2 :
return True
n = 2
while n < (numb // 2) + 1:
if numb % n != 0:
n += 1
else:
return False
return True
Also note that there is not need to check all numbers to numb. You can do check it till numb/2 and that would be enough.

Why is my simple code taking so much time to execute when i give in large numbers as input?

I have written a simple code to print the largest prime factor of a given number from Project Euler. It works just fine for numbers like 24, but there is no response from the python shell for large numbers!
a=600851475143
b=[]
for i in range(2,600851475143):
if a%i==0:
if i==2:
b.append(i)
continue
for j in range(2,i+1):
if j==i:
b.append(i)
if i%j==0:
break
print(max(b))
print(b)
You can use an algorithm like this to get large factors of prime numbers:
import math
def LLL(N):
p = 1<<N.bit_length()-1
if N == 2:
return 2
if N == 3:
return 3
s = 4
M = pow(p, 2) - 1
for x in range (1, 100000):
s = (((s * N ) - 2 )) % M
xx = [math.gcd(s, N)] + [math.gcd(s*p+x,N) for x in range(7)] + [math.gcd(s*p-x,N) for x in range(1,7)]
try:
prime = min(list(filter(lambda x: x not in set([1]),xx)))
except:
prime = 1
if prime == 1:
continue
else:
break
return N/prime

What am I doing wrong with this code for hackerrank?

I have been coding this problem for HackerRank and I ran into so many problems. The problem is called "Plus Minus" and I am doing it in Python 3. The directions are on https://www.hackerrank.com/challenges/plus-minus/problem. I tried so many things and it says that "there is no response on stdout". I guess a none-type is being returned. Here is the code.:
def plusMinus(arr):
p = 0
neg = 0
z = arr.count(0)
no = 0
for num in range(n):
if arr[num] < 0:
neg+=1
if arr[num] > 0:
p+=1
else:
no += 1
continue
return p/n
The following are the issues:
1) variable n, which represents length of the array, needs to be passed to the function plusMinus
2) No need to maintain the extra variable no, as you have already calculated the zero count. Therefore, we can eliminate the extra else condition.
3) No need to use continue statement, as there is no code after the statement.
4) The function needs to print the values instead of returning.
Have a look at the following code with proper naming of variables for easy understanding:
def plusMinus(arr, n):
positive_count = 0
negative_count = 0
zero_count = arr.count(0)
for num in range(n):
if arr[num] < 0:
negative_count += 1
if arr[num] > 0:
positive_count += 1
print(positive_count/n)
print(negative_count/n)
print(zero_count/n)
if __name__ == '__main__':
n = int(input())
arr = list(map(int, input().rstrip().split()))
plusMinus(arr, n)
The 6 decimals at the end are needed too :
Positive_Values = 0
Zeros = 0
Negative_Values = 0
n = int(input())
array = list(map(int,input().split()))
if len(array) != n:
print(f"Error, the list only has {len(array)} numbers out of {n}")
else:
for i in range(0,n):
if array[i] == 0:
Zeros +=1
elif array[i] > 0:
Positive_Values += 1
else:
Negative_Values += 1
Proportion_Positive_Values = Positive_Values / n
Proportion_Of_Zeros = Zeros / n
Proportion_Negative_Values = Negative_Values / n
print('{:.6f}'.format(Proportion_Positive_Values))
print('{:.6f}'.format(Proportion_Negative_Values))
print('{:.6f}'.format(Proportion_Of_Zeros))

Logic to find out the prime factors of a number

I have created the below script to find out the prime factors of a number :
def check_if_no_is_prime(n):
if n <= 3:
return True
else:
limit = int(math.sqrt(n))
for i in range(2,limit + 1):
if n % i == 0:
return False
return True
def find_prime_factors(x):
prime_factors = []
if check_if_no_is_prime(x):
prime_factors.append(1)
prime_factors.append(x)
else:
while x % 2 == 0 and x > 1:
prime_factors.append(2)
x = x // 2
for i in range(3,x+1,2):
while x % i == 0 and x > 1:
if check_if_no_is_prime(i):
prime_factors.append(i)
x = x // i
if x <= 1:
return prime_factors
return prime_factors
no = int(input())
check = find_prime_factors(no)
print (check)
I am not sure whether this is the best and efficient way to do this ?
Can someone please point out any better way to do this ?
using sieve of erathnostanes to get all prime numbers from 2 to whatever limit inputted
def sieve(N):
from math import floor,sqrt
A=[1 for x in range(N+1)]
for count in range(2):
A[count]=0
for i in range(floor(sqrt(N))+1):
if A[i]==1:
for k in range(i*i,N+1,i):
A[k]=0
ans=list(enumerate(A))
res=[]
for (i,j) in ans:
if j==1:
res+=[i]
return res
print(sieve(100))
#my code

The result is coming back correct but not in correct format

I am doing an assignment and the answers are coming back correctly but I would need them to say 5! = 120 instead of just = 120. How would I go about that?
def getInt():
getInt = int
done = False
while not done:
print("This program calcultes N!")
# get input for "N
N = int(input("Please enter a non-negative value for N: "))
if N < 0:
print("Non-Negative integers, please!")
else:
done = True
return N
def main():
n = getInt()
for i in range(n-1):
n = n * (i+1)
print("=" ,n)
main()
I hope this code will help.
print('Enter a positive integer')
a = int(input())
def factorial(n):
if n == 0:
return(1)
if n == 1:
return(1)
if n > 1:
return(n * factorial(n-1))
if a < 0:
print('Non-Negative integers, please!')
if a >= 0:
print(str(a) + '! = ' + str(factorial(a)))
In the for i in range(n-1)you could use another integer instead of n just to be sure things don't mess up and you can print like joel said print(i,"!=", n) but instead of n the integer you will use.
can you show me your homework instructions?
i'm not sure what the first value is in your example.. the current iteration or the original number entered?
# declare getInt()
def getInt():
getInt = int
done = False
while not done:
# write "this program calculates N!"
print("This program calcultes N!")
# get input for "N
N = int(input("Please enter a non-negative value for N: "))
# if N < 0 then
if N < 0:
print("Non-Negative integers, please!")
# else
else:
# done = true
done = True
# return N
return N
# main
def main():
n = entry = getInt()
for i in range(n-1):
n = n * (i+1)
print("{0}! = {1}".format(entry, n))
main()
results:
/*
This program calcultes N!
Please enter a non-negative value for N: 5
5! = 120
*/

Resources