I am pretty new to Python. I completed a challenge using a script I created. I am sure it can be improved upon and more efficient. I would appreciate suggestions to improve and simplify this script for future use. The challenge was to read from a file and run the value found in the file through base 16, base 32, & base 64 five times each. Below is the script I created. The last variable (v64) contains the flag.
Thank You!
> import base64
>
> i = 0
> with open('encodedflag.txt') as fp:
> v = fp.read()
>
> while i <= 4:
> decoded_16 = base64.b16decode(v)
> v = decoded_16
> i += 1
>
> v32 = v
>
> j = 0
>
> while j <= 4:
> decode_32 = base64.b32decode(v32)
> v32 = decode_32
> j += 1
>
> v64 = v32
>
> k = 0
>
> while k <= 4:
> decode_64 = base64.b64decode(v64)
> v64 = decode_64
> k += 1
>
> print(v64)
Related
I made a Python program using numpy, sympy, sys which worked well in IDE. Here is the code...
import numpy as np
from sympy import *
import sys
f = open("result.txt", 'w+')
for line in sys.stdin:
f.write(line)
f.close()
f = open("result.txt", 'r')
data = f.read().split("\n")
i = 0
while i < len(data):
data[i] = data[i].split(' ')
i += 1
print(data)
amount = int(data[0][0])
print(amount)
matrix = np.zeros((amount, amount))
i = 0
j = 0
while i < amount:
while j < amount:
matrix[i, j] = int(data[i + 1][j])
j += 1
j = 0
i += 1
i = 0
j = 0
counter = 0
formula = 1
while i < amount:
while j < amount:
if matrix[i, j] == 1:
x = symbols(str(i + 1))
y = symbols(str(j + 1))
if counter == 0:
formula = (~x | ~y)
counter += 1
else:
formula = formula & (~x | ~y)
j += 1
j = 0
i += 1
formula_to_string = pycode(simplify_logic(formula, form='dnf', force=True))
massive_to_parse = formula_to_string.split("or")
k = 1
i = 0
while i < len(massive_to_parse):
print("{", end='')
while k < amount + 1:
try:
massive_to_parse[i].index(str(k))
except ValueError:
print("V",k, sep='', end='')
finally:
k += 1
print("}-максимальное внутренне устойчивое множество")
k = 1
i += 1
Then I made an exe file using pyinstaller with this command...
pyinstaller main.py
but when i launch it, this errors appear.
How can I fix this problem? Because I need exe file for university to launch it from other program on C
Here's the code I am using.
if i < 50:
test_a = os.getenv("TEST_VAR_A")
elif i >= 50 and i < 100:
test_a = os.getenv("TEST_VAR_B")
elif i >= 100 and i < 150:
test_a = os.getenv("TEST_VAR_C")
elif i >= 150 and i < 200:
test_a = os.getenv("TEST_VAR_D")
elif i >= 200 and i < 250:
test_a = os.getenv("TEST_VAR_E")
elif i >= 250 and i < 300:
test_a = os.getenv("TEST_VAR_F")
elif i >= 300 and i < 350:
test_a = os.getenv("TEST_VAR_G")
elif i >= 350 and i < 400:
test_a = os.getenv("TEST_VAR_H")
else:
test_a = "test"
Is it possible to shorten it? Say in one line?
Thanks!
Python ranges can clean this up pretty well. There are various ways you can pull this off in a few line,s but they're probably just worse. For example:
def get_test_var(i): # Name this something better.
try:
letter = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H'][i // 50]
return os.getenv("TEST_VAR_" + letter)
except IndexError:
return "test"
Although admittedly, if somebody used environment variables named "TEST_VAR_A", I might just get into a homicidal rage.
Depending on what your real use case is, I think the "manual" solution is a bit more verbose, but much easier to understand and to change. For example, if you ever want to have non-equal intervals (say, 125-200), the previous approach would fail entirely.
People shouldn't need test cases or a debugger to trace out what your code does. It should be obvious at a glance.
def get_test_var(i): # Name this something better.
if i in range(0, 50):
return os.getenv("TEST_VAR_A")
elif i in range(50, 100):
return os.getenv("TEST_VAR_B")
elif i in range(100, 150):
return os.getenv("TEST_VAR_C")
elif i in range(150, 200):
return os.getenv("TEST_VAR_D")
elif i in range(200, 250):
return os.getenv("TEST_VAR_E")
elif i in range(250, 300):
return os.getenv("TEST_VAR_F")
elif i in range(300, 350):
return os.getenv("TEST_VAR_G")
elif i in range(350, 400):
return os.getenv("TEST_VAR_H")
else:
return "test"
I am trying to get my head around Expected Colon Error in the following code. Any help appreciated.
The code is -
if df.loc['pivot'] > df.loc['Open'] :
df.loc['Signal'] = 1
elif df.loc[['Open'] > df.loc['IB'] and df.loc['Open'] > df.loc['pivot'] and df.loc['Open'] < df.loc['OB']:
df.loc['Signal'] = 0
elif (((df.loc['Open']) <= (((df.loc['2_pips']) - 5)/ 1000)) * (df.loc['pivot'])) and ((df.loc['Open']) >= (((df.loc['1_pips']) + 10)/ 1000 * (df.loc['pivot']))) and ((df.loc['Open']) >= (df.loc['pivot'])) :
df.loc['Signal'] = 1
elif (df.loc['Open'] <= ((df.loc['1_pips'] * df.loc['pivot']) + df.loc['pivot'] )) and (df.loc['Open'] > (((df.loc['1_pips'] - 10) * df.loc['pivot']) + df.loc['pivot'])) :
df.loc['Signal'] = 1
elif ((df.loc['Open'] < OB) and (df.loc['Open'] < df.loc['pivot'])):
df.loc['Signal'] = -1
elif ((df.loc['Open'] <= OB) and (df.loc['Open'] >= IB) and (df.loc['Open'] < df.loc['pivot'])):
df.loc['bs'] = 0
elif (df.loc['Open'] < ((df.Loc['2_pips'] - 5) * df.loc['pivot']) + df.loc['pivot']) and (df.loc['Open'] > ((df.loc['1_pips'] + 10) * pivot) + df.loc['pivot']) and (df.loc['Open'] < df.loc['pivot']):
df.loc['Signal'] = -1
elif (df.loc['Open'] <= (df.loc['1_pips'] * df.loc['pivot']) + df.loc['pivot']) and (df.loc['Open'] > ((df.loc['1_pips'] - 10) * df.loc['pivot']) + df.loc['pivot']):
df.loc['Signal'] = -1
else:
df.loc['Signal'] = 0
Thanks!
On line 4, you have df.loc[['Open'] which I guess is one square bracket too much.
You can also simplify that line as:
elif df.loc['Open'] > df.loc['IB'] and df.loc['pivot'] < df.loc['Open'] < df.loc['OB']:
And generally, you have way too many parentheses. I'm guessing that it's actually because you were trying to find the issue.
In general, when you get a compiler syntax error like an (un)expected token, you have a structural issue just above it. It is parsing the line it's complaining about as the continuation of the previous statement. Unmatched (), [] or {}. To find it, one could have reduced the code with the error and noticed that it was still failing with the same error, meaning that the actual error was in fact from the previous line(s).
I am trying to re-create the column 'sig', below, but in a faster, more efficient way.
My attempt is 'sig2' but that, too, runs into its own errors.
import numpy as np
import pandas as pd
a = np.random.standard_normal(500)
A = pd.DataFrame(np.cumsum(a))
A['Max'] = pd.rolling_max(A[0],10)
A['Min'] = pd.rolling_min(A[0],10)
A['Mean'] = pd.rolling_mean(A[0],3)
A['sig'] = 0
for t in range(1,A.shape[0]):
if (A['Max'][t] > A['Max'][t-1]) & (A['sig'][t-1]==0):
A['sig'][t] = 1
elif (A['Min'][t] < A['Min'][t-1]) & (A['sig'][t-1]==0):
A['sig'][t] = -1
elif ((A[0][t] > A['Mean'][t]) & (A['sig'][t-1]==-1)) | ((A[0][t] < A['Mean'][t]) & (A['sig'][t-1]==1)):
A['sig'][t] = 0
else:
A['sig'][t] = A['sig'][t-1]
state = 0
B = A.shift()
def get_val(A,B,prev_state):
global state
if (A['Max'] > B['Max']) & (prev_state==0):
state = 1
return state
elif (A['Min'] < B['Min']) & (prev_state==0):
state = -1
return state
elif ((A[0] > A['Mean']) & (prev_state==-1)) | ((A[0] < A['Mean']) & (prev_state==1)):
state = 0
return state
else:
return state
A['sig2'] = A.apply(lambda x: get_val(x,B,state))
Thank you
i have a code which looks like this
def monokode(b):
while f == 0:
if g[h]== b[i]:
i = i + 1
j = h - e
if j >= 100:
j = (e-h + len(g))*-1
elif j <= -100:
j = (e-h - len(g))*-1
if j < 10 and j >=0:
print 0,0,j,
elif j < 0:
j = j*-1
if j < 10:
print 1,0,j,
elif j >= 10 and j < 100:
print 1,j,
else:
print 1,j,
elif j >= 10 and j < 100:
print 0,j,
else:
print 0,j,
h = 0
if i >= len(b):
f = 1
else:
h=h+1
now, i want to make all the statements that print right now, return their value instead. but after some tries, i've realised that i don't know enough about the return statement to use it properly. how can i make the program return multiple values in a long line and then print them afterwards?
UPDATED ANSWER:
Okay as I understand the question you're wanting to make your function return multiple variables and then print them?
I agree with most of the other replies. Store the objects you want to print in a list then call
print ', '.join(list)
right before you return whatever values from the program:
like this:
def monokode(b):
printspool=[]
while f == 0:
if g[h]== b[i]:
i = i + 1
j = h - e
if j >= 100:
j = (e-h + len(g))*-1
elif j <= -100:
j = (e-h - len(g))*-1
if j < 10 and j >=0:
printspool.append([0,0,j])
elif j < 0:
j = j*-1
if j < 10:
printspool.append([1,0,j])
elif j >= 10 and j < 100:
printspool.append([1,j])
else:
printspool.append([1,j])
elif j >= 10 and j < 100:
printspool.append([0,j])
else:
printspool.append([0,j])
h = 0
if i >= len(b):
f = 1
else:
h=h+1
#Now here I'll print out everything contained in the printspooler list
for node in printspooler:
print ','.join(node)
#This is where you would
return Whatevervariable, Whatevervariable2, Whatevervariable3 etc...
Collect your values into a list instead, then return that list:
def yourfunction(your_arguments):
results = []
while f == 0:
if g[h]== b[i]:
i = i + 1
j = h - e
if j >= 100:
j = (e-h + len(g))*-1
elif j <= -100:
j = (e-h - len(g))*-1
if j < 10 and j >=0:
results.extend([0,0,j])
elif j < 0:
j = j*-1
if j < 10:
results.extend([1,0,j])
elif j >= 10 and j < 100:
results.extend([1,j])
else:
results.extend([1,j])
elif j >= 10 and j < 100:
results.extend([0,j])
else:
results.extend([0,j])
h = 0
if i >= len(b):
f = 1
else:
h=h+1
return results
You can use return and say many variable names...
return a, b, c
and what is returned is a tuple in the same order..
eg. return 1, 2, 3
will be (1, 2, 3)
and you can directly print call_fn() # if this returns those values
From what I understand, you can to store the values into a list:
def myfunc(…)
…
myList=[]
while f == 0:
if g[h]== b[i]:
i = i + 1
j = h - e
if j >= 100:
j = (e-h + len(g))*-1
elif j <= -100:
j = (e-h - len(g))*-1
if j < 10 and j >=0:
myList.extend([0,0,j])
elif j < 0:
j = j*-1
if j < 10:
myList.extend([1,0,j])
elif j >= 10 and j < 100: #this test
myList.extend([1,j])
else:
myList.extend([1,j])
elif j >= 10 and j < 100: #and this one
myList.extend([0,j])
else:
myList.extend([0,j])
h = 0
if i >= len(b):
f = 1
else:
h=h+1
return myList
and then print myFunc(…), or maybe something like
results = myFunc(…)
for r in results:
print r,
Edit: I've marked 2 tests that I think are unnecessary, since in the èlse part, you print the same thing