SyntaxError: invalid syntax while using lambda in python2 - python-2.x

I want to print the cube of the numbers in the Fibonacci series and i am using the code below:
def fib_series():
o = int(raw_input ("enter the number for the Fibonacci series to print : "))
if o == 1 : return [1]
if o==0: return []
lst = [0,1]
for i in range(2,o):
lst.append(lst[i-1] + lst[i-2])
return lst
fib_series()
cube = lambda x : x:x:x
print (list((map(cube,fib_series))))

Try this:
def fib_series():
o = int(raw_input ("enter the number for the Fibonacci series to print : "))
if o == 1 : return [1]
if o==0: return []
lst = [0,1]
for i in range(2,o):
lst.append(lst[i-1] + lst[i-2])
return lst
fib_series()
cube = lambda x : x*x*x # Changed this from x:x:x
print (list((map(cube,fib_series))))

Try this...
cube = lambda x: x**3

Related

ELM recursive iteration

I need to create a function that takes a number, such as for a given number x, it computes the number y, by adding all digits of number x to itself.
An example :
Given x = 123:
It return 129 = 1 + 2 + 3 + 123
Given x = 35:
It return y = 43 = 3 + 5 + 35
I have this function that works but I need another way:
computeNextValue : Int -> Int
computeNextValue input =
String.fromInt input
|> String.split ""
|> List.filterMap String.toInt
|> List.sum
|> (+) input
First, let's make a recursive function that gives you all the digits of a number. The main idea is that you can get the rightmost digit of an integer by modBy 10, and you can remove it from the number by // 10:
getDigits : Int -> List Int
getDigits num =
if num == 0 then
[] -- base case
else
modBy 10 num :: getDigits (num // 10) -- recursive case
Note that this function returns the [] for 0, but that's OK for this usecase.
computeNextValue : Int -> Int
computeNextValue input =
input + List.sum (getDigits inputs)

Multiplying with divide and conquer

Below I've posted the code to a non-working "divide and conquer" multiplication method in ruby(with debug prints). I cannot tell if its broken code, or a quirk in Ruby like how the L-shift(<<) operator doesn't push bits into the bit-bucket; this is unexpected compared to similar operations in C++.
Is it broken code (doesn't match the original algorithm) or unexpected behavior?
Pseudo code for original algorithm
def multiply(x,y,n, level)
#print "Level #{level}\n"
if n == 1
#print "\tx[#{x.to_s(2)}][#{y.to_s(2)}]\n\n"
return x*y
end
mask = 2**n - 2**(n/2)
xl = x >> (n / 2)
xr = x & ~mask
yl = y >> (n / 2)
yr = y & ~mask
print " #{n} | x = #{x.to_s(2)} = L[#{xl.to_s(2)}][#{xr.to_s(2)}]R \n"
print " #{n} | y = #{y.to_s(2)} = L[#{yl.to_s(2)}][#{yr.to_s(2)}]R \n"
#print "\t[#{xl.to_s(2)}][#{yr.to_s(2)}]\n"
#print "\t[#{xr.to_s(2)}][#{yr.to_s(2)}]\n"
#print "\t([#{xl.to_s(2)}]+[#{xr.to_s(2)}])([#{yl.to_s(2)}]+[#{yr.to_s(2)}])\n\n"
p1 = multiply( xl, yl, n/2, level+1)
p2 = multiply( xr, yr, n/2, level+1)
p3 = multiply( xl+xr, yl+yr, n/2, level+1)
return p1 * 2**n + (p3 - p1 - p2) * 2**(n/2) + p2
end
x = 21
y = 22
print "x = #{x} = #{x.to_s(2)}\n"
print "y = #{y} = #{y.to_s(2)}\n"
print "\nDC_multiply\t#{x}*#{y} = #{multiply(x,y,8, 1)} \nregular\t#{x}*#{y} = #{x*y}\n\n "
I am not familiar with the divide and conquer algorithm but i don't think it contains parts you can't do in Ruby.
Here is a quick attempt:
def multiplb(a,b)
#Break recursion when a or b has one digit
if a < 10 || b < 10
a * b
else
#Max number of digits of a and b
n = [a.to_s.length, b.to_s.length].max
# Steps to split numbers to high and low digits sub-numbers
# (1) to_s.split('') => Converting digits to string then arrays to ease splitting numbers digits
# (2) each_slice => Splitting both numbers to high(left) and low(right) digits groups
# (3) to_a , map, join, to_i => Simply returning digits to numbers
al, ar = a.to_s.split('').each_slice(n/2).to_a.map(&:join).map(&:to_i)
bl, br = b.to_s.split('').each_slice(n/2).to_a.map(&:join).map(&:to_i)
#Recursion
p1 = multiplb(al, bl)
p2 = multiplb(al + ar, bl + br)
p3 = multiplb(ar, br)
p1 * (10**n) + (p2 - p1 - p3) * (10**(n/2)) + p3
end
end
#Test
puts multiplb(1980, 2315)
# => 4583700 yeah that's correct :)
Here are some references to further explain part of the code:
Finding max of numbers => How do you find a min / max with Ruby?
Spliting an array to half => Splitting an array into equal parts in ruby
Turning a fixnum into array => Turning long fixed number to array Ruby
Hope it hepls !

scala : better solution

QUESTION:
We define super digit of an integer x using the following rules:
Iff x has only 1 digit, then its super digit is x.
Otherwise, the super digit of x is equal to the super digit of the digit-sum of x. Here, digit-sum of a number is defined as the sum of its digits.
For example, super digit of 9875 will be calculated as:
super-digit(9875) = super-digit(9+8+7+5)
= super-digit(29)
= super-digit(2+9)
= super-digit(11)
= super-digit(1+1)
= super-digit(2)
= 2.
You are given two numbers - n k. You have to calculate the super digit of P.
P is created when number n is concatenated k times. That is, if n = 123 and k = 3, then P = 123123123.
Input Format
Input will contain two space separated integers, n and k.
Output Format
Output the super digit of P, where P is created as described above.
Constraint
1≤n<10100000
1≤k≤105
Sample Input
148 3
Sample Output
3
Explanation
Here n = 148 and k = 3, so P = 148148148.
super-digit(P) = super-digit(148148148)
= super-digit(1+4+8+1+4+8+1+4+8)
= super-digit(39)
= super-digit(3+9)
= super-digit(12)
= super-digit(1+2)
= super-digit(3)
= 3.
I have written the following program to solve the above problem , but how to solve it even efficiently and is string operation efficient than math operation ??? and for few inputs it takes a long time for example
861568688536788 100000
object SuperDigit {
def main(args: Array[String]) {
/* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution
*/
def generateString (no:String,re:BigInt , tot:BigInt , temp:String):String = {
if(tot-1>re) generateString(no+temp,re+1,tot,temp)
else no
}
def totalSum(no:List[Char]):BigInt = no match {
case x::xs => x.asDigit+totalSum(xs)
case Nil => '0'.asDigit
}
def tot(no:List[Char]):BigInt = no match {
case _ if no.length == 1=> no.head.asDigit
case no => tot(totalSum(no).toString.toList)
}
var list = readLine.split(" ");
var one = list.head.toString();
var two = BigInt(list(1));
//println(generateString("148",0,3,"148"))
println(tot(generateString(one,BigInt(0),two,one).toList))
}
}
One reduction is to realise that you do not have to concatenate the number considered as a string k times but rather can start with the number k * qs(n) (where qs is the function that maps a number to its sum of digits, i. e. qs(123) = 1+2+3). Here is a more functional programming stylish approach. I do not know whether it can be made faster than this.
object Solution {
def qs(n: BigInt): BigInt = n.toString.foldLeft(BigInt(0))((n, ch) => n + (ch - '0').toInt)
def main(args: Array[String]) {
val input = scala.io.Source.stdin.getLines
val Array(n, k) = input.next.split(" ").map(BigInt(_))
println(Stream.iterate(k * qs(n))(qs(_)).find(_ < 10).get)
}
}

Improve efficiency of modules

I am running the loop in this method for around 1 million times but it is taking a lot of time maybe due O(n^2) , so is there any way to improve these two modules :-
def genIndexList(length,ID):
indexInfoList = []
id = list(str(ID))
for i in range(length):
i3 = (str(decimalToBase3(i)))
while len(i3) != 12:
i3 = '0' + i3
p = (int(str(ID)[0]) + int(i3[0]) + int(i3[2]) + int(i3[4]) + int(i3[6]) + int(i3[8]) + int(i3[10]))%3
indexInfoList.append(str(ID)+i3+str(p))
return indexInfoList
and here is the method for to convert number to base3 :-
def decimalToBase3(num):
i = 0
if num != 0 and num != 1 and num != 2:
number = ""
while num != 0 :
remainder = num % 3
num = num / 3
number = str(remainder) + number
return int(number)
else:
return num
I am using python to make a software and these 2 functions are a part of it.Please suggest why these 2 methods are so slow and how to improve efficiency of these methods.
The first function can be reduced to:
def genIndexList(length, ID):
indexInfoList = []
id0 = str(ID)[0]
for i in xrange(length):
i3 = format(decimalToBase3(i), '012d')
p = sum(map(int, id0 + i3[::2])) % 3
indexInfoList.append('{}{}{}'.format(ID, i3, p))
return indexInfoList
You may want to make it a generator instead:
def genIndexList(length, ID):
id0 = str(ID)[0]
for i in xrange(length):
i3 = format(decimalToBase3(i), '012d')
p = sum(map(int, id0 + i3[::2])) % 3
yield '{}{}{}'.format(ID, i3, p)
The second function could be:
def decimalToBase3(num):
if 0 <= num < 3: return num
result = ""
while num:
num, digit = divmod(num, 3)
result = str(digit) + result
return int(result)
Next step; you are just generating a sequence of base-3 digits. Just generate these directly:
from itertools import product, imap
def base3sequence(l=12, digits='012'):
return imap(''.join, product(digits, repeat=l))
This produces base3 values, 0-padded to 12 digits:
>>> gen = base3sequence()
>>> for i in range(10):
... print next(gen)
...
000000000000
000000000001
000000000002
000000000010
000000000011
000000000012
000000000020
000000000021
000000000022
000000000100
and genIndexList() becomes:
from itertools import islice
def genIndexList(length, ID):
id0 = str(ID)[0]
for i3 in islice(base3sequence(), length):
p = sum(map(int, id0 + i3[::2])) % 3
yield '{}{}{}'.format(ID, i3, p)

Optimizing the damerau version of the levenshtein algorithm to better than O(n*m)

Here is the algorithm (in ruby)
#http://en.wikipedia.org/wiki/Damerau%E2%80%93Levenshtein_distance
def self.dameraulevenshtein(seq1, seq2)
oneago = nil
thisrow = (1..seq2.size).to_a + [0]
seq1.size.times do |x|
twoago, oneago, thisrow = oneago, thisrow, [0] * seq2.size + [x + 1]
seq2.size.times do |y|
delcost = oneago[y] + 1
addcost = thisrow[y - 1] + 1
subcost = oneago[y - 1] + ((seq1[x] != seq2[y]) ? 1 : 0)
thisrow[y] = [delcost, addcost, subcost].min
if (x > 0 and y > 0 and seq1[x] == seq2[y-1] and seq1[x-1] == seq2[y] and seq1[x] != seq2[y])
thisrow[y] = [thisrow[y], twoago[y-2] + 1].min
end
end
end
return thisrow[seq2.size - 1]
end
My problem is that with a seq1 of length 780, and seq2 of length 7238, this takes about 25 seconds to run on an i7 laptop. Ideally, I'd like to get this reduced to about a second, since it's running as part of a webapp.
I found that there is a way to optimize the vanilla levenshtein distance such that the runtime drops from O(n*m) to O(n + d^2) where n is the length of the longer string, and d is the edit distance. So, my question becomes, can the same optimization be applied to the damerau version I have (above)?
Yes the optimization can be applied to the damereau version. Here is a haskell code to do this (I don't know Ruby):
distd :: Eq a => [a] -> [a] -> Int
distd a b
= last (if lab == 0 then mainDiag
else if lab > 0 then lowers !! (lab - 1)
else{- < 0 -} uppers !! (-1 - lab))
where mainDiag = oneDiag a b (head uppers) (-1 : head lowers)
uppers = eachDiag a b (mainDiag : uppers) -- upper diagonals
lowers = eachDiag b a (mainDiag : lowers) -- lower diagonals
eachDiag a [] diags = []
eachDiag a (bch:bs) (lastDiag:diags) = oneDiag a bs nextDiag lastDiag : eachDiag a bs diags
where nextDiag = head (tail diags)
oneDiag a b diagAbove diagBelow = thisdiag
where doDiag [_] b nw n w = []
doDiag a [_] nw n w = []
doDiag (apr:ach:as) (bpr:bch:bs) nw n w = me : (doDiag (ach:as) (bch:bs) me (tail n) (tail w))
where me = if ach == bch then nw else if ach == bpr && bch == apr then nw else 1 + min3 (head w) nw (head n)
firstelt = 1 + head diagBelow
thisdiag = firstelt : doDiag a b firstelt diagAbove (tail diagBelow)
lab = length a - length b
min3 x y z = if x < y then x else min y z
distance :: [Char] -> [Char] -> Int
distance a b = distd ('0':a) ('0':b)
The code above is an adaptation of this code.

Resources