how do i find the fibonacci sequence of a number . Here Is The code
def fib(n):
for i in range(n):
b = 1
b+=i
print(b)
p = fib(9)
the program just returns the normal sum. how to do this in the easy way
The fibonacci sequence is built by adding the last two values of the sequence, starting with 1,1 (or 0,1 for the modern version). A recursive function does it elegantly:
def fib(n,a=1,b=1):
return a if n==1 else fib(n-1,b,a+b)
n = 10
a, b = 0, 1
while a <= n:
print(a)
a, b = b, a + b
try this using recursion
def fibonacci(n):
if n <= 0:
return 0
elif n == 1:
return 1
else:
return fibonacci(n-1) + fibonacci(n-2)
I am just getting started in Python Programming. I had a problem on checking if a given list contains alternating sequence of primes and perfect squares. The list can start with either a prime or a perfect square. I came up with a solution but it's not efficient as it generates unwanted lists. Is this possible with more efficient Python code?
First I'm creating functions to generate a list of primes as well as perfect squares up to the max value of testing list. Functions squaretest() and primecheck():
def squaretest(num):
sqlist=[]
i=1
while i**2 <= num:
sqlist.append(i**2)
i+=1
return sqlist
def primecheck(num):
primelist=[]
for i in range(2,num + 1):
for p in range(2,i):
if (i % p) == 0:
break
else:
primelist.append(i)
return primelist
Then I am dividing the given list into lists of even index and odd index elements and checking all elements of them against the primelist and the squarelist:
def primesquare(l):
if len(l)==1:
primelist = primecheck(l[0])
sqlist = squaretest(l[0])
return (l[0] in primelist) or (l[0] in sqlist)
else:
ol=[]
el=[]
for i in range(0,len(l),2):
ol.append(l[i])
for p in range (1, len(l),2):
el.append(l[p])
primelist = primecheck(max(l))
sqlist = squaretest (max(l))
return((all(x in primelist for x in el)) == True and (all(y in sqlist for y in ol)) == True) or ((all(x in primelist for x in ol)) == True and (all(y in sqlist for y in el)) == True)
It works.
Any suggestions will be really helpful.
You can use sets to check if all members of a list are in another list.
def primesquare(l):
if len(l) == 0:
return True
primelist = set(primecheck(max(l)))
sqlist = set(squaretest(max(l)))
ol = set(l[::2])
el = set(l[1::2])
odds_are_primes = ol.issubset(primelist)
odds_are_squares = ol.issubset(sqlist)
evens_are_primes = el.issubset(primelist)
evens_are_squares = el.issubset(sqlist)
return (odds_are_primes and evens_are_squares) or (odds_are_squares and evens_are_primes)
I came up with a solution but it's not efficient as it generates
unwanted lists.
Assuming the unwanted lists are the two lists representing the even and odd elements, then we can fix that. (Eliminating the primes and squares list is a whole 'nother problem.) Below is my rework of your code -- we don't create addtional lists but rather with a couple of reusable ranges which are objects that produce integer sequences as needed, but not stored in memory.
Your any() design is efficient in that the arguments are generator expressions, not lists, which are computed as needed. As soon as a flaw is found in the array, the whole thing stops and returns False--it doesn't need to process the rest:
def squares(number):
return {x * x for x in range(int(number ** 0.5) + 1)}
def primes(number):
prime_set = set()
for i in range(2, number + 1):
for p in range(2, int(i ** 0.5) + 1):
if (i % p) == 0:
break
else: # no break
prime_set.add(i)
return prime_set
def primesquare(array):
if not array:
return True # define as the problem demands
length, maximum = len(array), max(array)
odd, even = range(0, length, 2), range(1, length, 2)
prime_set, square_set = primes(maximum), squares(maximum)
return all(array[i] in prime_set for i in even) and all(array[i] in square_set for i in odd) or all(array[i] in prime_set for i in odd) and all(array[i] in square_set for i in even)
I admire #AndreySemakin's set-based solution (+1), and use sets above, but his solution generates the same lists you want to eliminate (just in the form of sets).
I came up with this solution:
def primesquare(lst):
# checking if the first element is either perfect square or a prime
if not lst or (not checksquare(lst[0]) and not checkprime(lst[0])):
return False
length = len(lst)
if length == 1:
return True
if checksquare(lst[0]):
# if first element is square then make s(quare)=2 and p(rime)=1
s, p = 2, 1
else:
# if first element is prime then make s=1 and p=2
s, p = 1, 2
# running perfect square loop from s to len-1 with gap of 2 and checking condition
for i in range(s, length, 2):
if not checksquare(lst[i]):
return False
# running prime loop from p to len-1 with gap of 2
for i in range(p, length, 2):
if not checkprime(lst[i]):
return False
return True
def checksquare(n): # function to check perfect square
if n < 0:
return False
if 0 <= n <= 1:
return True
for i in range(int(n ** 0.5) + 1):
if i * i == n:
return True
return False
def checkprime(n): # function to check prime
if n < 2:
return False
if n % 2 == 0:
return n == 2
for i in range(3, int(n ** 0.5) + 1, 2):
if n % i == 0:
return False
return True
I have written a code to find out the LCM (Lowest Common Multiple) of a list of numbers but there appears to be an error in my code. The code is given below:
def final_lcm(thelist):
previous_thelist = thelist
prime_thelist = list(set(thelist) - set(returns_new_thelist(previous_thelist))
factors = 1
for i in prime_thelist:
factors = factors*i
new_thelist = returns_new_thelist(previous_thelist)
for i in range(1, 10000000000):
s_empty = []
for j in new_thelist:
if i % j == 0:
s_empty.append(True)
if len(new_thelist) == len(s_empty):
initial_lcm = i
break
final_lcm = factor*initial_lcm
return final_lcm
def returns_new_thelist(ll):
if 3 in ll:
ll.remove(3)
for i in ll:
if checks_if_prime(i) == True:
ll.remove(i)
return ll
def checks_if_prime(n):
if n == 2:
return True
import math
for i in range(math.ceil(0.5*n), 1, -1):
if n % i == 0:
return False
elif i == 2:
return True
print(final_lcm([1,2,3,4,5,6,7,8,9]))
Kindly pardon my poor choice of variables, I request you to see if the logic is correct and that the code is functional.
The syntax error which I am getting is that "factors" is invalid syntax though I don't agree with this. Please tell me where my code is wrong.
This is the best way that I know of :
from math import gcd
a = [100, 200, 150] #will work for an int array of any length
lcm = 1
for i in a:
lcm = lcm*i//gcd(lcm, i)
print(lcm)
Hope this helps. All queries, contributions and comments are welcome :)
Works with an arbitrarily long denominator list.
from math import gcd # Python versions 3.5 and above
#from fractions import gcd # Python versions below 3.5
from functools import reduce # Python version 3.x
def lcm(denominators):
return reduce(lambda a,b: a*b // gcd(a,b), denominators)
Example:
>>> lcm([100, 200, 300])
600
As of Python 3.9 lcm() function has been added in the math library. It can be called with the following signature:
math.lcm(*integers)
Return the least common multiple of the specified integer arguments.
If all arguments are nonzero, then the returned value is the smallest
positive integer that is a multiple of all arguments. If any of the
arguments is zero, then the returned value is 0. lcm() without
arguments returns 1.
Advantages:
Besides being native,
Its a one-liner,
Its fastest,
Can deal with arbitrarily long list of integers
And can deal with nearly any kind of exceptions (e.g. lcm(0,0)) overlooked by custom-built solutions.
In Numpy v1.17 (which is, as of writing, the non-release development version) there is an lcm function that can be used for two numbers with, e.g.:
import numpy as np
np.lcm(12, 20)
or for multiple numbers with, e.g.:
np.lcm.reduce([40, 12, 20])
There's also a gcd function.
Your solution might be too lengthy ... Try this !
from functools import reduce # need this line if you're using Python3.x
def lcm(a, b):
if a > b:
greater = a
else:
greater = b
while True:
if greater % a == 0 and greater % b == 0:
lcm = greater
break
greater += 1
return lcm
def get_lcm_for(your_list):
return reduce(lambda x, y: lcm(x, y), your_list)
ans = get_lcm_for([1, 2, 3, 4, 5, 6, 7, 8, 9])
print(ans)
if you don't want to import anything.
def gcd(n, m):
if m == 0:
return n
return gcd(m, n % m)
A = [10, 25, 37, 15, 75, 12]
lcm = 1
for i in A:
lcm = lcm * i // gcd(lcm, i)
print(lcm)
You're missing a closing parenthesis ()) in the third line.
Hence the error in line factors.
Moreover in second to last line of your first function,
you've named the variable factor instead of factors.
To find LCM of given list of numbers
def findDivisor(num):
# 2,3 are the most common divisor for many numbers hence I go by divisor of 2,3
# if not then by the same number as divisor
if num%2 == 0:
return 2
elif num%3==0:
return 3
return num
def findLCM(lcmArray):
lcm = 1
while len(lcmArray) > 0:
minOfLCMArray = min(lcmArray)
divisor = findDivisor(minOfLCMArray)
for x in xrange(0, len(lcmArray)):
Quotient = lcmArray[x]/divisor
Reminder = lcmArray[x]%divisor
if Reminder == 0:
lcmArray[x] = Quotient
lcm*=divisor
minOfLCMArray = min(lcmArray)
if minOfLCMArray == 1:
lcmArray.remove(minOfLCMArray)
return lcm
lcmArray = map(int, raw_input().split())
print findLCM(lcmArray)
A faster approach without using any math functions would be to calculate GCD and calculate LCM.
def gcd(a,b):
while b:
a,b = b, a%b
return a
Now find LCM using GCF
def lcm(a,b):
return a*b // gcd(a,b)
Extend this to work with list as below
LCM = functools.reduce(lambda x, y: lcm(x, y), your_list_to_find_lcm)
I had written a code to find lcm of numbers within a list. The User can input any number of values he wants. I'm attaching the code below, It is simpler than the code you posted. Try checking this...
I know your question is to find errors in your code, but try checking this for future purpose.
a = list(map(int,input('enter numbers for the lcm: ').strip().split()))
a.sort(reverse = True)
a
x = a[0]
while 1:
sum = 0
for i in a:
if x%i == 0:
sum += 1
if sum == len(a):
break
else :
x += 1
print(x,' is the lcm of numbers in the input')
c=1
i=0
q=0
j=2;
flag=0;
count=0;
a=input("ente 3 no")
a=a.split(',')
print(len(a))
for i in range(len(a)):
z=int(a[i])
c=c*z
while(j<c):
for p in range(len(a)):
if(j%int(a[p])==0):
count=count+1
if(count==len(a)):
print('in count counter',count)
print('in count',j)
flag=1
break
else:
flag=0
else:
break
if(flag==1):
print('flag',j)
break
else:
count=0
j=j+1
print(j)enter code here
print("count",count)
Find LCM and GCD of a list of numbers
After reading all these solutions it is still unclear so, here is my possible simplest approach :)
find LCM using GCD
from fractions import gcd
from functools import reduce
a = [2,4] #given list
def LCM(a, b):
return (a*b)//gcd(a,b) # as LCM(a,b)*GCD(a,b) = a*b
lcm = reduce(LCM, a) #here reduce will iterate through all
#the elements one by one
gcd = reduce(gcd, a)
print(lcm, gcd)
OUTPUT:
4 2
if you do not wish to use GCD algorithm, below code returns the smallest multiple of the greatest number of the array:
a=[5,10,15,7]
ctr=1
LCM=max(a)
remList=[LCM%i for i in a]
if all(v == 0 for v in remList):
print("LCM is : ", max(a))
else:
while True:
remList=[LCM%i for i in a]
if all(v == 0 for v in remList):
print("LCM is : ",LCM)
break
else:
LCM=LCM+max(a)
This may be useful to you,
Rather finding LCM directly, it is a bit simpler to derive LCM from GCD.
def gcd(a,b):
if a == 0:
return b
return gcd(b % a, a)
x=int(input("enter x"))
y=int(input("enter y"))
print(int(gcd(x,y)))
print(int((x*y)/gcd(x,y)))
prime_thelist = list(set(thelist) - set(returns_new_thelist(previous_thelist))
You're missing a bracket at the end of the line. Correct it to the following:
prime_thelist = list(set(thelist) - set(returns_new_thelist(previous_thelist)))
Also,
if n == 2:
return True
You need to indent the return statement because it is inside a conditional statement.
And it is generally best practice to import any libraries you might need at the beginning rather than in the middle of a function.
from math import gcd
a = [100, 200, 150] #will work for an int array of any length
lcm = a[0]
for i in a[1:]:
lcm = lcm*i//gcd(lcm, i)
print lcm
I needed a 0 dependency one for python2.7 so I came up with this brute one:
def lcm(lst):
"""
finds the lcm for the numbers in the list
"""
candidate = max(lst)
while True:
if sum([candidate % i == 0 for i in lst]) == len(lst):
return candidate
candidate+=1
LCM for N numbers without using GCD
n=list(map(int,input().split()))
def LCMof2(n1,n2):
m= max(n1,n2)
while(1):
if (m%n1==0 and m%n2==0):
ans=m
break
m+=1
return ans
lcm1=LCMof2(n[0],n[1])
for i in range(2,len(n)):
ans=LCMof2(lcm1,n[i])
lcm1=ans
print(ans)
This is my answer to compute GCD and LCM. Please try it. Easiest one I could do.
import math
GCF = yourlist[0]
LCM = yourlist[0]
for i in yourlist[1:]:
GCF = math.gcd(GCF, i)
LCM = LCM*i//math.gcd(LCM, i)
print(GCF)
print(LCM)
This would be a good way to find lcm of a list of numbers in Python
from math import gcd
from functools import reduce
def lcm(a,b):
gc = gcd(a, b) # gcd_of_two_numbers
lc = (a*b) // gc
return lc
numbers = [150, 200, 300]
result = reduce(lcm, numbers)
print(result)
Simple solution to find LCM without using build-in gcd function
def gcd(x,y):
while y:
x,y = y,x%y
return x
for i in ls:
lcm = (lcm*i) // gcd(lcm,i)
print(lcm)
I can get the answer of cubes but I don't really know where to go from here to get the function to return back the answer and keep adding it to a sum! What do I have to do to make it keep adding to get a total?
def sumNCubes(n):
for i in range(n)
return (n-1)**3
def main():
number = int(raw_input("What number do you want to find the sum of cubes for?"))
n = number + 1
for i in range(number):
n = n - 1
print "The result of the sums is:", sumNCubes(n)
main()
You could simply do something like this:
def sumNCubes(n):
return sum(i**3 for i in range(1,n+1))
which uses a list comprehension to cube number in a range from 1-n+1 (1-n will not include n) then uses python built in sum function to sum all of the cubes.
you could then just pass in your input and print it:
def main():
number = int(raw_input("What number do you want to find the sum of cubes for?"))
#this doesn't do anything but change n to 0
#for i in range(number):
# n = n - 1
print "The result of the sums is:", sumNCubes(number)
main()
with input of, for example, 5, this will return:
>>> sumNCubes(5)
225
The answer is very simple. This will be given by recursive approach.
Here is the function to find sum of N numbers and you were very close in getting this
def sumNcubes(n):
if (n == 1):
return 1
else:
return n**3 + sumNcubes(n-1)
>>>sumNcubes(6)
441
Without using n**3
def sum_cubes (n):
b, c, sum = 1, 0, 0
for a in range(0, 6*n, 6):
sum += (c := c + (b := b + a))
return sum
Without a loop
def sum_cubes (n):
return (n*(n+1)//2)**2
What is the recursive call (or inductive steps) for a function that returns the number of integers from 1 to N, which evenly divide N. The idea is to concieve a pure recursive code in python for this function. No 'for' or 'while' loops, neither modules can be used. The function num_of_divisors(42) returns 8, representing 1, 2, 3, 6, 7, 14, 21, and 42 as divisors of 42.
def num_of_divisors(n):
return sum(1 if n % i==0 else 0 for i in range(((n+1)**0.5)//1)
Good luck explaining it to your teacher!
If you really can't use for loops (?????????) then this is impossible without simulating one.
def stupid_num_of_divisors_assigned_by_shortsighted_teacher(n, loop_num=1):
"""I had to copy this from Stack Overflow because it's such an
inane restriction it's actually harmful to learning the language
"""
if loop_num <= (n+1) ** 0.5:
if n % loop_num == 0:
return 2 + \
stupid_num_of_divisors_assigned_by_shortsighted_teacher(n, loop_num+1)
else:
return stupid_num_of_divisors_assigned_by_shortsighted_teacher(n, loop_num+1)
else:
if n % loop_num == 0:
return 1
Bonus points: explain why you're adding 2 in the first conditional, but only 1 in the second conditional!
Here you go buddy your teacher'll be happy.
def _num_of_divisors(n, k):
if (k == 0):
return 0
return _num_of_divisors(n, k-1) + (n % k == 0)
def num_of_divisors(n):
return _num_of_divisors(n, n)
It's easier than you think to convert such a simple problem from a loop to a recursive function.
Start with a loop implementation:
n = 42
result = []
for i in range(n+1):
if n % i == 0:
result.append(i)
then write a function
def num_of_divisors_helper(i, n, result):
if <condition when a number should be added to result>:
result.append(n)
# Termination condition
if <when should it stop>:
return
# Recursion
num_of_divisors_helper(i+1, n, result)
Then you define a wrapper function num_of_divisors that calls num_of_divisors_helper. You should be able to fill the gaps in the recursive function and write the wrapper function yourself.
It's a simple, inefficient solution, but it matches your terms.
Without using %
def is_divisible(n, i, k):
if k > n:
return False
if n - i*k == 0:
return True
else:
return is_divisible(n, i, k+1)
def num_of_divisors(n, i=1):
if i > n/2:
return 1
if is_divisible(n, i, 1):
return 1 + num_of_divisors(n, i+1)
else:
return num_of_divisors(n, i+1)
num_of_divisors(42) -> 8
def n_divisors(n,t=1):
return (not n%t)+(n_divisors(n,t+1) if t < n else 0)
good luck on the test later ... better hit those books for real, go to class and take notes...
with just one input i guess
t=0
def n_divisors(n):
global t
t += 1
return (not n%t)+(n_divisors(n) if t < n else 0)