How can I convert these two functions to use lambda notation?
def sum_digits(number):
if number == 0:
return 0
else:
return (number % 10) + sum_digits(number / 10)
def count_digit(number):
if number == 0:
return 0
else:
return 1 + count_digit(number/10)
sum_digits = lambda number: 0 if number == 0 else (number % 10) + sum_digits (number / 10)
count_digit = lambda number: 0 if number == 0 else 1 + count_digit(number/10)
Incidentally, this is a bad time to use lambdas, since you need the function names in order for them to call themselves. The point of lambdas is that they're anonymous.
Use a conditional expression for the body of the lambda:
>>> sum_digits = lambda n: 0 if n == 0 else (n % 10) + sum_digits(n // 10)
>>> count_digit = lambda n: 0 if n == 0 else 1 + count_digit(n // 10)
Also, if is preferred to use // for the division so that the code will still work in Python 3.
A string-oriented approach wouldn't require recursion:
sum_of_digits = lambda n: sum(int(d) for d in str(n))
count_digit = lambda n: len(str(n))
sum_digits = lambda number: 0 if number == 0 else (number % 10) + sum_digits (number//10)
count_digit = lambda number: 0 if number == 0 else 1 + count_digit(number//10)
print(sum_digits(2546))
print(count_digit(2546))
Will work on python 3 too...
print(list(map(lambda x: sum(int(i) for i in str(x)),list(map(int,input().split())))))
this might be useful for reading and using lamda function on the same line.
Related
I need help for defining the fibanocci 2 function. The fibanocci 2 function is decribed as :
fib2(n) = {0 if n <= 0, 1 if n = 1, 2 if n = 2, ( fib2( n - 1) * fib2( n - 2)) - fib2( n - 3) else}
We need to define this function iterative.
I tried my best but i couldn't write a working code.
def fib2(n: int) -> int:
if n <= 0:
return 0
elif n == 1:
return 1
elif n == 2:
return 2
else:
n = ((n - 1) * (n - 2) - (n - 3)
return n
a = fib2(7)
print (a)
assert (fib2(7) == 37)
the output from this fib2 function is 26 but it should be 37.
Thank you in advance
For the iterative version you have to use a for loop.
And just add the 3 previous numbers to get the next one.
Here is a piece of code:
def fib3(n):
a = 0
b = 1
c = 0
for n in range(n):
newc = a+b+c
a = b
b = c
c = newc
return newc
print(fib3(7))
assert (fib3(7) == 37)
You can not change the value of a parameter.
Please try to return directly :
Return ((fb2(n-1)×fb2(n-2))-fb2(n-3))
So it will work as a recursive function.
def fibo(n):
current = 0
previous_1 = 1
previous_2 = 0
for i in range(1,n):
current = previous_1 + previous_2
previous_2 = previous_1
previous_1 = current
return current
To do it iteratively, the best way is to write it on paper to understand how it works.
Mathematically fibo is Fn = Fn-1 + Fn-2 . Therefore, you can create variables called previous_1 and previous_2 which represents the elements of Fn and you simply update them on each run.
Fn is current
I'm a bit stuck on a python problem.
I'm suppose to write a function that takes a positive integer n and returns the number of different operations that can sum to n (2<n<201) with decreasing and unique elements.
To give an example:
If n = 3 then f(n) = 1 (Because the only possible solution is 2+1).
If n = 5 then f(n) = 2 (because the possible solutions are 4+1 & 3+2).
If n = 10 then f(n) = 9 (Because the possible solutions are (9+1) & (8+2) & (7+3) & (7+2+1) & (6+4) & (6+3+1) & (5+4+1) & (5+3+2) & (4+3+2+1)).
For the code I started like that:
def solution(n):
nb = list(range(1,n))
l = 2
summ = 0
itt = 0
for index in range(len(nb)):
x = nb[-(index+1)]
if x > 3:
for index2 in range(x-1):
y = nb[index2]
#print(str(x) + ' + ' + str(y))
if (x + y) == n:
itt = itt + 1
for index3 in range(y-1):
z = nb[index3]
if (x + y + z) == n:
itt = itt + 1
for index4 in range(z-1):
w = nb[index4]
if (x + y + z + w) == n:
itt = itt + 1
return itt
It works when n is small but when you start to be around n=100, it's super slow and I will need to add more for loop which will worsen the situation...
Do you have an idea on how I could solve this issue? Is there an obvious solution I missed?
This problem is called integer partition into distinct parts. OEIS sequence (values are off by 1 because you don't need n=>n case )
I already have code for partition into k distinct parts, so modified it a bit to calculate number of partitions into any number of parts:
import functools
#functools.lru_cache(20000)
def diffparts(n, k, last):
result = 0
if n == 0 and k == 0:
result = 1
if n == 0 or k == 0:
return result
for i in range(last + 1, n // k + 1):
result += diffparts(n - i, k - 1, i)
return result
def dparts(n):
res = 0
k = 2
while k * (k + 1) <= 2 * n:
res += diffparts(n, k, 0)
k += 1
return res
print(dparts(201))
I'm new to programming and i'm doing the Project Euler challenges to give me a reason to learn.
Find below my very simple python code
x = 1
thirdDivide = 0
fifthDivide=0
total = 0
print('Enter the max value')
maxValue = input()
while (x != maxValue):
thirdDivide = x / 3
fifthDivide = x / 5
if (thirdDivide).is_integer():
total = total + x
x = x + 1
elif (fifthDivide).is_integer():
total = total + x
x = x + 1
print ("The sum of the multiples of 3 and 5 between 0 and " + maxValue + " is " + total)
When I run it it asks for my max value, then ceases doing anything.
Thanks!
Assuming you are in Python 3, the fixes for using strings instead of floats, or floats instead of strings, infite loop is following:
x = 1
thirdDivide = 0
fifthDivide=0
total = 0
maxValue = float(input('Enter the max value: '))
while (x != maxValue):
thirdDivide = x / 3
fifthDivide = x / 5
if (thirdDivide).is_integer():
total = total + x
elif (fifthDivide).is_integer():
total = total + x
x = x + 1
print("The sum of the multiples of 3 and 5 between 0 and " + str(maxValue) + " is " + str(total))
Note, I dont check for correctness of your algoritm and whether it calculates what it is supposed to do. But now it produces some results and compiles.
You can solve it with a functional approach using filter and reduce:
def f(acc, v): return acc + v
def g(x): return x % 3 == 0 or x % 5 == 0
print reduce(f, filter(g, range(1000)))
How it works:
filter: takes two arguments:
The first is a function g applied for every element of range(1000). g takes one argument x and check if is multiple of 3 or 5 (checking the remainder of the modulo operation %).
The second is the range from 0 to 1000.
reduce: takes two arguments:
The first is a function f that takes two arguments: an accumulator acc and a variable v that represents the current element in the list.
The second argument is the filtered range returned before by filter.
Output:
with range(10) = 23
with range(1000) = 233168
Using lambda functions (same logic just different syntax):
print reduce(lambda acc, v: acc + v, filter(lambda x: x % 3 == 0 or x % 5 == 0, range(1000)))
You only increment x if thirdDivide.is_integer() or fifthDivide.is_integer() are true. So if neither it true, you'll just loop infinitely on the same value of x.
If neither thirdDivide nor fifthDivide is an integer, x is never updated -- you enter an infinite loop. You need to make sure you have a "base case" so that the iteration variable is always changing. Here's a slightly cleaner algorithm:
total = 0
for i in range(0, x):
if i % 3 == 0 or i % 5 == 0:
total += i
I think you'll find that for most iteration, for loops are easier to reason about. Happy coding!
As many said before, you are stuck in an infinite loop with x not being incremented. If you added a "else" statement at the end and printed the output you could see what they are talking about. You can do this in one line of code.
print(sum(x for x in range(maxValue) if x % 3 == 0 or x % 5 == 0))
I am learning python and I meet some troubles.
I want to write the script to reverse a negative integer " -1234 to 4321- " and non-integer " 1.234 to 432.1". please help me.
P.S. cannot use "str()" function
I just only can write the script to reverse positive integer 1234 to 4321
def reverse_int(n):
x = 0
while n > 0:
x *= 10
x += n % 10
n /= 10
return x
print reverse_int(1234)
def reve(x):
x=str(x)
if x[0]=='-':
a=x[::-1]
return f"{x[0]}{a[:-1]}"
else:
return x[::-1]
print(reve("abc"))
print(reve(123))
print(reve(-123))
#output
cba
321
-321
how about using your code, but just concatenate a - when n is negative?
rev_int.py:
def reverse_int(m):
x = 0
n = m
if m < 0 :
n *= -1
while n > 0 :
x *= 10
x += n % 10
n /= 10
if m < 0:
#concatenate a - sign at the end
return `x` + "-"
return x
print reverse_int(1234)
print reverse_int(-1234)
This produces:
$ python rev_int.py
4321
4321-
Using SLICING EASILY DONE IT
def uuu(num):
if num >= 0:
return int(str(num)[::-1])
else:
return int('-{val}'.format(val = str(num)[1:][::-1]))
Below code runs fine on Python-3 and handles positive and negative integer case. Below code takes STDIN and prints the output on STDOUT.
Note: below code handles only the integer case and doesn't handles the
non-integer case.
def reverseNumber(number):
x = 0
#Taking absolute of number for reversion logic
n = abs(number)
rev = 0
#Below logic is to reverse the integer
while(n > 0):
a = n % 10
rev = rev * 10 + a
n = n // 10
#Below case handles negative integer case
if(number < 0):
return (str(rev) + "-")
return (rev)
#Takes STDIN input from the user
number=int(input())
#Calls the reverseNumber function and prints the output to STDOUT
print(reverseNumber(number))
Using str convert method.
num = 123
print(str(num)[::-1])
Use this as a guide and make it work for floating point values as well:
import math
def reverse_int(n):
if abs(n) < 10:
v = chr(abs(n) + ord('0'))
if n < 0: v += '-'
return v
else:
x = abs(n) % 10
if n < 0: return chr(x + ord('0')) + reverse_int(math.ceil(n / 10))
else: return chr(x + ord('0')) + reverse_int(math.floor(n / 10))
print reverse_int(1234)
Why not just do the following?:
def reverse(num):
revNum = ''
for i in `num`:
revNum = i + revNum
return revNum
print reverse(1.12345)
print reverse(-12345)
These would print 54321.1 and 54321-.
I am working on this seemingly simple problem, where I need to add one to every digit of a number. Example: number = 1234 ; output = 2345
That's simple, but when 9 is one of those digits, then by the law of addition, that 9 will be replaced by 0 and 1 will be added to the number on the left (9 + 1 = 10, hence, place value = 0 & carry over = 1)
Example: number = 1239 ; output = 2350
number = 1234
s = str(number)
l = []
for num in s:
num = int(num)
num += 1
if num > 9:
num = 0
l.append(num)
else:
l.append(num)
print int(''.join(str(v) for v in l))
Can someone please explain to me, what logic should I use? I can see something on the lines of modular arithmetic, but not really sure how to implement that.
Thanks :)
A simple approach would be as follows
Consider a number N = anan-1an-2...a0
Then F(N) = N + (10n-1+10n-2 .. 100) = N + int('1' X N)
= N + (10n - 1) / (10 - 1) = N + (10n - 1) / 9
>>> def foo(N):
return N + int('1'*len(str(N)))
>>> foo(1234)
2345
>>> foo(1239)
2350
Edit: Simplifying a bit by utilizing sum of power formula
>>> def foo(N):
return N + ((10**len(str(N)) - 1) // 9)
With pure math:
num = num + (10**int(math.ceil(math.log10(num)))-1)//9
Your code can be easily modified to process the digits in reversed order and maintain the carry state. The "modular arithmetic" you're looking for is typically implemented using the % operator:
number = 1234
s = str(1234)
l = []
carry = 0
for num in reversed(s):
num = int(num) + carry
num += 1
carry = num / 10
l.append(num % 10)
print int(''.join(str(v) for v in reversed(l)))