List comprehension & ternary operator -> SyntaxError - python

With text, type, scope being string and val, altval being int, why is the following code syntatically not correct? (I know this isn't the correct way to do it aesthatically but would that affect syntax?)
result = [(i[val:] if scope=="before" else i[:val] if scope=="after" else i[val:altval] if scope=="beforeafter" else i) if j<=until for j,i in enumerate(text.split("\n"))]
Broken down into lines:
result = [
(i[val:] if scope=="before"
else i[:val] if scope=="after"
else i[val:altval] if scope=="beforeafter"
else i) if j<=until
for j,i in enumerate(text.split("\n"))]
With lines split up as this, the SyntaxError is at the last line:
for j,i in enumerate(text.split("\n"))]
^
Version: Python 3.x
System: Windows
What am I missing? Is it a list comprehension limitation?

Simply move the last if condition after for:
result = [
(
i[val:] if scope=="before"
else i[:val] if scope=="after"
else i[val:altval] if scope=="beforeafter"
else i
) for j, i in enumerate(text.split("\n"))
if j <= until
]
Online Demo

Related

Function that is made to remove round brackets does not work, Python 3

I have a function that takes in an argument, preferably a string, takes each value of the string and implements them as elements in a list. After that, it iterate's through the list and is supposed to delete/remove elements that are round brackets, so basically, these: ( ). Here is the code:
def func(s):
n = 0
s = [i for i in s]
for i in s:
if s[n] == "(" or s[n] == ")":
del s[n]
else:
n += 1
continue
return s
print(func("ubib0_)IUBi(biub()()()9uibib()((U*H)9g)*(GB(uG(*UV(V79V*&^&87vyutgivugyrxerdtufcviO)()(()()()(0()90Y*(g780(&*^(UV(08U970u9yUV())))))))))"))
However, the function stops the iteration and ends/returns the list early (when some round brackets are still there).
I also went with another way, a way that works:
def func(s):
n = 0
s = [i for i in s]
s2 = [i for i in s if i != "(" and i != ")"]
return s2
print(func("ubib0_)IUBi(biub()()()9uibib()((U*H)9g)*(GB(uG(*UV(V79V*&^&87vyutgivugyrxerdtufcviO)()(()()()(0()90Y*(g780(&*^(UV(08U970u9yUV())))))))))"))
Why does this work while the other way doesn't? They like they'd output the same result.
What am I doing wrong in the first example?
Your concept is correct, in that you either delete the current item or increment n.
Where you've gone wrong is that you're iterating over each letter which doesn't make sense given the above info. Changing for i in s to while n < len(s) will fix the problem.
A couple of things you may find useful:
list(s) looks cleaner than [i for i in s]
i not in "()" is another way to write i != "(" and i != ")"
At the beginning when you're increasing n, n equals to i. But when you meet a bracket, n has the same value the next iteration, and i increases. It happens every time s[n] == "(" or s[n] == ")" and the difference between n's and i's values increases.
To work correctly you program needs to check every symbol in the list (string) for equality of either '(' or ')' using s[n], but it doesn't happen because the iteration stops when i achieves the end of the list and n at that time is much less than i and it hasn't achieved the end of the list yet and hasn't checked all symbols.

Change character in list Python Flask

so here is my relativly simple code:
#app.route("/[<string:pfade>]")
def testaufruf(pfade):
s=list(pfade)
part = [i for i,x in enumerate(s) if x=="$"]
print(part)
s[part]="\\"
print(part)
My problem is I want to pass something like 127.0.0.1:5000/[Test$path1]
now I take this Test$path1 make it an list and want to replace every $ with an \
These lines work:
s=list(pfade)
part = [i for i,x in enumerate(s) if x=="$"]
print(part)
They return me the place where the $ is located but the second part to replace the $ does not work. I did search a lot but couldnt find a solution to this problem.
Thanks for help in advance.
Strings have a replace method:
part = pfade.replace('$', '\\')
Note the \ is repeated for escaping.
this line is gonna return a list of integers
part = [i for i,x in enumerate(s) if x=="$"]
and you're simply trying to index s with a list, you're facing the following error
TypeError: list indices must be integers or slices, not list.
to solve this:
parts = [i for i,x in enumerate(s) if x=="$"]
for part in parts:
s[part] = '\\'
print(s)
So it was a pretty simple fix:
instead of using part = [i for i,x in enumerate(s) if x=="$"]
I just used: part = s.index("$", 0)
than s[part] = "\\" replaces the $ with "\"

C++ nested for loops representation in Python

I have been coding in C++ and Java for some time. I have started to code in Python recently as well. However, I got stuck in the case of nested for loops in Python.
I have written following code in C++. What will be the equivalent code of it in Python?
for(int i = 0; i<a.size();i++){
for(int j = i; j<a.size();j++)
{
if a[i] != a[j]
/*some code */
}
}
I tried to use enumerate as follows, but it fails:
for i, val in enumerate(lst):
for j=i,val2 in enumerate(lst):
if val != val2
#some code
So how can I represent the C++ nested loops in python?
import itertools
for val1, val2 in itertools.combinations(lst, 2):
if val1 != val2:
combinations will loop over all cases of choosing two distinct elements from your list which is what your nested for loops are doing anyhow. Note that your second nested for loop is initialized at j=i, but that first case will always fail to process anyhow because it will never pass the conditional.
If you really, really need the indices, and usually you shouldn't, you can do:
for (i, val1), (j, val2) in itertools.combinations(enumerate(lst), 2):
if val1 != val2:
As mentioned elsewhere, enumerate does one thing (provide indexes). It will not truncate or skip around in your list. If you wanted to use enumerate, one option is to pass a list slice instead of the full list, and use the start= keyword argument to start the index numbering correctly:
for i, val in enumerate(lst):
for j, val2 in enumerate(lst[i:], start=i):
if val != val2:
#some code
The enumerate function doesn't have a start index, however range does in that sense. It should be noted that while enumerate(sequence, start=0) has a start parameter, it only specifies the start of the returned index, and not the first index of which the list is accessed.
So you could do it like this:
n = len(lst)
for i in range(n):
val = lst[i]
for j in range(i, n):
val2 = lst[j]
if val != val2:
#some code

Python-Does For loop have a return value?(I know this is lame,but take a look)

int(x) for x in range(3)
I know this for loop is absurd,but bear with me.Here in this block of code what i think is happening is (Correct me if i am wrong)-X is assigned with the 0 value at first and will return,Okay this is fine.
[1 for x in range(3) if a[x] > b[x]]
In this case what is happening is if the statement is correct it is returning 1 and if it isn't it is returning nothing.
Am i getting this right, Is saying for loops have return values right?
ThankYou.
A good way to see the execution of a Python script is to use this tutor. But you need to indicate what a and b are (lists ? strings ?).
a = [4,5,6,8]
b = [1,2,3,4]
print([1 for x in range(3) if a[x] > b[x]])
Output :
[1,1,1]
This is equivalent to :
tmp = []
for x in range(3):
if a[x] > b[x]:
tmp.append(1)
print(tmp)
What you have posted seems like part of a list comprehension (you probably removed the outer []-braces).
Have a look here: https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions

Not able to find what is the syntax error in the code?

def makeInverseIndex(strlist):
return { s:{ j if strlist[i] in strlist[j].split() for j in range(len(strlist)) }
for (i,s) in enumerate(strlist) }
What is the syntax error in the code in Python??
You can't have an if statement to the left of for inside any comprehension unless you also have an else part (ternary operator). You need to move if strlist[i] in strlist[j].split() to the right,
def makeInverseIndex(strlist):
return {s:{j for j in range(len(strlist)) if strlist[i] in strlist[j].split()}
for (i,s) in enumerate(strlist)}

Categories

Resources