Interpret the meaning of one line of Python3 code [duplicate] - python-3.x

This question already has answers here:
is_max = s == s.max() | How should I read this?
(5 answers)
Closed last month.
I am a beginner for Python3. Here I have one question to bother you. In the function below:
def highlight_min(s):
'''
highlight the minimum in a Series red.
'''
is_max = s == s.min()
return ['background-color: red' if v else '' for v in is_max]
What does is_max = s == s.min() mean?
Thank you.

s appears to be an array of some sort. The result of is_max in this operation will be a boolean type array the same size as s. Any element in s that is the same as the minimum of the array s will have the value True, else it will have the value False .
The following line is a loop through is_max that returns a python list. if v queries if an element is True in is_max and assigns the string 'background-color: red' if it is or an empty string if not.
I suspect that the function was copied from the original probably called 'highlight_max' and is_max should really be is_min.

Related

Checking words using "YNEOS"

In this problem, I take two strings from the user, the first string being s and the second string being t. If t is the reverse of s, I print "YES" else I print "NO".
Here is my code which gives me expected outputs:
s = input()
t = input()
if t == s[::-1]:
print("YES")
else:
print("NO")
But I found another approach that I am curious to understand, but the slicing part is making me confused. Here the code goes:
print("YNEOS"[input()!=input()[::-1]::2])
Trying to find a good explanation, so StackOverflow is what came to my mind before anything else.
Let's first extract the parts of that expression that concern the input/output and the string reversal. We then get this solution:
s = input()
t = input()
trev = t[::-1]
result = "YNEOS"[s != trev::2]
print(result)
The focus of the question is on the expression "YNEOS"[s != trev::2]
Now we get to the "trick" that is performed here. The expression s != trev can be either False or True. This boolean value becomes the first part in the slicing. You'd expect to have the start index of the slice at this position. But the boolean value will also work, as booleans are a subclass of integers, and False is 0 and True is 1. So the above expression evaluates to either:
"YNEOS"[0::2]
or
"YNEOS"[1::2]
The 2 serves as the step, and so "YNEOS"[0::2] will take the characters at indices 0, 2 and 4 ("YES"), while "YNEOS"[1::2] takes the characters at indices 1 and 3 ("NO").
I hope this clarifies it.

for loop doesn't itterate through all the data? [duplicate]

This question already has answers here:
How to remove items from a list while iterating?
(25 answers)
Closed 1 year ago.
data = [1, 2, 3, 4, 5]
for x in data:
print(x)
if data.count(x) < 2:
data.remove(x)
Hello Guys,
so I am currently working through py.checkio.org and am at a point where I have to remove all the numbers that are unique in a list.
When I run my code without the if statement I get an output counting from 1 to 5. But once I run the for loop with the if statement the for loop only runs through the data for every second number and my output is 1 3 5. Can anyone please tell me what is happening here?
While the from #Stef and #0x5453 are both relevant to your problem. The comment from #ConnorTJ is patently wrong. The remove function does not remove the item at the index but the first occurrence of the item.
To answer your question, about what's going on here, let[s examine your code:
The first pass through the value of x is 1
You print the value of x
You then test to see if the number of occurrences of x is less than 2
Since the answer is yes, you proceed to remove the item from the list.
The second pass through the list the For loop picks up the next value in the list (at index 1) which is now the value 3
You print the value 3
You check to see if the count of 3 is less than 2
Since the count is less you remove that item from the list.
This process than continues
Simple solution, use filter()
Construct an iterator from those elements of iterable for which function returns true
it returns a list of the list items that the function returned true for.
example:
x = [1,1,2,2,3,4]
x = filter(lambda f: (x.count(f)<2), x)
x = list(x)
print(x)
or in short: print(list(filter(lambda f: (x.count(f)>=2),x)))
output is [1,1,2,2]

Python 3 : List of odd numbers [duplicate]

This question already has answers here:
Python "for i in" + variable
(3 answers)
Closed 2 years ago.
I'm trying to return a list of odd numbers below 15 by using a python user-defined function
def oddnos(n):
mylist = []
for num in n:
if num % 2 != 0:
mylist.append(num)
return mylist
print(oddnos(15))
But I'm getting this error :
TypeError: 'int' object is not iterable
I didn't understand what exactly this means, please help me find my mistake
Because 15 is an integer, not a list you need to send the list as an input something like range(0,15) which will give all numbers between 0 and 15.
def oddnos(n):
mylist = []
for num in n:
if num % 2 != 0:
mylist.append(num)
return mylist
print(oddnos(range(0,15)))
When you're passing values to the function oddnos, you're not passing a list of values till 15, rather only number 15. So the error tells you, you're passing an int and not a list, hence not iterable.
Try to use range() function directly in the for loop, pass your number limit to the oddnos function.

Return Statement is not working properly in recursive function of Python

Hi i have a python code for DFS algorithm. I need to return when i reached to "GoalNode". But my function don't return, it works until the reach all the nodes. I guess problem is i don't know how recursive function works. My function must stop in bolded code lines. How can i solve this problem
def DFS(visited, StartNode, GoalNode):
index =(list(MainDictionary).index(StartNode))
visited[index] = True
print(StartNode)
**# it has to return here out put must be only F - C but function reaches all the nodes
if StartNode == GoalNode:
return**
#This line is for accessing my dictionary data type
values = ReturnKeyVal(StartNode)
for key in values:
index =(list(values).index(key))
if visited[index] == False and values[key] != 0:
DFS(visited, key, GoalNode)
def ReturnKeyVal(Target):
for keys, values in MainDictionary.items():
if keys == Target:
return values
visited = [False] * (len(MainDictionary))
DFS(visited,"F", "C")
While I have other questions about your code (Because I can't figure out what ReturnKeyVal is supposed to do, if MainDictionary is a normal python dictionary it would just return the value corresponding to the key but if you just wanted to do that why would you write a function for it? Getting the corresponding value is what keys are for. Which is why I asked for the MainDictionary.) the problem is pretty simple: You don't check whether a function call has found the goal so the loop will continue regardless of whether it has been found. The return just ends the current function call not the entire recursion. Return true if it is found and then check the return value and keep returning true.

This code is not giving the value of the new sorted list . Can someone tell me the error in this code? [duplicate]

This question already has answers here:
Why does my recursive function return None?
(4 answers)
Closed 3 years ago.
I am making a class for sorting algorithms . But there seems to be some error which is giving the value of my sorted linked list as None. I cannot identify the missing piece of the code. Please help.
#Bubble sort algorithm
class Sort:
def Bubble(self,llister):
for i in range(len(llister)-1,0,-1):
for j in range(i):
if llister[j]>llister[j+1]:
llister[j],llister[j+1]= llister[j+1],llister[j]
if __name__=='__main__':
obj = Sort()
llist = [2,5,3,15,10,13,1]
print("The list before bubble sort : " ,llist)
ans = obj.Bubble(llist)
print("The list after bubble sort :" ,ans)
Unfortunately Python doesn't do any type checking. Your bubble function doesn't contain a return statement; it therefore returns None by default. ans is therefore None and None is what is printed.
In order to avoid returning None, return a result explicitly instead e.g. return 'Some'.

Resources