Invalid Syntax Python - syntax

def solution(t, p):
extracted_number = []
answer = 0
while(len(t) >= len(p)):
extracted_number.append(t[:len(p)])
t = t[1:]
for x in extracted_number:
if(int(x) <= int(p)):
answer +=1
return answer
I want to make the code concise, so I did this.
answer +=1 for x in extracted_number if (int(x) < int(p)) --> invalid syntax
How to revise?

I think you can try out answer=answer+1 and then u can return that answer variable

Related

Julia 1.0 UndefVarError - Scope of Variable

I am moving from Julia 0.7 to 1.0. It seems that Julia's rule for the scope of variables changed from 0.7 to 1.0. For example, I want to run a simple loop like this:
num = 0
for i = 1:5
if i == 3
num = num + 1
end
end
print(num)
In Julia 0.7 (and in most of other languages), we could expect num = 1 after the loop. However, it will incur UndefVarError: num not defined in Julia 1.0. I know that by using let I can do this
let
num = 0
for i = 1:5
if i == 3
num = num + 1
end
end
print(num)
end
It will print out 1. But I do want to get the num = 1 outside the loop and the let block. Some answers suggest putting all code in a let block, but it will incur other problems including UndefVarError while testing line-by-line. Is there any way instead of using let blocking? Thanks!
This is discussed here.
Add global as shown below inside the loop for the num variable.
num = 0
for i = 1:5
if i == 3
global num = num + 1
end
end
print(num)
Running in the Julia 1.0.0 REPL:
julia> num = 0
0
julia> for i = 1:5
if i == 3
global num = num + 1
end
end
julia> print(num)
1
Edit
For anyone coming here new to Julia, the excellent comment made in the answer below by vasja, should be noted:
Just remember that inside a function you won't use global, since the scope rules inside a function are as you would expect:
See that answer for a good example of using a function for the same code without the scoping problem.
Just remember that inside a function you won't use global, since the scope rules inside a function are as you would expect:
function testscope()
num = 0
for i = 1:5
if i == 3
num = num + 1
end
end
return num
end
julia> t = testscope()
1
The unexpected behaviour is only in REPL.
More on this here

hilbert matrix in octave to given Number

I'm supposed to create a Hilbert-Matrix H by the following input:
Hilbert(n=4):
This is what I tried. It's rubbish. Could anybody help me out here?
function H = hilbertmatrix(n)
i=1;
for i=1:n;`
H=[(1:(1/i+1)) (1:(1/i+1);
(1:(1/i+1)) (1:(1/i+1)]; `
end
endfunction
Just use hilb
hilb(4)
ans =
1.00000 0.50000 0.33333 0.25000
0.50000 0.33333 0.25000 0.20000
0.33333 0.25000 0.20000 0.16667
0.25000 0.20000 0.16667 0.14286
Ok, I think I got it. So I will answer my own question.
`function [H,h] = hilbertmatrix(n)
J = 1:n;
J = J(ones(n,1),:);
I = J';
E = single(ones(n,n));
H = E./(I+J-1); %H will give the hilbertmatrix in accordance to the
%code above
h = hilb(n); %h is for reference.
end
endfunction`
.

Algorithm to check matching parenthesis

This relates to the Coursera Scala course so I want to directly ask you NOT to give me the answer to the problem, but rather to help me debug why something is happening, as a direct answer would violate the Coursera honor code.
I have the following code:
def balance(chars: List[Char]): Boolean = {
val x = 0
def loop(list: List[Char]): Boolean = {
println(list)
if (list.isEmpty) if(x == 0) true
else if (list.head == '(') pushToStack(list.tail)
else if (list.head == ')') if(x <= 0) false else decreaseStack(list.tail)
else loop(list.tail)
true
}
def pushToStack(myList: List[Char]) { x + 1; loop(myList)}
def decreaseStack(myList: List[Char]) { x - 1; loop(myList)}
loop(chars)
}
A simple explanation:
If the code sees a "(" then it adds 1 to a variable. If it sees a ")" then it first checks whether the variable is equal to or smaller than 0. If this is the case, it returns false. If the value is bigger than 0 then it simply decreases one from the variable.
I have tried running the following:
if(balance("This is surely bad :-( ) (".toList)) println("balanced") else println("not balanced");
Clearly this is not balanced, but my code is returning balanced.
Again: I am not asking for help in writing this program, but rather help in explained why the code is returning "balanced" when clearly the string is not balanced
--EDIT--
def balance(chars: List[Char]): Boolean = {
val temp = 0;
def loop(list: List[Char], number: Int): Boolean = {
println(list)
if (list.isEmpty) if(number == 0) true
else if (list.head == '(') loop(list.tail, number + 1)
else if (list.head == ')') if(number <= 0) false else loop(list.tail, number - 1)
else loop(list.tail,number)
true
}
loop(chars,0)
}
^^ Still prints out balanced
You are using an immutable x when you really want a mutable x.
Here, let me rewrite it for you in a tail recursive style to show you what you're actually doing:
#tailrec def loop(myList: List[Char], cur: Int = 0): Boolean = myList match{
case "(" :: xs =>
val tempINeverUse = cur+1
loop(xs, cur) //I passed in 0 without ever changing "cur"!
case ")" :: xs if cur < 0 => false //This is a bug, regardless if you fix the rest of it
case ")" :: xs =>
val tempINeverUse = cur-1
loop(xs, cur) //Passed in 0 again!
case x :: xs => loop(xs, cur)
case Nil => cur == 0 //Since I've never changed it, it will be 0.
}
You need to keep a context of parenthesis in comments or in quotes as well. You can use a counter to achieve that. If the counter is set for a comment or a double quote then ignore any parenthesis that comes your way. Reset the counter whenever you find a finishing comment or double quote

Basic If/Else statement question

I'm getting a strange error: "syntax error, unexpected $end, expecting kEND" and it points to the final line of my code.
New to Ruby and not sure what I'm doing wrong here. Any help would be fantastic. Thanks!
def add(x,y)
if(x > y)
c = x + y
return c
else
puts "Y is too big"
return
end
a = 4
b = 6
add(a,b)
BTW, you can refactor your if..end statement out completely if you prefer
def add(x,y)
return (x + y) if(x > y)
puts "Y is too big"
end
Corrected code (you are missing one end for the if-else):
def add(x,y)
if(x > y)
c = x + y
return c
else
puts "Y is too big"
return
end
end
a = 4
b = 6
add(a,b)
Both if statements and function definitions require an end statement to terminate them.
Try adding another end after your existing end and your problem should go away.
wap to input principle, rate, time and choice. if choice is 1 than calculate simple interest, if choice is 2 calculate compund interest and if it is other than 1 or 2 print "Enter valid choice"

ruby - simplify string multiply concatenation

s is a string, This seems very long-winded - how can i simplify this? :
if x === 2
z = s
elsif x === 3
z = s+s
elsif x === 4
z = s+s+s
elsif x === 5
z = s+s+s+s
elsif x === 6
z = s+s+s+s+s
Thanks
Something like this is the simplest and works (as seen on ideone.com):
puts 'Hello' * 3 # HelloHelloHello
s = 'Go'
x = 4
z = s * (x - 1)
puts z # GoGoGo
API links
ruby-doc.org - String: str * integer => new_str
Copy—Returns a new String containing integer copies of the receiver.
"Ho! " * 3 #=> "Ho! Ho! Ho! "
z=''
(x-1).times do
z+=s
end
Pseudo code (not ruby)
if 1 < int(x) < 7 then
z = (x-1)*s
For example for a rating system up to 5 stars you can use something like this:
def rating_to_star(rating)
'star' * rating.to_i + 'empty_star' * (5 - rating.to_i)
end

Resources