I have the following code:
def check(onen,twon,threen,fourn,fiven):
while ((onen != twon) and (onen != threen) and (onen != fourn) and (onen != fiven)):
return onen
else:
onen = random.randint(1,45)
I'd like to ask how to make it like this:
def check(onen,twon,threen,fourn,fiven):
while ((onen != twon) and (onen != threen) and (onen != fourn) and (onen != fiven)):
return onen
else:
onen = random.randint(1,45)
(check the condition on while again)
I want to make this loop: if the condition is false, check and check again until it's true.
It seems like you have it backwards. Try this:
while not condition:
change condition
return that
For your specific example:
def check(onen, twon, threen, fourn, fiven):
while not ((onen != twon) and (onen != threen) and (onen != fourn) and (onen != fiven)):
onen = random.randint(1,45)
return onen
Or shorter:
def check(onen, twon, threen, fourn, fiven):
while onen in (twon, threen, fourn, fiven):
onen = random.randint(1,45)
return onen
Or much shorter, without the loop (only feasible for small range, though):
def check(onen, twon, threen, fourn, fiven):
return random.choice([x for x in range(1, 46)
if x not in (twon, threen, fourn, fiven)])
Note, however, that neither of those will change the value of onen outside of the function (unless, of course, you do onen = check(...)).
What you are basically looking for is a do-while loop. Python has no do-while loop, but you can easily emulate one:
def something():
while True:
# ...
# perform some task
if [condition]:
return [result]
So here you have to fill in [condition] that checks if the result is satisfying, and [result] is what you want to return. As long as the condition is not met, Python will go for another loop.
Example:
Say you want to query the user for input, you can do this with:
def something():
while True:
try:
x = int(input('Enter a number'))
except ValueError:
x = None
if x is not None:
return x
So here we will keep querying for a number until it is a valid one.
Of course we sometimes can fold the task and condition check together. Here we can transform the above program into:
def something():
while True:
try:
return int(input('Enter a number'))
except ValueError:
pass
From the update to your question it seems you just need to invert the sense of the while to get what you want:
def condition(onen, twon, threen, fourn, fiven):
return ((onen != twon) and (onen != threen) and (onen != fourn) and (onen != fiven))
def check(onen, twon, threen, fourn, fiven):
while not condition(onen, twon, threen, fourn, fiven):
onen = random.randint(1,45)
return onen
You can try this also:
something(condition):
# evaluate and return condition value
while(condition is not satisfactory):
condition = something(condition)
else:
# code post satisfaction of condition
def something():
while(condition):
return that
else:
return this
something() # just callback the function
You can also remove the else statment and just callback the current function
Related
I am trying to get this attribute which is very deeply nested.
The problem is that some of the values on the way tends to be None.
here is how I did it (the wrong way).
def name(x):
x = x["relay_rendering_strategy"]
if x:
x = x["view_model"]
if x:
x = x["profile"]
if x:
x = x["event_place"]
if x:
x = x["contextual_name"]
if x:
return x.lower()
return ''
data = [x for x in get_events() if name(x) == 'ved siden af']
In kotlin there is a nice syntax like this:
val name = first?.second?.third?.andSoFourth ?: ''
Is there a similar awesome way you can do it in python???
You can do something similar with dict.get and default values:
def name(x):
return x.get("relay_rendering_strategy", {}).get("view_model", {}).get("profile", {}).get("event_place", {}).get("contextual_name", "").lower()
Or use a simple try-except:
def name(x):
try:
return x["relay_rendering_strategy"]["view_model"]["profile"]["event_place"]["contextual_name"].lower()
except KeyError:
return ""
Or simply keep the nesting level down with a loop to be more DRY:
def name(x):
for k in ("relay_rendering_strategy","view_model","profile","event_place","contextual_name"):
if k not in x:
return ""
x = x[k]
return x.lower()
In python, it is better to ask forgiveness than permission.
Using try/except (as suggested by #Iain Shelvington).
def name(x):
try:
return x["relay_rendering_strategy"]["view_model"]["profile"]["event_place"]["contextual_name"].lower()
except (KeyError, AttributeError):
return ""
def str_tree(atree,indent_char ='.',indent_delta=2):
def str_tree_1(indent,atree):
if atree == None:
return ''
else:
answer = ''
answer += str_tree_1(indent+indent_delta,atree.right)
answer += indent*indent_char+str(atree.value)+'\n'
answer += str_tree_1(indent+indent_delta,atree.left)
return answer
return str_tree_1(0,atree)
def build_balanced_bst(l):
if len(l) == 0:
return None
else:
mid = (len(l)-1)/2
if mid >= 1:
build_balanced_bst(l[:mid])
build_balanced_bst(l[mid:])
else:
return
I am working on the build_balanced_bst(l), the build_balanced_bst(l) takes a list of unique values that are sorted in increasing order. calling build_ballanced_bst( list(irange(1,10)) returns a binary search tree of height 3 that would print as:
......10
....9
..8
......7
....6
5
......4
....3
..2
....1
the str_tree function is used to print what the build_balanced_bst() function returns. my str_tree function is correct, I cannot change it. I can only change the build_balanced_bst() function.
I used the middle value in the list as the root’s value. when I try to call the build_balanced_bst(l) in the below, it does not print anything.
l = list(irange(1,10))
t = build_balanced_bst(l)
print('Tree is\n',str_tree(t),sep='')
can someone help me to fix my build_balanced_bst(l) function? many thanks.
str_tree() doesn't do anything: It just defines a nested function and implicitly returns None.
As a start, you can have str_tree do something:
def str_tree(atree, indent_char ='.', indent_delta=2):
def str_tree_1(indent, atree):
# Note that str_tree_1 doesn't use the indent argument
if atree == None:
return ''
return str_tree_1(indent_delta, atree)
But this is just a start.
I have two functions that contain mostly the same code. One returns "True" if the array passed in contains all positive numbers while the other returns "True" if the array contains all numbers that are divisible by 10.
I want to combine these two functions into a function like this:
def master_function(array, function):
for i in array:
if function:
result = True
else:
result = False
break
print(result)
return result
The only part that would vary is the "function" in the If statement. When I write functions with the missing line they don't get called as the program executes.
def positive_integers(array):
i >= 0
def divisible_by_10(array):
i%10 == 0
The test code isn't executed either.
master_function([10,20,30,35],divisible_by_10)
Your functions aren't returning anything, and you need to give them access to i:
def positive_integers(i):
return i >= 0
def divisible_by_10(i):
return not i%10
def master_function(array, function):
for i in array:
if function(i):
result = True
else:
result = False
break
print(result)
return result
Your function don't return anything. Also, you need read about all and any:
def positive_integers(array):
return all(i >= 0 for i in array)
def divisible_by_10(array):
return all(i % 10 == 0 for i in array)
def master_function(array, function):
return function(array)
def master_function(array, function):
for i in array:
print str(i)
if function(i):
result = True
else:
result = False
print(result)
return result
def positive_integers(i):
if i >= 0:
return True
def divisible_by_10(i):
if i%10 == 0:
return True
master_function([10,20,30,35],divisible_by_10)
I apologise if I seem stupid here, but I am stumped... as stated I need to have this program that evaluates infix notation expressions using stacks, but I cannot for the life of me get this thing to work out appropriately.
If anyone could help me fix my code and possibly explain where I went wrong then I would be very appreciative. Also, sorry for the wonky formatting, this is my first post and I don't fully understand the code input format.
import operator
def Main():
#In main, necessary stacks are generated and
#all calculations and methods are called and preformed.
opStack = ArrayStack()
numStack = ArrayStack()
opList = ['*', '/', '+', '-']
nums = '1234567890'
parn = ['(', ')']
toEval = input('Enter the Expression: ')
toEval = toEval.split()
#print(toEval)
for each in toEval:
if each in nums:
numStack.push(each)
if each == parn[0]:
opStack.push(each)
if each in opList:
if each == opList[2] or opList[3]:
opStack.push(each)
if each == opList[0] or opList[1]:
while opStack.top() == (opList[2] or opList[3]) and len(opStack) > 0 and len(numStack) >= 2:
ans = Eval(numStack.pop(),numStack.pop(),opStack.pop())
numStack.push(ans)
opStack.push(each)
if each == parn[1]:
while opStack.top() != "(":
ans = Eval(numStack.pop(),numStack.pop(),opStack.pop()) # this line is poping the empty stack
numStack.push(ans)
opStack.pop()
while opStack.is_empty() != True:
ans = Eval(numStack.pop(),numStack.pop(),opStack.pop())
numStack.push(ans)
print(ans)
def Eval(num1, num2, op):
#two numbers and an op are pulled from stacks, op checked against dict
#dict should supply necessary
ops2 = {"+": operator.add, "-": operator.sub, "*": operator.mul, "/": operator.truediv}
op_char = op
op_func = ops2[op_char]
res = op_func(float(num1), float(num2))
return res
class ArrayStack:
# LIFO Stack implementation using a Python list as underlying storage.
def __init__(self):
# Create an empty stack.
self._data = [] # nonpublic list instance
def __len__(self):
# Return the number of elements in the stack.
return len(self._data)
def is_empty(self):
# Return True if the stack is empty.
return len(self._data) == 0
def push(self, e):
# Add element e to the top of the stack.
self._data.append(e) # new item stored at end of list
def top(self):
# Return (but do not remove) the element at the top of the stack.
# Raise Empty exception if the stack is empty.
if self.is_empty():
raise Empty( 'Stack is empty' )
return self._data[-1] # the last item in the list
def pop(self):
#Remove and return the element from the top of the stack (i.e., LIFO).
#Raise Empty exception if the stack is empty.
if self.is_empty():
raise Empty( 'Stack is empty' )
return self._data.pop() # remove last item from list
Main()
These two if statements are always true:
if each == opList[2] or opList[3]:
if each == opList[0] or opList[1]:
You want something more like this:
if each == opList[2] or each == opList[3]:
And so on.
There may be other problems but that one certainly will keep your program from working.
I have a function that needs input as True/False that will be fed in from another function. I would like to know what is the best practice to do this. Here is the example I am trying:
def feedBool(self, x):
x = a_function_assigns_values_of_x(x = x)
if x=="val1" or x == "val2" :
inp = True
else
inp = False
feedingBool(self, inp)
return
def feedingBool(self, inp) :
if inp :
do_something
else :
dont_do_something
return
You can do:
def feedBool(self, x):
x = a_function_assigns_values_of_x(x = x)
feedingBool(self, bool(x=="val1" or x == "val2"))
Or, as pointed out in the comments:
def feedBool(self, x):
x = a_function_assigns_values_of_x(x = x)
feedingBool(self, x in ("val1","val2"))
why not just:
inp = x in ("val1", "val2")
of cause it can be compacted even more directly in the call to the next function, but that will be at the cost of some readability, imho.
You usually put the test in a function and spell out the consequence:
def test(x):
# aka `return x in ("val1", "val2")` but thats another story
if x=="val1" or x == "val2" :
res = True
else
res = False
return res
def dostuff(inp):
# i guess this function is supposed to do something with inp
x = a_function_assigns_values_of_x(inp)
if test(x):
do_something
else :
dont_do_something
dostuff(inp)