Python self defined function with None argument - python

I want to define my own function as below:
def myown(df, ADD1, ADD2 = None, OtherArgument_1, OtherArgument_2):
tmp = df
tmp['NEWADD'] = (tmp['ADD1'] + ' ' + tmp['ADD2']).str.strip()
return tmp
I know this is incorrect so I can add if statement in the function.
def myown(df, ADD1, ADD2 = None, OtherArgument_1, OtherArgument_2):
tmp = df
if ADD2 == None:
tmp['NEWADD'] = tmp[ADD1].str.strip()
else:
tmp['NEWADD'] = (tmp[ADD1] + ' ' + tmp[ADD2]).str.strip()
However, If I don know how many ADD inputs at first, how can I modify this?
For example, there are 5 ADD need to be combined this time and next time it may be 3. It is difficult to re-write function each time like this:
def myown(df, ADD1, ADD2, ADD3, ADD4, ADD5, OtherArgument_1, OtherArgument_2):
tmp = df
tmp['NEWADD'] = (tmp[ADD1] + ' ' + tmp[ADD2] + ' ' + tmp[ADD3] + ' ' + tmp[ADD4] + ' ' + tmp[ADD5]).str.strip()

You can accomplish this by using loops and lists like this:
def myown(df, add_args, OtherArgument_1, OtherArgument_2):
tmp = df
new_add = ''
for i in add_args:
new_add = new_add + tmp[i].str.strip() + ''
tmp['NEWADD'] = new_add
Your add_args parameter must be a list, which looks like this:
add_args = [ADD1, ADD2, ADDn]

Related

Openpyxl module: return weird value(not error) + hope to calculate

I wrote some codes trying to let the user be able to check the percentage of the money they spent(compared to the money they earned). Almost every step perform normally, until the final part.
a_c[('L'+row_t)].value return:
=<Cell 'Sheet1'.B5>/<Cell 'Sheet1'.J5>
yet I hope it should be some value.
Code:
st_column = st_column_r.capitalize()
row_s = str(a_c.max_row)
row_t = str(a_c.max_row + 1)
row = int(row_t)
a_c[('J'+row_t)] = ('=SUM(I2,J'+row_s+')') #總收入
errorprevention = a_c[('J'+row_t)].value
a_c[(st_column+row_t)] = ('=SUM('+(st_column+'2')+','+(st_column+row_s)+')')
a_c['L'+row_t].number_format = FORMAT_PERCENTAGE_00
if errorprevention != 0:
a_c[('L'+row_t)] = ('='+str(a_c[(st_column+row_t)])+'/'+str(a_c[('J'+row_t)]))
print('過往支出中,'+inputtype[st_column]+'類別佔總收入的比率為:'+a_c[('L'+row_t)].value)
Try changing the formula creation to;
a_c[('L' + row_t)].value = '=' + a_c[(st_column + row_t)].coordinate + '/' + a_c[('J' + row_t)].coordinate
or use an f string
a_c[('L' + row_t)].value = f"={a_c[(st_column + row_t)].coordinate}/{a_c[('J' + row_t)].coordinate}"

Trouble getting text in to an email

I'm trying to send an email to someone with information I've scraped from the web but I can't get the contents to send. I keep receiving empty emails. Any help would be great. I've tried all sorts of different numbers of ' and +s and i can't figure it out.
def singaporeweather():
singaporehigh=singapore_soup.find(class_='tab-temp-high').text
singaporelow=singapore_soup.find(class_='tab-temp-low').text
print('There will be highs of ' + singaporehigh + ' and lows of ' +
singaporelow + '.')
def singaporesuns():
singaporesunsets=singapore_soup.find(class_='row col-sm-5')
suns_singapore=singaporesunsets.find_all('time')
sunset_singapore=suns_singapore[1].text
sunrise_singapore=suns_singapore[0].text
print('Sunrise: ' + sunrise_singapore)
print('Sunset: ' + sunset_singapore)
def ukweather():
ukhigh= uk_soup.find('span', class_='tab-temp-high').text
uklow= uk_soup.find(class_='tab-temp-low').text
print('There will be highs of ' + ukhigh + ' and lows of ' + uklow +
'.')
def uksuns():
uk_humid = uk_soup.find('div', class_='row col-sm-5')
humidity=uk_humid.find_all('time')
sunrise_uk=humidity[0].text
sunset_uk= humidity[1].text
print('Sunrise: '+str(sunrise_uk))
print('Sunset: '+str(sunset_uk))
def ukdesc():
uk_desc=uk_soup.find('div',class_='summary-text hide-xs-only')
uk_desc_2=uk_desc.find('span')
print(uk_desc_2.text)`enter code here`
def quotes():
quote_text=quote_soup.find(class_='b-qt qt_914910 oncl_q').text
author=quote_soup.find(class_='bq-aut qa_914910 oncl_a').text
print('Daily quote:\n' + '\"'+quote_text +'\"'+ ' - ' + author +'\n')
def message():
print('Subject:Testing\n\n')
print(('Morning ' +
nameslist[random.randint(1(len(nameslist)-1))]).center(30,'*'),
end='\n'*2)
quotes()
print('UK'.center(30,'_') + '\n')
ukweather()
ukdesc()
uksuns()
print('\n' + 'Singapore'.center(30,'_') + '\n')
singaporeweather()
singaporedesc()
singaporesuns()
smtpthing.sendmail('XXX#outlook.com', 'XXX#bath.ac.uk', str(message()))
In your functions, instead of printing the results to the console, you should use return statements so that you can use the function's result in your main program. Otherwise, message() is returning null, which is why your email is empty (the main program cannot see message()'s result unless it is returned).
Try something like:
def singaporeweather():
singaporehigh=singapore_soup.find(class_='tab-temp-high').text
singaporelow=singapore_soup.find(class_='tab-temp-low').text
return 'There will be highs of ' + singaporehigh + ' and lows of ' +
singaporelow + '.'
By using a return statement like this one, you will be able to use singaporeweather()'s result in your main program, e.g.:
var result = singaporeweather()
Using returns in the rest of your methods as well, you will be able to do the following in your function message():
def message():
body = "" #your message
body += 'Subject:Testing\n\n'
body += ('Morning ' + nameslist[random.randint(1(len(nameslist)-1))]).center(30,'*')
body += quotes()
body += 'UK'.center(30,'_') + '\n'
+ ukweather()
+ ukdesc()
+ uksuns()
+ '\n' + 'Singapore'.center(30,'_') + '\n'
+ singaporeweather()
+ singaporedesc()
+ singaporesuns()
#finally, don't forget to return!
return body
Now you are returning body, now you can use message()'s result in your main program to send your email correctly:
smtpthing.sendmail('XXX#outlook.com', 'XXX#bath.ac.uk', str(message()))

Why are Lists causing problems

So I am working on a certain code to modify a text file. When I use this function individually, it works perfectly
TextRotation.rotTextC("cv.txt")
But when I use it in batch as a list like this
def files_LTXT(pathF):
return glob.glob(pathF + "*" + ".txt")
for i in range (len(listFileTXT)):
TextRotation.rotTextC(listFileTXT[i])
IT gives the following error:
File "C:\Users\Administrator\PycharmProjects\openCV\TextRotation.py", line
9, in rotLineC
0
valueObj = int(lineStr[c1])
0.472917 0.713281 0.845833 0.376563
IndexError: string index out of range
Function rotLineC is as follows:
def rotLineC(lineStr, c1):
if len(lineStr) > 2:
valueObj = int(lineStr[c1])
print(valueObj)
valueXC = float(lineStr[(c1+2):(c1+10)])
valueYC = float(lineStr[(c1+11):(c1+19)])
valueW = float(lineStr[(c1+20):(c1+28)])
valueH = float(lineStr[(c1+29):(c1+37)])
# print(valueXC)
# print(valueYC)
# print(valueW)
# print(valueH)
nValueXC = round(1 - valueYC, 6)
nValueYC = round(valueXC, 6)
nValueW = round(valueH, 6)
nValueH = round(valueW, 6)
rotString = str(int(valueObj)) + " " + str(nValueXC) + " " + \
str(nValueYC) + " " + str(nValueW) + " " + str(nValueH)
print(str(nValueXC) + " " + str(nValueYC) + " " + str(nValueW) + " " + str(nValueH))
print(rotString)
return rotString
This function works fine!
for i in range (len(listFileJPG)):
ImageRotation.rotImage(listFileJPG[i])
Mind to include the / to the end of the path! (I am assuming a UNIX environment here)
If the path is 'dev/my_pat', for example, your function will fail. The path must end with a /. You can it to your function:
...
if pathF[-1] != '/':
return glob.glob(pathF + "/*.txt")
...
Also, do not iterate using indices, use the pythonic way!
for file in listFileTXT(my_path):
TextRotation.rotTextC(file)

Python random hex generator

So I'm looking to generate a random hex value each time this is called
randhex = "\\x" + str(random.choice("123456789ABCDEF")) + str(random.choice("123456789ABCDEF"))
So far all I've come up with is to make different = calls (ex. randhex1 = ^^, randhex2) etc etc but that's tedious and inefficient and I don't want to do this
ErrorClass = "\\x" + str(random.choice("123456789ABCDEF")) + "\\x" + str(random.choice("123456789ABCDEF")) + "\\x" + str(random.choice("123456789ABCDEF")) + "\\x" + str(random.choice("123456789ABCDEF"))
because that doesn't look good and can be hard to tell how many there are.
I'm trying to assign it to this
ErrorClass = randhex1 + randhex2 + randhex3 + randhex4,
Flags = randhex5,
Flags2 = randhex6 + randhex7,
PIDHigh = randhex2 + randhex5,
and ideally, instead of having to assign different numbers, I want it all to be uniform or something like ErrorClass = randhex*4 which would be clean. If I do this, however, it simply copies the code to be something like this:
Input: ErrorClass = randhex + randhex + randhex + randhex
Output: \xFF\xFF\xFF\xFF
which obviously doesn't work because they are all the same then. Any help would be great.
Make a function that returns the randomly generated string. It will give you a new value every time you call it.
import random
def randhex():
return "\\x" + str(random.choice("0123456789ABCDEF")) + str(random.choice("0123456789ABCDEF"))
ErrorClass = randhex() + randhex() + randhex() + randhex()
Flags = randhex()
Flags2 = randhex() + randhex()
PIDHigh = randhex() + randhex()
print(ErrorClass)
print(Flags)
print(Flags2)
print(PIDHigh)
Sample result:
\xBF\x2D\xA2\xC2
\x74
\x55\x34
\xB6\xF5
For additional convenience, add a size parameter to randhex so you don't have to call it more than once per assignment:
import random
def randhex(size=1):
result = []
for i in range(size):
result.append("\\x" + str(random.choice("0123456789ABCDEF")) + str(random.choice("0123456789ABCDEF")))
return "".join(result)
ErrorClass = randhex(4)
Flags = randhex()
Flags2 = randhex(2)
PIDHigh = randhex(2)
print(ErrorClass)
print(Flags)
print(Flags2)
print(PIDHigh)

how to calculate 24?

I wrote a python script trying to solve the 'calculate 24' problem, which originated from a game, drawing 4 cards from a deck of cards and try to get the value 24 using +,-, *, and /.
The code is working, only that it have many duplications, for example, I input 2, 3, 4, 5 to get the value of 24, it will find and print that 2*(3 + 4 + 5) is 24, but it will also print 2*(5 + 4 + 3), 2*(5 + 3 + 4), etc., while it will find 4*(3 + 5 - 2), it will also print 4*(5 + 3 - 2). Could anyone please give me some hints on how to remove duplicated answers?
The code is as follows:
def calc(oprands, result) :
ret=[]
if len(oprands)==1 :
if oprands[0]!=result :
return ret
else :
ret.append(str(oprands[0]))
return ret
for idx, x in enumerate(oprands) :
if x in oprands[0:idx] :
continue
remaining=oprands[0:idx]+oprands[idx+1:]
temp = calc(remaining, result-x) # try addition
for s in temp :
ret.append(str(x) + ' + ' + s)
if(result%x == 0) : # try multiplication
temp = calc(remaining, result/x)
for s in temp :
ret.append(str(x) + ' * (' + s + ')')
temp = calc(remaining, result+x) # try subtraction
for s in temp :
ret.append(s + ' - ' + str(x))
temp = calc(remaining, x-result)
for s in temp :
ret.append(str(x) + ' - (' + s + ')')
temp = calc(remaining, result*x) # try division
for s in temp :
ret.append('(' + s + ') / ' + str(x))
if result!=0 and x%result==0 and x/result!=0 :
temp = calc(remaining, x/result)
for s in temp :
ret.append(str(x) + ' / ' + '(' +s +')')
return ret
if __name__ == '__main__' :
nums = raw_input("Please input numbers seperated by space: ")
rslt = int(raw_input("Please input result: "))
oprds = map(int, nums.split(' '))
rr = calc(oprds, rslt)
for s in rr :
print s
print 'calculate {0} from {1}, there are altogether {2} solutions.'.format(rslt, oprds, len(rr))
Calculate 24 is an interesting and challenging game. As other users pointed out in the comments, it's difficult to create a solution that doesn't present any flaw.
You could study the Rosetta Code (spoiler alert) implementation and compare it to your solution.

Categories

Resources