Simplify for loop in python - python

I am using python and asking for help on how to simplify the code below. Thanks.
for i in range(1,9):
if i == 1:
wt_1 = gwt_2018[gwt_2018.WkNum == i]
elif i == 2:
wt_2 = gwt_2018[gwt_2018.WkNum == i]
elif i == 3:
wt_3 = gwt_2018[gwt_2018.WkNum == i]
elif i == 4:
wt_4 = gwt_2018[gwt_2018.WkNum == i]
elif i == 5:
wt_5 = gwt_2018[gwt_2018.WkNum == i]
elif i == 6:
wt_6 = gwt_2018[gwt_2018.WkNum == i]
elif i == 7:
wt_7 = gwt_2018[gwt_2018.WkNum == i]
else i == 8:
wt_8 = gwt_2018[gwt_2018.WkNum == i]

Do you need something like this?
l = [wt_1, wt_2, wt_3, wt_4, wt_5, wt_6, wt_7, wt_8]
for index, i in enumerate(l):
i = gwt_2018[gwt_2018.WkNum == index+1]

Is that mandatory to have 'wt_i' as variable name for all i's ?
I would use a dictionary instead:
wt = {}
for i in range(1,9):
wt[i] = gwt_2018[gwt_2018.WkNum == i]

I found the solution [a link] (Create multiple dataframe using for loop in python 2.7)
gbl = globals()
for i in range(1,54):
gbl['df_'+str(i)] = gwt_2018[gwt_2018.WkNum == i]

Related

how i break the while loop in func "loop of user"?

I need to break the while loop, I try to do it with status statment and it didn't work to me.
Any suggestions what are the easiest ways to break a while loop?
This is my code:
def loop_of_user(my_details):
"""_summary_
the function do a variety of actions on the the variable my_detailes
:my_details (dict): dictionary of detailes on mariha
"""
num = int(input())
if num == 1:
print(my_details["first_name"])
elif num == 2:
print(my_details["birth_date"][3:5])
elif num == 3:
print(len(my_details["hobbies"]))
elif num == 4:
print(my_details["hobbies"][-1])
elif num == 5:
my_details["hobbies"].append("cooking")
print(my_details["hobbies"])
elif num == 6:
print(tuple_birth_date(my_details["birth_date"]))
elif num == 7:
my_details ["age"] = calculate_age(my_details["birth_date"])
print(my_details["age"])
else:
return "break"
def main():
mariah_details = {"first_name" : "mariah", "last_name" : "carey", "birth_date" : "27.03.1970", "hobbies" : ["sing", "compose", "act"]}
status = ""
while status != "break":
loop_of_user(mariah_details)
if __name__ == "__main__":
main()
The I try to use in satatus like you see and write "break" in the else satement and it not working, it still in the loop and won't break.
I will love some help here.
You can put the while loop inside the function loop_of_user instead and call the function loop_of_user() explicitly.
def loop_of_user(my_details):
"""_summary_
the function do a variety of actions on the the variable my_detailes
:my_details (dict): dictionary of detailes on mariha
"""
while True:
num = int(input())
if num == 1:
print(my_details["first_name"])
elif num == 2:
print(my_details["birth_date"][3:5])
elif num == 3:
print(len(my_details["hobbies"]))
elif num == 4:
print(my_details["hobbies"][-1])
elif num == 5:
my_details["hobbies"].append("cooking")
print(my_details["hobbies"])
elif num == 6:
print(tuple_birth_date(my_details["birth_date"]))
elif num == 7:
my_details["age"] = calculate_age(my_details["birth_date"])
print(my_details["age"])
else:
break
def main():
mariah_details = {"first_name": "mariah", "last_name": "carey", "birth_date": "27.03.1970",
"hobbies": ["sing", "compose", "act"]}
loop_of_user(mariah_details)
if __name__ == "__main__":
main()

unpacking tuples based on if statements

I'm creating a nested dictionary with values from a tuple that is based on if statement. The variables in the code(estabilidad_atm, Q_puntos_muestreo and puntos de muestreo) are defined in the global scope. When I run the function I got and error saying: name a is not defined. I'm not sure why it isn't working... I've thought of applying namedtuple but I'm not sure which is the best way to proceed. Thanks!
variables_coeficientes_por_punto = {}
for punto in puntos_de_muestreo:
x = punto[0]
if estabilidad_atm == 'A' and x <= 1:
a,c,d,f = (213,440.8,1.941,9.27)
elif estabilidad_atm == 'A' and x > 1:
a,c,d,f = (213,459.7,2.094,-9.6)
elif estabilidad_atm == 'B' and x <= 1:
a,c,d,f = (156,106.6,1.149,3.3)
elif estabilidad_atm == 'B' and x > 1:
a,c,d,f = (156,108.2,1.098,2)
elif estabilidad_atm == 'C' and x <= 1:
a,c,d,f = (104,61,0.911,0)
elif estabilidad_atm == 'C' and x > 1:
a,c,d,f = (104,61,0.911,0)
elif estabilidad_atm == 'D' and x <= 1:
a,c,d,f = (68,33.2,0.725,-1.7)
elif estabilidad_atm == 'D' and x > 1:
a,c,d,f = (68,44.5,0.516,-13)
elif estabilidad_atm == 'E' and x <= 1:
a,c,d,f = (50.5,22.8,0.678,-1.3)
elif estabilidad_atm == 'E' and x > 1:
a,c,d,f = (50.5,55.4,0.305,-34)
elif estabilidad_atm == 'F' and x <= 1:
a,c,d,f = (34,14.35,0.740,-0.35)
elif estabilidad_atm == 'F' and x > 1:
a,c,d,f = (34,62.6,0.180,-48.6)
for i in range(Q_puntos_muestreo):
variables_coeficientes_por_punto['punto '+ str(i+1)] = {}
variables_coeficientes_por_punto['punto ' + str(i+1)]['a'] = a
variables_coeficientes_por_punto['punto ' + str(i+1)]['c'] = c
variables_coeficientes_por_punto['punto ' + str(i+1)]['d'] = d
variables_coeficientes_por_punto['punto ' + str(i+1)]['f'] = f
Many large if statements like this can be replaced with a dict. For example,
tuples = {
'A': lambda x: (213,440.8,1.941,9.27) if x < 1 else (213,459.7,2.094,-9.6),
'B': lambda x: (156,106.6,1.149,3.3) if x <= 1 else (156,108.2,1.098,2),
...
}
variables_coeficientes_por_punto = {}
for punto in puntos_de_muestreo:
x = punto[0]
try:
a, c, d, f = tuples[estabilidad_atm](x)
except KeyError:
raise
for i in range(1, Q_puntos_muestreo + 1):
variables_coeficientes_por_punto['punto '+ str(i)] = dict(a=a, c=c, d=d, f=f)
This will raise a KeyError if estabilidad_atm is not a valid key, at which point you can optionally catch and do something sensible, rather than simply let your program exit.

Are there better ways to write if statements in python?

So ive been writing Python for a bit now. I've decided to make an app to help my sister with multiplication tables. Im writing the code that will randomly pick from my 10 lists of the diffrent questions (I know there are better ways to write it but it gave me abilities i wanted to use with SQL). lists are by Table (Tone,Ttwo,Tthree, etc.) inside Tone would be ['1*1','1*2',...] then as seen in the if statement it calls by calling the list and problem with randomly generated numbers.
def pick_question():
Table = random.randint(0,9)
Col = random.randint(0,9)
if Table == 0:
if Col == 0:
return Tone[0]
elif Col == 1:
return Tone[1]
elif Col == 2:
return Tone[2]
elif Col == 3:
return Tone[3]
elif Col == 4:
return Tone[4]
elif Col == 5:
return Tone[5]
elif Col == 6:
return Tone[6]
elif Col == 7:
return Tone[7]
elif Col == 8:
return Tone[8]
elif Col == 9:
return Tone[9]
elif Table == 1:
if Col == 0:
return Ttwo[0]
elif Col == 1:
return Ttwo[1]
elif Col == 2:
return Ttwo[2]
elif Col == 3:
return Ttwo[3]
elif Col == 4:
return Ttwo[4]
elif Col == 5:
return Ttwo[5]
elif Col == 6:
return Ttwo[6]
elif Col == 7:
return Ttwo[7]
elif Col == 8:
return Ttwo[8]
elif Col == 9:
return Ttwo[9]
obviously it would keep going but it was already quite long. was wondering if there was anyway to make this not hae to be so repetitive and look better...
def pick_question():
Table = random.randint(0,9)
Col = random.randint(0,9)
return [Tone,Ttwo][Table][Col]
I guess what you are trying to write is
import random
Tone = [f"1*{i}" for i in range(1,10)]
Ttwo = [f"2*{i}" for i in range(1,10)]
Tthree = [f"3*{i}" for i in range(1,10)]
Tfour = [f"4*{i}" for i in range(1,10)]
Tfive = [f"5*{i}" for i in range(1,10)]
Tsix = [f"6*{i}" for i in range(1,10)]
Tseven = [f"7*{i}" for i in range(1,10)]
Teight = [f"8*{i}" for i in range(1,10)]
Tnine = [f"9*{i}" for i in range(1,10)]
Questions = [
Tone,
Ttwo,
Tthree,
Tfour,
Tfive,
Tsix,
Tseven,
Teight,
Tnine,
]
def pick_question():
Table = random.randint(0,8)
Col = random.randint(0,8)
return Questions[Table][Col]
print(pick_question())
but I guess what you are trying to do is this:
import random
A=random.randint(1,9)
B=random.randint(1,9)
print(f"{A}*{B}=?")
C=input()
try:
assert A*B==int(C)
print("You are RIGHT!")
except:
print(f"Your are WRONG, right answer is: {A*B}")
Good luck with python! it's an amazing language! :)
Just use a one-dimensional list:
def pick_question():
Table = random.randint(0,9)
Col = random.randint(0,9)
if Table == 0:
return Tone[Col]
elif Table == 1:
return Ttwo[Col]
This will do the trick.
Or even better, a two-dimensional list:
def pick_question():
Table = random.randint(0,9)
Col = random.randint(0,9)
List = [Tone, Ttwo]
return List[Table][Col]
I quite like this solution with dictionaries and the get method:
route = input()
branch = {'y': code1, 'n': code2}.get(route)
This shortens your code and will be easier to read.
Rather than write the inner if structures, why not just
return Tone[Col]
?
In fact, you can create a list with the Tone, Ttwo, etc. inside it and then write
return outer_list[Table][Col]
def pick_question(list_with_tone_ttwo):
table = random.randint(0,9)
col = random.randint(0,9)
return list_with_tone_ttwo[table][col]
EDIT: added full function

How do I get the consecutive elements between two identical elements in a list?

For example I have a list l = ['.','b','w','w','w','b','.','.'], how would I traverse this list and return the indices of the three w's that are between the b's.
I need to be able to handle cases such as l = ['.','b','w','w','w','w','.','.'], where there is no second 'b', in this case nothing would be returned. Other cases that could be encountered are l = ['.','b','w','w','.','.','b','.'], in this case nothing would be returned either. I need to be able to get the consecutive w's between the b's. What I have tried so far is this:
l = ['.','b','w','w','.','.','.','.']
q = []
loop = False
for i in range(len(l)):
if l[i] == 'b' and l[i+1] == 'w':
loop = True
elif l[i] == 'w' and l[i+1] == 'w' and l[i+2] == '.':
pass
elif l[i] == 'w' and l[i-1] == 'b' and l[i+1] == 'w' and loop == True:
q.append(i)
elif l[i-1] == 'w' and l[i] == 'w' and l[i+1] == 'w' and loop == True: q.append(i)
elif l[i] == 'w' and l[i+1] == 'b' and loop == True:
q.append(i)
loop = False
break
print(q)
But this does not handle all cases and sometimes returns errors. How could I go about doing this without numpy?
Try this:
ind = [i for i, e in enumerate(l) if e == 'b']
q = []
if len(ind) == 2:
w = l[ind[0]+1: ind[1]]
if set(w) == {'w'}:
for i in range(ind[0]+1, ind[1]):
q.append(i)
try this
import re
l = ['.','b','w','w','b','.','.','.']
s = ''.join(l)
# print(re.findall('[b]([w]+)[b]',s))
# print(re.findall('[w]([b]+)[w]',s))
if(re.findall('[b]([w]+)[b]',s)):
witer =re.finditer('w',s)
wpos = []
for i in witer:
wpos.append(i.start())
print('reverse', wpos)
if(re.findall('[w]([b]+)[w]',s)):
biter =re.finditer('b',s)
bpos = []
for i in biter:
bpos.append(i.start())
print('reverse', bpos)

Calculate by using Reverse Polish Notation (Python)

I learn about Reverse Polish Notation (:RPN).
I want to calculate Numerical formula by using RPN.
I managed to write following Program.
At a glance, this code work properly.
But, when I submitted this code to Programming Contest Site, (
http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=0109
) I got Wrong Answer.
What is wrong with my code?
# coding: utf-8
# Convert String to List
def String2List(s):
L = []
flag = True
l = len(s)
for i in range(l):
if s[i].isdigit() and flag:
t = ""
j = 0
while s[i+j].isdigit():
t += s[i+j]
if i+j == l-1:
break
j += 1
L.append(t)
flag = False
elif not s[i].isdigit():
L.append(s[i])
flag = True
return L
# generate Reverse Polish Notation
def RPN_list(L):
S, L2 = [], []
table = {"*": 1, "/": 1, "+": 0, "-": 0, "(": -1, ")": -1}
for i in L:
if i.isdigit():
L2.append(i)
elif i == "(":
S.append(i)
elif i == ")":
while S[-1] != "(":
L2.append(S.pop())
S.pop()
else:
if len(S) != 0 and (table[S[-1]] >= table[i]):
L2.append(S.pop())
S.append(i)
while len(S) != 0:
L2.append(S.pop())
return L2
# calculate Reverse Polish Notation
def RPN_cul(L):
St = []
for i in L:
if i == '+':
St.append(int(St.pop()) + int(St.pop()))
elif i == '-':
St.append(-int(St.pop()) + int(St.pop()))
elif i == '*':
St.append(int(St.pop()) * int(St.pop()))
elif i == '/':
a = int(St.pop())
b = float(St.pop())
St.append(b/a)
else:
St.append(i)
return St[0]
N = int(raw_input())
for i in range(N):
s = raw_input()
L = String2List(s[:-1])
L = RPN_list(L)
print int(RPN_cul(L))
Result
$ python reverse_polish_notation.py
2
4-2*3=
-2
4*(8+4+3)=
60
when I fixed as follows, It was accepted. Thanks to help me.
Before:
def RPN_list(L):
...
if len(S) != 0 and (table[S[-1]] >= table[i]):
L2.append(S.pop())
S.append(i)
...
After:
def RPN_list(L):
...
while len(S) != 0 and (table[S[-1]] >= table[i]):
L2.append(S.pop())
S.append(i)
...
polish_str="123*+4-"
#scan from left to right once you got the operator make the operation save the result again perform the operation
#result=3
polish_list=[]
for i in polish_str:
polish_list.append(i)
print(polish_list)
####
temp=[]
operator=['*',"+","/","-"]
def operation(o,a,b):
if o=="+":
result=a+b
if o=="-":
result=a-b
if o=="*":
result=a*b
if o=="/":
result=a/b
return result
for i,v in enumerate(polish_list):
if v in operator:
print(temp)
leng=len(temp)
arg1=temp.pop()
print("arg1==>",arg1)
arg2=temp.pop()
print("arg2==>",arg2)
result=operation(v,arg1,arg2)
print("result==>",result)
temp.append(result)
print("temp in iteration==>",temp)
else:
temp.append(i)
print("***final temp***",temp)

Categories