Here is my code:
def extractEachKth(inputArray, k):
n = []
for i in inputArray:
n.append(i)
for i in range(1, len(n) + 1):
if i % k == 0:
n.remove(n[i-1])
return (n)
print (extractEachKth([1,2,3,4,5,6,7,8,9,10],3))
and here is my error:
Traceback (most recent call last):
File "C:/Users/Harry/Documents/randompythonprograms/editable.py", line 9, in <module>
print (extractEachKth([1,2,3,4,5,6,7,8,9,10],3))
File "C:/Users/Harry/Documents/randompythonprograms/editable.py", line 7, in extractEachKth
n.remove(n[i-1])
IndexError: list index out of range
This : n.remove(n[i-1]) is causing the problem, since you're removing values from the list and looping till len(n) so it won't have same size i.e, length of the list will reduce and will give you index out of bound error, your range is correct.
You can solve it by updating the N whenever you remove a value, like this :
def extractEachKth(inputArray, k):
n = []
for i in inputArray:
n.append(i)
i = 1
N = len(n) + 1
while i < N:
if i % k == 0:
n.remove(n[i-1])
N = len(n) + 1
# or simply
# N -= 1
i += 1
return (n)
print (extractEachKth([1,2,3,4,5,6,7,8,9,10],3))
Related
According to my code which is
def factorial(n):
if n == 0:
return 1
else:
N = 1
for i in range(1, n+1):
if i==1*2*3*...*N:
return(N)
it did not produce n error when i tested with the value zero it give one but with other number i.e 7 it gave this error
TypeError Traceback (most recent call last)
<ipython-input-167-5e0569aed165> in <module>
----> 1 factorial(7)
<ipython-input-166-cef7895a4a43> in factorial(n)
5 N = 1
6 for i in range(1, n+1):
----> 7 if i==1*2*3*...*N:
8 return(N)
TypeError: unsupported operand type(s) for *: 'int' and 'ellipsis'
and the line 7 is the problem
Perhaps something like this would be good?
#!/usr/local/cpython-3.8/bin/python3
import itertools
def factorials_forever():
n = 1
for factor in itertools.count(2):
yield n
n *= factor
def find_which_n(n):
for factorialno, factorial in enumerate(factorials_forever(), start=1):
if factorial > n:
raise ValueError('input not a valid factorial')
if factorial == n:
return factorialno
def main():
# for fact in zip(range(10), factorials_forever()):
# print(fact)
nth = find_which_n(3628800)
print(nth)
main()
HTH.
def factorial(n):
if n == 0:
return 1
else:
N = 1
for i in range(1, n+1):
N *= i
return(N)
so this is the ans you can try it
I am trying to add all even Fibonacci numbers up to 4000000. I have successfully outputted all Fibonacci numbers up to 4000000, but adding all the even ones is becoming a problem for me. So far this is what I tried:
fibonacci = [1, 2]
i = 0
while fibonacci[-1] < 4000000:
fib = fibonacci[-1] + fibonacci[-2]
fibonacci.append(fib)
i += 1
del fibonacci[-1]
result = 0
for x in fibonacci:
if fibonacci[x] % 2 == 0:
result += fibonacci[x]
print(result)
It outputs an error:
IndexError: list index out of range
In the lines:
for x in fibonacci:
if fibonacci[x] % 2 == 0:
result += fibonacci[x]
x is actually the Fibonacci number itself, not an index, and is guaranteed to be outside of the bounds of the fibonacci list. If the code was for x in range(len(fibonacci)):, this would yield the indexes as x.
Change it to:
for x in fibonacci:
if x % 2 == 0:
result += x
or better yet, use a list comprehension:
result = sum(x for x in fibonacci if x % 2 == 0)
print(result)
Furthermore, instead of building an entire list, you could accumulate the sum on the spot as you generate the Fibonacci numbers, which is much more memory-efficient:
def even_fib_sum(n):
total = 0
a = 0
b = 1
while a < n:
if a % 2 == 0:
total += a
a, b = a + b, a
return total
if __name__ == "__main__":
print(even_fib_sum(55))
Or, even better, you can use a generator and drop even, since fib is more generally reusable:
def fib(n):
a = 0
b = 1
while a < n:
yield a
a, b = a + b, a
if __name__ == "__main__":
print(sum(x for x in fib(4000000) if x % 2 == 0))
Note that the Fibonacci series usually begins with 0, 1, 1, 2, 3, 5... rather than 1, 2, 3, 5... but you can adjust this as necessary, along with whether you want to iterate inclusive of n or not.
A small compilation of previous answers
fibonacci = [0, 1]
while fibonacci[-1] + fibonacci[-2] < 4000000:
fibonacci.append(fibonacci[-1] + fibonacci[-2])
print(sum(x for x in fibonacci if x % 2 == 0))
That's how I wrote as a beginner.
#By considering the terms in the Fibonacci sequence whose values do
#not exceed four million,
#find the sum of the even-valued terms.
cache = {}
def fib(n):
if n < 3:
return 1
elif n in cache:
return cache[n]
else:
value = fib(n - 1) + fib(n - 2)
cache[n] = value
return value
tot = 0
for n in range(1, 34):
if fib(n) % 2 == 0:
tot += fib(n)
print(n, ':', fib(n))
print(tot)
I'm working on a program that finds perfect numbers (i.e., 6, because its factors, 1, 2, and 3, add up to itself). My code is
k=2
mprim = []
mprimk = []
pnum = []
def isprime(n):
"""Returns True if n is prime."""
if n == 2:
return True
if n == 3:
return True
if n % 2 == 0:
return False
if n % 3 == 0:
return False
i = 5
w = 2
while i * i <= n:
if n % i == 0:
return False
i += w
w = 6 - w
return True
def mprime(k):
while k < 50:
check = (2**k)-1
if isprime(check) == True:
mprim.append(check)
mprimk.append(k)
print check
k+=1
else:
k+=1
mprime(k)
def isperf(lst):
for i in lst:
prm = (((2**i)-1)(2**i))/(2)
pnum.append(prm)
isperf(mprimk)
print pnum
The first part, that checks if a number is prime, and produces mercenne primes, is working alright. Its the second part I'm having trouble with. I have read that if 2^k - 1 is prime, then ((2^k - 1)(2^k))/2 is a perfect number, so I am using that formula.
The error it gives is
Traceback (most recent call last):
File "python", line 47, in <module>
File "python", line 44, in isperf
TypeError: 'int' object is not callable
Line 47 is isperf(mprimk) and line 44 is prm = (((2**i)-1)(2**i))/(2). Any assistance would be appreciated.
Thanks!
The error clearly states that you are trying to call an int type, which isn't callable.
In practice it means you trying to do something like 123()
And code responsible for it is ((2**i)-1)(2**i) because you forgot * and it should be (((2**i)-1)*(2**i))/(2)
Here is the question:
Let us calculate sum of digits, as earlier, but multiplying each digit by its position (counting from the left, starting from 1). For example, given the value 1776 we calculate such weighted sum of digits (let us call it "wsd") as:
wsd(1776) = 1 * 1 + 7 * 2 + 7 * 3 + 6 * 4 = 60
Here is my code:
digitlist = []
numlist = []
def splitdigit(number):
numlist = []
digitlist = []
numlist.append(number)
while number >= 1:
number = number/10
numlist.append(number)
del numlist[-1]
for ele in numlist:
digitlist.append(ele%10)
return digitlist
# digit part
# test if the split digit work here:
# print (splitdigit(1234)) it works
times = int(input())
raw = raw_input()
string = raw.split()
nlist = []
outbox = []
rout = 0
res = 0
n = 0
for item in string:
nlist.append(int(item))
# print (nlist) [it worked]
for element in nlist:
# check for split method : checked
# formula to make the digit work: n = len(out) | while(n>1): n=n-1
# rout=out[-n]*n res=res+rout(res=0)
n = len(splitdigit(element))
print (n)
res = 0
while n >= 1:
rout = (splitdigit(element)[(n*(-1))]) * n # I HAVEN"T CHECK THIS FORMULA OUT !!!
res = res + rout
n = n + 1
outbox.append(res)
print (outbox)
print(" ".join(str(x) for x in outbox))
And here is my running error:
> 3
9 15 1776
1
Traceback (most recent call last):
File "13.py", line 39, in <module>
rout = splitdigit(element)[(n*(-1))] * n # I HAVEN"T CHECK THIS FORMULA OUT !!!
IndexError: list index out of range
and I checked it in interactive python. I think I am not asking for a item out of range but it gives me this error. I hope someone can help me out. Thank you, love you all.
You are thinking way too complicated.
def wsd(number):
digits = [int(i) for i in str(number)]
result = 0
for index, value in enumerate(digits):
result += (index + 1) * value
return result
print(wsd(1776))
Output:
60
I've a small Python (2.7.10) script, which you can see below.
def numbers_calc(max_num, num_step):
"""Returns every number from 0 to max_num with num_step as step."""
n = 0
l = []
while n < max_num + 1:
l.append(n)
n += n * num_step
return l
n_l = []
n_l.append(numbers_calc(25, 1))
print "Here are the numbers."
print n_l
The function numbers_calc is meant to take all the given args, form a list, and populate it with numbers (with num_step as the step when calculating) before it reaches max_num + 1. The script then does return it's local list named l.
However, every time I run the script, I encounter MemoryError. Here's what Python returned when I ran the script:
Traceback (most recent call last):
File "num.py", line 13, in <module>
n_l.append(numbers_calc(25, 1))
File "ex33.py", line 7, in numbers_calc
l.extend(i)
MemoryError
I tried looking it up, saw nothing helpful. I hope you can help me!
n starts at 0. n += n * num_step adds 0 to n. n never changes, and your loop keeps adding items to the list forever.
Cause n to change somehow.
The issue is in the line -
n += n * num_step
Here, you initialized n as 0 , and then you are multiplying n and num_step , whose result would always be 0 , and then adding it to n . So n always stays at 0 . If you are Try to loop from 0 to max_num+1 for every num_step, you should use range() function, Example -
def numbers_calc(max_num, num_step):
"""Returns every number from 0 to max_num with num_step as step."""
l = []
for i in range(0,max_num + 1,num_step):
l.append(i)
return l
anything times 0 is always going to be 0 so you have an infinite loop settingn = 0 set n to 1 initially:
def numbers_calc(max_num, num_step):
"""Returns every number from 0 to max_num with num_step as step."""
n = 1
l = []
while n < max_num + 1:
l.append(n)
n += n * num_step
print(n)
return l
n_l = []
n_l.append(numbers_calc(25, 1))
Output:
[[1, 2, 4, 8, 16]]
If you want a list of number just use the return value:
nl = numbers_calc(25, 1)
Which will give you [1, 2, 4, 8, 16]
If you actually want every number from 0 to max_num with num_step use += not *= and leave n at 0:
def numbers_calc(max_num, num_step):
"""Returns every number from 0 to max_num with num_step as step."""
n = 0
l = []
while n < max_num + 1:
l.append(n)
n += num_step
print(n)
return l
Or simply return range with a step:
def numbers_calc(max_num, num_step):
"""Returns every number from 0 to max_num with num_step as step."""
return list(range(max_num + 1,num_step))
You should be aware that if the step is not a multiple of max_num then you are not going to get max_num i.e numbers_calc(25, 2) will go to 24 .
Thanks everybody for helping! Didn't even realise I had math problems there. Thank you all! By the way, here's the final version of my script.
def numbers_calc(max_num, num_step):
"""Returns every number from 0 to max_num with num_step as step."""
i = 0
l = []
while i < max_num + 1:
l.append(i)
i += num_step
return l
n_l = numbers_calc(25, 5)
print "Here are the numbers."
print n_l