List Index out of range, trying to get the [-1] position - python-3.x

I've tested to see if the list is empty and I'm sure it's not empty. So why this error continues?
The code is to find the smallest amount of factorial to a sum is equal to N.
def fat(n):
if n == 0 or n == 1:
return 1
else:
return n * fat(n - 1)
n = int(input())
ns = [x+1 for x in range(n)]
listaFat = []
l = []
for x in ns:
if fat(x) < n:
listaFat.append(x)
maior = max(listaFat)
listaFat.remove(maior)
print(listaFat)
print(len(listaFat))
while (fat(listaFat[-1]) + fat(maior)) < n:
l.append(listaFat[-1])
if len(listaFat) > 0:
listaFat.remove(listaFat[-1])
continue
else: break
print(l)
print(listaFat)

Related

658. Find K Closest Elements - for loop 'comp' comparison variable not updating as expected

So I am working on problem 658 'Find K Closest Elements'(https://leetcode.com/problems/find-k-closest-elements/), which asks to return a list from the given list, 'arr'. This return list will be the length of 'k' and will contain the 'k' # of values closest to the given 'x' value. I've created all the base cases and constraints, and am now stuck on the comparison part below:
I've created an empty list, 'a'. While the length of 'a' is not 'k', the function will go through the list and compare abs(i - x) < abs(comp - x), 'comp' starting at 'arr[0]' and updating to 'i' if the comparison is true. The problem is that the comparison is not working correctly. Here is an example case I'm trying to figure out:
arr = [1,1,1,10,10,10], k = 4, x = 9
Below is the portion of the code I am focusing on:
a = []
comp = arr[0]
iteration = 0
i_index = 0
while len(a) != k:
for i in arr:
comp_1 = abs(i - x)
comp_2 = abs(comp - x)
if comp_1 < comp_2:
comp == i
print(f"comp: {comp}")
arr.pop(arr.index(comp))
a.append(comp)
return a
I am including the entirety of the code just in case below:
def findClosestElements(self, arr: List[int], k: int, x: int) -> List[int]:
# Constraints
if k < 1 or k > len(arr):
return "k must be greater than 0 and less than the arr length"
if len(arr) < 1 or len(arr) > 10**4:
return "arr length must be greater than 0 and less than 10^4"
if x > 10**4:
return "x must be less than 10^4"
if sorted(arr) != arr:
return "arr must be sorted"
for i in arr:
if i < -10**4:
return "arr item cannot be less than -10^4"
#Variables 1
begin = arr[:k]
end = arr[-k:]
# Base cases
if len(arr) == k:
return arr
if x < arr[0]:
return begin
elif x > arr[-1]:
return end
try:
x_index = arr.index(x)
half_k = int(k/2)
#if k == x and x_index != None:
# return [x]
# Captures all other lists that begin at arr[0] or end at arr[-1]
if x_index - half_k < 0:
return begin
elif x_index + half_k > len(arr) - 1:
return end
# Create list out of interior of arr if necessary
else:
return arr[x_index - half_k : x_index + half_k]
# Means x is not in arr
except ValueError:
a = []
comp = arr[0]
iteration = 0
i_index = 0
while len(a) != k:
for i in arr:
print(f"{iteration} - {i_index}:")
print(f"i: {i}")
print(f"comp_1: {abs(i - x)}")
print(f"comp_2: {abs(comp - x)}")
comp_1 = abs(i - x)
comp_2 = abs(comp - x)
if comp_1 < comp_2:
comp == i
print(f"comp: {comp}")
i_index += 1
print("\n")
iteration += 1
arr.pop(arr.index(comp))
a.append(comp)
return a
I would take the approach of:
finding the shortest distance from x to the elements of arr.
sorting arr by the distances.
So, this is a good method:
arr = [1,1,1,10,10,10]
k = 4
x = 9
distances = [abs(x - n) for n in arr]
Z = [a for _,a in sorted(zip(distances,arr))]
print(Z[:k])
result
[10, 10, 10, 1]

Why does my code stop after the first test case? (Problem -- https://www.hackerearth.com/practice/codemonk/)

Please review my code for the problem given in the title, it stops after showing correct output for the first test case and shows Runtime error if I put t > 1 in Hackerearth IDE.
t = int(input())
while t > 0:
t = t - 1
n, k = map(int, input().split())
A = [int(i) for i in input().split()]
p = []
if k > n:
k = k - n
elif k == n:
k = 0
else:
k = k
for j in range(k):
x = A.pop()
p.append(x)
p = p[::-1]
for j in range(len(A)):
p.append(A[j])
print(*p)

solve n which is an integer above 0 in python

This code works but it is not very efficient is there any help on a faster code in python to find n knowing that n is an integer above 0 and that n has no upper bound, how(x) will return you 1 if x>n, 0 if x = n, and -1 if x
def how(x):
if x > n:
return 1
elif x < n:
return -1
else:
return 0
def find(how):
if how(1) == 1:
return 1
x = 2
while how(x) != 1:
x = x**x
v = x
while how(x) != 0:
if how(x) == 1:
v = x
x = (x+1)//2
else:
x += (v-x+1)//2
return x
Rebecca, I've added some print statements so you can see where goes what wrong. As Patrick Artner said... its a bit confusing which way to go so I've tried to clean-up some things that enable you to continue exploring comparison of two variables against each other (and fake error catching (0).
Lets start and remove the confusing lingo and produce something workable code. With current below script it runs and with value = 1, reference = 1 you get the below print result in a continues loop until YOU stop the script manually:
v1 = n: error
loop1 1
def selector(v1, n):
if v1 > n:
print 'v1 > n', v1, n
return 1
elif v1 < n:
print 'v1 < n', v1, n
return -1
else:
print 'v1 == n: error'
return 0
def find(value, reference):
if selector(value, reference) == 1:
return 1
while selector(value, reference) != 1:
x = value**value
print 'loop1', x
v = x
while selector(value, reference) != 0:
print 'loop2'
if selector(value, reference) == 1:
v = value
x = (value+1)/2
print 'loop2-if', v, x
else:
x += (v-(value+1))/2
print 'loop2-else', x
print ' Almost done...'
return x
if __name__ == '__main__':
n = 1
print find(1, 1)
Happy exploring,....

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