problem:
For this problem, we'll round an int value up to the next multiple of 10 if its rightmost digit is 5 or more, so 15 rounds up to 20. Alternately, round down to the previous multiple of 10 if its rightmost digit is less than 5, so 12 rounds down to 10. Given 3 ints, a b c, return the sum of their rounded values. To avoid code repetition, write a separate helper "def round10(num):" and call it 3 times. Write the helper entirely below and at the same indent level as round_sum().
------------------------------------------------------------------------
round_sum(16, 17, 18) → 60
round_sum(12, 13, 14) → 30
round_sum(6, 4, 4) → 10
my code:
def round_sum(a, b, c):
round10(a)
round10(b)
round10(c)
return a+b+c
def round10(num):
if num%10>=5:
while num%10!=0:
num = num+1
else:
while num%10!=0:
num = num-1
enter link description here
You don't modify a,b,c. round10 computes the value you want but since you don't keep it in any variable it's forgotten immediately. Try this:
def round_sum(a, b, c):
a = round10(a)
b = round10(b)
c = round10(c)
return a+b+c
also round10 needs to return your final value:
def round10(num):
if num%10>=5:
while num%10!=0:
num = num+1
else:
while num%10!=0:
num = num-1
return num # <----
My Code
def round_sum(a, b, c):
count = 0
for i in (a,b,c):
if i<5: i = 0
if i>4 and i<10: i = 10
if i%10 in [5,6,7,8,9]and i!= 0 and i > 9:
i = i + (10-i%10)
elif i%10 in [1,2,3,4] and i!=0 and i > 9:
i = i - (i%10)
count = count + i
return count
def roundsum(a, b, c):
sum=0
for x in (a,b,c):
if 5<=x<=10:
y=x-x+10
sum+=y
elif x>10:
if x%10<5:
y=x-(x%10)
sum+=y
elif x%10>=5:
y=x-(x%10)+10
sum+=y
return sum
Related
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 wrote a Fibonacci series using Python. Could not figure out why second program is giving wrong answer and first one right when both look same.
Below program gives right answer
def fib(n):
a,b=0,1
while b<n:
print b
a,b=b,a+b
fib(4)
1
1
2
3
Below program gives wrong answer:
def fib(n):
a = 0
b = 1
while b<n:
print b
a = b
b = a+b
fib(4)
1
2
In first one, a, b = b, a+b does the assigning simultanously.
In second one, you are first doing a = b and then doing b = a+b which actually is just b = 2*b.
How to achieve such behaviour in second one? Use temporary value to store a.
def fib(n):
a = 0
b = 1
while b<n:
print b
temp = a
a = b
b = temp+b
fib(4)
>>>1
>>>1
>>>2
>>>3
In the second code posted, you redefine the value of b after having changed a, resulting as
def fib(n):
a = 0
b = 1
while b<n:
print b #prints 1
a = b #a = 1
b = a+b #b = 1 + 1 = 2
In the second code, there is no problem, as python code generally reads equations from right to left, thus redefines b first, as is correct
def fib(n):
a,b=0,1 #a = 0, b = 1
while b<n:
print b
a,b=b,a+b #b = 0 + 1 = 1, #a = 1
fibonacci series using lambda function in python
n = int(input("Enter the range of numbers in fibonacci series:"))
F = [0,1]
list(map(lambda i: F.append(F[i-1] + F[i-2]), range(2, n)))
print(F)
fibonacci series using List Comprehension function in python
n = int(input("Enter the range of numbers in fibonacci series:"))
F = [0,1]
[F.append(F[i-1] + F[i-2]) for i in range(2,n)]
print(F)
In the first example, you've used this code:
a,b=b,a+b
While in the second, you've done this instead:
a = b
b = a+b
These are not the same thing.
For the sake of argument, let's say that a = 3 and b = 6. Let's run the working code first:
>>> a, b = 10, a + 1
>>> a
10
>>> b
4
The value of a + 1 is 4 rather than 11, because b's assignment is using the old value of a, so 3 + 1 == 4.
Now let's put a and b back to their starting values. Let's try the other method of assigning:
>>> a = 10
>>> b = a + 1
>>> a
10
>>> b
11
Now b is 11! That's because a was assigned before the assignment of b, so the addition uses a's new value.
The reason your second version isn't working is because the assignments don't happen simultaneously, so b is actually 2 * b because a has already been set to b by the time a+b is executed.
def fibonacci (n):
if n == 1 or n == 2:
return 1
return fibonacci (n-1) + fibonacci (n-2)
for i in range(1,50):
print (fibonacci(i))
n1 = 0
n2 = 1
c = 0
nTerms = int(input())
if nTerms <= 0:
print("Enter the valid value")
elif nTerms == 1:
print(a)
else:
while c < nTerms:
print(n1)
nth = n1 + n2
n1 = n2
n2 = nth
c += 1
Fibonacci Series Using Recursion
def f_recursion(n):
if n <= 1:
return n
else:
return(f_recursion(n-1) + f_recursion(n-2))
# Driver Code
nterms = int(input())
if nterms <= 0:
print("Enter the positive value")
else:
for i in range(0,nterms):
print (f_recursion(i))
n1=int(input("Enter Term"))
mylist=[0,1]
for a in range(n1):
sum=0
for b in mylist[len(mylist)-2:]:
sum+=b
mylist.append(sum)
print(mylist)
def fib(n):
a=0
b=1
sum=0
for i in range(0,n):
print(sum)
sum = a + b
b = a
a = sum
fib(10) // here you can add any n value from 1 to 100
# The below code will generate the fibonacci series as per desired range
# just put the number, you want the fibonaci series upto.
def fibonacci(num):
x,y = 0,1
if num==1:
print(x)
elif num==2:
print(x,y)
else:
print(x,y,end = " ")
for i in range(num-2):
z=x+y
x=y
y=z
print(z,end = " ")
def fib(n1, n2):
print(n1)
print(n2)
for i in range(n1, n2):
n1 += n2
n2 += n1
print(n1)
print(n2)
starting_number = int(input('Enter First Term: '))
ending_number = int(input('Enter Second Number: '))
fib(starting_number, ending_number)
i have written this code which finds factors of a number .after thinking and trying so much i could not get the sum of the numbers I get in output.I wish to get the sum of these numbers as output recursively.here's my code:
def p(n,c):
s = 0
if c >= n:
return n
if n % c == 0:
s += c
print(s,end=',')
return p(n,c+1)
n = int(input('enter no:'))
c = 1
print(p(n,c))
Given the comments, it appears that this might be what you want:
sum([n for n in xrange(1,24) if 24 % n == 0])
To make it a bit more generic:
def sum_of_factors(x):
return sum([n for n in xrange(1,x) if x % n == 0])
EDIT: here's a recursive version:
def sum_of_factors(x, y=1):
if (y >= x):
return 0
if (x % y == 0):
return y + sum_of_factors(x, y + 1)
return sum_of_factors(x, y + 1)
>>> sum_of_factors(24)
36
Is this the output you are looking for?
Use global variable,
s = 0
def p(n,c):
global s
if c >= n:
return n
if n % c == 0:
s += c
print(s,end=',')
return p(n,c+1)
n = int(input('enter no:'))
c = 1
print(p(n,c))
Output
enter no:1,3,6,10,16,24,36,24
fib = [0,1]
a = 1
b = 0
i = 0
while i < n:
i = a+b
a,b = i, a
fib.append(i)
This works in cases where 'n' (which is a given variable) is a number in an actual Fibonacci sequence, like 21 or 13. However, if the number is something like six, it adds one more number than it should. The list should not contain a number that is greater than n.
You could always add a to the list first, then do your incrementing.
fib = [0]
a, b = 1, 0
while a <= n:
fib.append(a)
a,b = a+b, a
Using the classic shnazzy recursive Fibonacci function (which took me a few tries to remember and get right):
def fib(num):
if ((num == 0) or (num == 1)): return 1
fib_num = fib(num - 1) + fib(num - 2)
return fib_num
x, n, i = 2, 15, []
while (fib(x) < n):
i.append(fib(x))
x += 1
I need to make a program that asks for the amount of Fibonacci numbers printed and then prints them like 0, 1, 1, 2... but I can't get it to work. My code looks the following:
a = int(raw_input('Give amount: '))
def fib():
a, b = 0, 1
while 1:
yield a
a, b = b, a + b
a = fib()
a.next()
0
for i in range(a):
print a.next(),
I would use this method:
Python 2
a = int(raw_input('Give amount: '))
def fib(n):
a, b = 0, 1
for _ in xrange(n):
yield a
a, b = b, a + b
print list(fib(a))
Python 3
a = int(input('Give amount: '))
def fib(n):
a, b = 0, 1
for _ in range(n):
yield a
a, b = b, a + b
print(list(fib(a)))
You are giving a too many meanings:
a = int(raw_input('Give amount: '))
vs.
a = fib()
You won't run into the problem (as often) if you give your variables more descriptive names (3 different uses of the name a in 10 lines of code!):
amount = int(raw_input('Give amount: '))
and change range(a) to range(amount).
Since you are writing a generator, why not use two yields, to save doing the extra shuffle?
import itertools as it
num_iterations = int(raw_input('How many? '))
def fib():
a,b = 0,1
while True:
yield a
b = a+b
yield b
a = a+b
for x in it.islice(fib(), num_iterations):
print x
.....
Really simple with generator:
def fin(n):
a, b = 0, 1
for i in range(n):
yield a
a, b = b, a + b
ln = int(input('How long? '))
print(list(fin(ln))) # [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, ...]
Python is a dynamically typed language. the type of a variable is determined at runtime and it can vary as the execution is in progress.
Here at first, you have declared a to hold an integer type and later you have assigned a function to it and so its type now became a function.
you are trying to apply 'a' as an argument to range() function which expects an int arg but you have in effect provided a function variable as argument.
the corrected code should be
a = int(raw_input('Give amount: '))
def fib():
a, b = 0, 1
while 1:
yield a
a, b = b, a + b
b = fib()
b.next()
for i in range(a):
print b.next(),
this will work
def fibonacci(n):
fn = [0, 1,]
for i in range(2, n):
fn.append(fn[i-1] + fn[i-2])
return fn
To get the fibonacci numbers till any number (100 in this case) with generator, you can do this.
def getFibonacci():
a, b = 0, 1
while True:
yield b
b = a + b
a = b - a
for num in getFibonacci():
if num > 100:
break
print(num)
def genFibanocciSeries():
a=0
b=1
for x in range(1,10):
yield a
a,b = b, a+b
for fib_series in genFibanocciSeries():
print(fib_series)
Your a is a global name so-to-say.
a = int(raw_input('Give amount: '))
Whenever Python sees an a, it thinks you are talking about the above one. Calling it something else (elsewhere or here) should help.
Also you can use enumerate infinite generator:
for i,f in enumerate(fib()):
print i, f
if i>=n: break
Also you can try the closed form solution (no guarantees for very large values of n due to rounding/overflow errors):
root5 = pow(5, 0.5)
ratio = (1 + root5)/2
def fib(n):
return int((pow(ratio, n) - pow(1 - ratio, n))/root5)
You had the right idea and a very elegant solution, all you need to do fix is your swapping and adding statement of a and b. Your yield statement should go after your swap as well
a, b = b, a + b #### should be a,b = a+b,a #####
`###yield a`
Simple way to print Fibonacci series till n number
def Fib(n):
i=a=0
b=1
while i<n:
print (a)
i=i+1
c=a+b
a=b
b=c
Fib(input("Please Enter the number to get fibonacci series of the Number : "))
a = 3 #raw_input
def fib_gen():
a, b = 0, 1
while 1:
yield a
a, b = b, a + b
fs = fib_gen()
next(fs)
for i in range(a):
print (next(fs))
I've build this a while ago:
a = int(raw_input('Give amount: '))
fab = [0, 1, 1]
def fab_gen():
while True:
fab.append(fab[-1] + fab[-2])
yield fab[-4]
fg = fab_gen()
for i in range(a): print(fg.next())
No that fab will grow over time, so it isn't a perfect solution.
It looks like you are using the a twice. Try changing that to a different variable name.
The following seems to be working great for me.
def fib():
a, b = 0, 1
while True:
yield a
a, b = b, a+b
f = fib()
for x in range(100):
print(f.next())
i like this version:
array = [0,1]
for i in range(20):
x = array[0]+array[1]
print(x)
array[0] = array[1]
array[1] = x
Below are two solution for fiboncci generation:
def fib_generator(num):
'''
this will works as generator function and take yield into account.
'''
assert num > 0
a, b = 1, 1
while num > 0:
yield a
a, b = b, a+b
num -= 1
times = int(input('Enter the number for fib generaton: '))
fib_gen = fib_generator(times)
while(times > 0):
print(next(fib_gen))
times = times - 1
def fib_series(num):
'''
it collects entires series and then print it.
'''
assert num > 0
series = []
a, b = 1, 1
while num > 0:
series.append(a)
a, b = b, a+b
num -= 1
print(series)
times = int(input('Enter the number for fib generaton: '))
fib_series(times)
Why do you go for complex here is one of my snippet to work on!!
n = int(input('Enter your number..: '))
a = 0
b = 1
c = 0
print(a)
print(b)
for i in range(3, n+1):
c = a+b
print(c)
a,b=b,c
check out my git - rohith-sreedharan
We can use it in a short way without through 'yield and 'next' statements
def fib(n):
return n if n <= 1 else fib(n - 1) + fib(n - 2)