Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
i am trying to make the same functionality using lambda to get the plural of a word, this is my function (i want to write it in lambda form).
import re
def plural(noun):
if re.search("[sxz]$",noun):
return re.sub("$","es",noun)
elif re.search("[^aeioudgkprt]h$",noun):
return re.sub("$","es",noun)
elif re.search("[^aeiou]y$",noun):
return re.sub("y$","ies",noun)
else:
return noun+"s"
i want to make the same function job using lambda ,not sure where to start.
(i am using python 2.7)
import inflect
result = inflect.engine().plural('bike')
import re
rules=((lambda word:re.search('[sxz]$',word),lambda word:re.sub('$','es',word)),
(lambda word: re.search('[^aeioudgkprt]h$', word),lambda word: re.sub('$', 'es', word)),
(lambda word: re.search('[^aeiou]y$', word),lambda word: re.sub('y$', 'ies', word)),
(lambda word: re.search('$', word),lambda word: re.sub('$', 's', word)))
def plural(noun):
for findpattern,rule in rules:
if findpattern(noun):
return rule(noun)
print plural('boy')
This your functions as lambda rules, it will search for pattern if it's true,apply rule
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
Below is my data.
'{"Data": {"a":5647953897,"b":"323299901059958183671030","c":1605858513465}}{"Data": {"a":5647953897,"b":"323299901059958183671030","c":1605858513465}}'
My output should be as below
[{"a":5647953897,"b":"323299901059958183671030","c":1605858513465},{"a":5647953897,"b":"323299901059958183671030","c":1605858513465}]
This should solve your case.
from json import JSONDecoder, JSONDecodeError
import re
NOT_WHITESPACE = re.compile(r'[^\s]')
data = '''{"Data": {"a":5647953897,"b":"323299901059958183671030","c":1605858513465}}{"Data": {"a":5647953897,"b":"323299901059958183671030","c":1605858513465}}'''
def decode_stacked(document, pos=0, decoder=JSONDecoder()):
while True:
match = NOT_WHITESPACE.search(document, pos)
if not match:
return
pos = match.start()
try:
obj, pos = decoder.raw_decode(document, pos)
except JSONDecodeError:
raise
yield obj
for obj in decode_stacked(data):
print(obj)
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
Is there any magic python way to get the firsts letters of each name and join with '#company.com' to create a email address?
Here is how I did:
name = ['Elon Reeve Musk']
full_name = [word[0].lower() for word in name[0].split(' ')]
firts_letters = "".join(full_name)
username = '%s#company.com' %(firts_letters)
The result is erm#company.com
Here's some "python magic"
name = ['Elon Reeve Musk']
f"{''.join(filter(str.isupper, name[0]))}#company.com".lower()
>>> erm#company.com
Whether this is better than your method is debatable. Most of the time a few lines of easy to read code is better than a one line hack.
My recommendation would be
name = ['Elon Reeve Musk']
initials = ''.join(word[0] for word in name[0].split())
f'{initials.lower()}#company.com'
>>> erm#company.com
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
Could someone help me with following function:
def nagios_chart():
alpha = [chr(item).upper() for item in range(ord('b'), ord('l')+1)]
for idx, column in enumerate(alpha):
print worksheet.write_column('column + 1', nagios_data[idx])
if __name__ == '__main__':
nagios_chart()
I need output like this:
worksheet.write_column('B1', nagios_data[0])
worksheet.write_column('C1', nagios_data[1])
worksheet.write_column('D1', nagios_data[2])
worksheet.write_column('E1', nagios_data[3])
worksheet.write_column('F1', nagios_data[4])
worksheet.write_column('G1', nagios_data[5])
worksheet.write_column('H1', nagios_data[6])
worksheet.write_column('I1', nagios_data[7])
worksheet.write_column('J1', nagios_data[8])
worksheet.write_column('K1', nagios_data[9])
worksheet.write_column('L1', nagios_data[10])
To use the column as a variable, remove it from the quotes so it isn't treated as a string literal. Then you can concatenate it with '1'.
def nagios_chart():
alpha = [chr(item).upper() for item in range(ord('b'), ord('l')+1)]
for idx, column in enumerate(alpha):
print worksheet.write_column(column + '1', nagios_data[idx])
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
import itertools
import math
import time
from time import time
from math import factorial
from math import sqrt
def pretty(string):
string=string.replace("(4)","4")
string=string.replace("factorial4","factorial(4)")
string=string.replace("sqrt4","sqrt(4)")
return string
def test(n):
start=time()
fails=0
for i in range(0,n+1):
if(fours(i))!=None:
print(fours(i))
else:
print("Failed: "+str(i))
fails+=1
return("\nFailed "+str(fails)+" out of "+str(n)+"\n\nTotal time: "+str(time()-start)[:4]+"\nAverage time: "+str((time()-start)/n)[:4])
def fours(goal):
operators = ['-','/','+','*','sqrt','^','factorial',"."]
brackets = ["{0}{1}{0}{2}{0}{3}{0}",
"({0}{1}{0}){2}{0}{3}{0}",
"({0}{1}{0}{2}{0}){3}{0}",
"({0}{1}({0}{2}{0})){3}{0}",
"(({0}{1}{0}){2}{0}){3}{0}",
"{0}{1}({0}{2}({0}{3}{0}))",
"{0}{1}(({0}{2}{0}){3}{0})",
"({0}{1}{0}){2}({0}{3}{0})"]
for combination in itertools.product(operators, repeat=3):
for bracket in brackets:
try:
formula = bracket.format("(4)", *combination).replace(".(4","(.4")
except ValueError:
pass
try:
if eval(formula)==goal:
return(pretty((formula + " = " + str(int(eval(formula))))))
except:
pass
print(test(20))
Here is the code for a solver for the "Four Fours"
puzzle.http://en.wikipedia.org/wiki/Four_fours
It basically work, but the problem is that it can only use the + - / * operators, because it can't have two operators in a row(Solutions like this (4-4)/4+factorial(4) aren't allowed because of this "+factorial" part).What I could do(but would be to slow) would be to make pairings like this.
['-', '/', '+', '*', '-sqrt', '-^', '-factorial', '-.', '/sqrt', '/^', '/factorial', '/.', '+sqrt', '+^', '+factorial', '+.', 'sqrt', '^', 'factorial', '.']
This is far too many operators.
What I would like to do, would be to try something like this
formula = bracket.format(["(4)","(4*)","(4-)","(4/)"], *combination).replace(".(4","(.4")
Except this syntax is invalid.
How can I do this?
Or if you have better ideas(which I'm sure some of you do) I am open to suggestions.
You could try converting it into pre or post-fix. You can allow it to use ['!','sqrt','.'] anytime. '^' would only be used if at least one four is still available to be pushed on the stack. And ['+','-','/','*'] would only be pushed if there are more operators than numbers (or something like that).
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
def getPressAve(odbname):
odb=openOdb(odbname)
lastFrame=odb.steps['Step-1'].frames[-1]
pressure=lastFrame.fieldOutputs['CPRESS']
press=[[0,0]] # sets the first element to [0,0]
for n in pressure.values:
gridPt=part1.nodes.getFromLabel(n.nodeLabel)
coord=assemb.getCoordinates(gridPt)
press.append([n.nodeLabel,n.data,coord])
press=avePress=press[1:] # removes the first element
press.sort(Comp_X)
print ('pressure extracted')
index=0
while index<len(press):
sum=0
tally=0
if index!=0:
sum=sum+press[index-1][1]
tally=tally+1
if index!=1:
sum=sum+press[index-2][1]
tally=tally+1
if index!=2:
sum=sum+press[index][1]
tally=tally+1
if index<len(press)-1:
sum=sum+press[index+1][1]
tally=tally+1
if index<len(press)-2:
sum=sum+press[index+2][1]
tally=tally+1
average=sum/tally
avePress[index][1]=average
index=index+1
odb.close()
print ('pressure averaged')
return avePress
In Python, indentation matters. As is, you're defining a function called getPressAve which does only this:
odb=openOdb(odbname)
After you've defined your function, you go on to do
lastFrame=odb.steps['Step-1'].frames[-1]
and such outside of the function. That's not what you want. The solution is to indent everything after that odb=openOdb(odbname) line to that level, so those lines are interpreted as being part of the body of the function.
You forgot to properly indent your code:
def getPressAve(odbname):
odb=openOdb(odbname)
...
print ('pressure averaged')
return avePress
As yours has not been, the return keyword is featured outside of a function, and hence the error: SyntaxError: 'return' outside function.