Function does not give desired result - python-3.x

I am trying to define a function for Fibonacci series but the code is not working. I can't resolve the issues and need help to fix the problem. Whenever I am trying to call this function, last value of the series comes always greater than n, which I don't want
def fib(n):
Series = [0,1]
if n>1:
while Series[-1]<=n:
c=Series[-2]+Series[-1]
Series.append(c)
if Series[-1]>n:
break
return Series

Your code is really good, just the indentation of the return is wrong. Just align it properly.
def fib(n):
Series = [0,1]
if n>1:
while Series[-1]<=n:
c=Series[-2]+Series[-1]
Series.append(c)
return Series

do you need something like this:
def fibo(n):
l = [0,1]
for i in range(2,n+1):
l += [l[i-1] + l[i-2]]
return l

If you want to get the Fibonacci sequence up to n:
def fib(n):
series = [0,1]
if n > 1:
c = 1
while c <= n:
series.append(c)
c = series[-2] + series[-1]
return series

Related

Need help writing a function which returns a dictionary with the keys as recursive digit sums

So I have written a function which calculates the sum of the digits when a number is input to the function. Now I am trying to write another function which would return a dictionary with the values from my digitsum function as the keys and the values would be how many times the count of that specific digitsum has occurred. Any ideas on how to go about writing the second function?
def digitsum(x):
if x < 10:
return x
else:
return (x%10) + digitsum(x//10)
def digitsumdictionary(lnum=0, hnum=100):
L =[digitsum(num) for num in range(100)]
counter = Counter(L).items()
return counter
Digitsum function is called depending on the length of the number.
You can simply find it by using len(list(str(num))). But if you want to count as the function calls itself, Then try this,
def digitsum(x, count=1):
if x < 10:
return { x : count }
else:
return {(x%10) + int(list(digitsum(x//10 , count+1).keys())[0]) : int(list(digitsum(x//10 , count+1).values())[0])}
Setting the count to 1 or 0 initially, includes or excludes the first call respectively.
The below code returns a list of dictionaries of the desired output.
[digitsum(i) for i in range(10)]

Python 3, any better/cleaner way to write these functions that use for loops?

I'm trying to write code in the most simplest and cleanest way possible. I've found a few ways to shorten and simplify my code through functions that I've never seen before or through using other methods. I'd like to expand my knowledge on writing code using various (but simple) methods, and also expand my function 'vocabulary'.
Here are the functions:
1. Perfect number:
If a number's divisors' sum is equal to the number itself, it is a perfect number. We dont count the number itself as a divisor. E.g. 6's divisors are 1, 2, 3. The sum of the divisors is 6. Therefore 6 is a perfect number.
def perfect_number(num):
if type(num) != int or num < 0:
return None
divisors = []
total = 0
for x in range(num):
if num % (x+1) == 0:
if num != x+1:
divisors += [x+1]
for x in divisors:
total += x
if total == num:
return True
return False
2. Pattern:
A function that takes a positive integer and prints a pattern as follows:
pattern(1): '#-'
pattern(2): '#-#--'
pattern(5): '#-#--#---#----#-----'
def pattern(num):
if type(num) != int or num < 0:
return None
output = ''
for x in range(num):
output += '#'+('-'*(x+1))
return output
3. Reversed Numbers:
A function that takes 2 integers. It goes through every number in the range between those 2 numbers, if one of those numbers is a palindrome (the same thing backwards e.g. 151 is a 'palindrome'), it will increase a variable by 1. That variable is then returned.
invert_number(num) returns the opposite of num as an integer.
def reversed_numbers(low, high):
output = 0
for x in range(low,high+1):
if invert_number(x) == x:
output += 1
return output
It is assumed that low is lower than high.
If I broke a rule or if this doesnt fit here, please tell me where I can post it/how I can improve. Thanks :)

power (a, n) in PYTHON

POwer in Python. How to write code to display a ^ n using funсtion?
why doesn't this code working?
a = int(input())
n = int(input())
def power(a, n):
for i in range (n):
a=1
a *= n
print(power (a, n))
Few errors:
Changing a will lose your power parameter, use result (or something else).
Move setting result = 1 outside your loop to do so once.
Multiply by a not by n.
Use return to return a value from the function
def power(a, n):
result = 1 # 1 + 2
for _ in range (n):
result *= a # 3
return result # 4
Style notes:
Setting/mutating a parameter is considered bad practice (unless explicitly needed), even if it is immutable as is here.
If you're not going to use the loop variable, you can let the reader know by using the conventional _ to indicate it (_ is a legal variable name, but it is conventional to use it when not needing the variable).
Tip: you can simple use a**n
It doesn't work because your function doesn't return the end value. Add return a to the end of the function.
ALSO:
That is not how a to the power of n is is calculated.
A proper solution:
def power(a,n):
pow_a = a
if n is 0:
return 1
for _ in range(n-1): # Substracting 1 from the input variable n
pow_a *= a # because n==2 means a*a already.
return pow_a
and if you want to be really cool, recursion is the way:
def power_recursive(a,n):
if n is 0:
return 1
elif n is 1:
return a
else:
a *= power_recursive(a,n-1)
return a

sum even integer in a list of integer (without loop)

I have a task: create a function that takes a integer list as parameter and returns the sum of all even integer in an integer list, without using any kinds of loop. All addition must be done by + operator only. Below is my solution
def sumTest(list_Of_Integers):
return sum(list(filter(lambda x: x%2 == 0, list_Of_Integers)))
I want to ask if there is any better solution, like without using the built-in sum() of python.
Thanks
As stated above in the comments, a more pythonic way of doing this is to use a list comprehension:
def sumTest(list_Of_Integers):
return sum([x for x in list_Of_Integers where x % 2 == 0])
As #UloPe states, however, this sounds very much like a homework question, in which case a more recursive method may be expected (rather than using the sum() function):
def sumTest2(xs):
if len(xs) == 0:
return 0
total = xs[0] if xs[0] % 2 == 0 else 0
return total + sumTest2(xs[1:])
This will generate a function stack dependent on the size of the list.
If you want to generate a shallower stack, then you can do the following:
def sumTest3(xs):
if len(xs) == 0:
return 0
midpoint = len(xs) / 2
total = xs[midpoint] if xs[midpoint] % 2 == 0 else 0
return sumTest3(xs[:midpoint]) + total + sumTest3(xs[midpoint + 1:])
The stack depth of this version will be log(size of list)

Creating a function that returns index of minimum value in a list?

def minimum_index(xs):
minimum_index=xs[0]
for i in range(len(xs)):
if xs[i]<xs[i+1]:
min_i=i
elif xs[i]>xs[i+1]:
min_i=i+1
continue
return minimum_index
This looks correct to me, but for some reason, I keep trying to change things around and I either get an incorrect return value or no return value.
Simplify the function
def minimum_index(xs):
ans = 0
for i in range(1, len(xs)):
if xs[i] < xs[ans]:
ans = i
return ans
or in a more pythonic way
minimum_index = lambda xs: xs.index(min(xs))
Your code has at least two issues: You seem to have two variables that stand for the minimal index, and you mix them up. Also, it is not enough to compare subsequent elements, you will have to compare to the minimal value. Try this:
def minimum_index(xs):
minx = xs[0]
mini = 0
for i in range(1,len(xs)):
if xs[i]<minx:
mini = i
minx = xs[i]
return mini
If you are using numpy, then you can simply use their numpy.argmin(xs).

Resources