Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I followed along a tutorial at https://towardsdatascience.com/audio-to-guitar-tab-with-deep-learning-d76e12717f81 but i am getting an error.
# Initialize variables
cnt_row = -1
cnt_col = 0
cnt_zero = 0
# Grab all relevant MIDI data (available in MIDI_dat)
for i in range(0, len(jam['annotations'])):
if jam['annotations'][int(i)]['namespace'] == 'note_midi':
for j in range(0, len(sorted(jam['annotations'][int(i)]['data']))):
cnt_row = cnt_row + 1
for k in range(0, len(sorted(jam['annotations'][int(i)]['data'])[int(j)]) - 1):
if cnt_zero == 0:
MIDI_arr = np.zeros((len(sorted(jam['annotations'][int(i)]['data'])), len(sorted(jam['annotations'][int(i)]['data'])[int(j)]) - 1), dtype = np.float32)
cnt_zero = cnt_zero + 1
if cnt_zero > 0:
MIDI_arr = np.vstack((MIDI_arr, np.zeros((len(sorted(jam['annotations'][int(i)]['data'])), len(sorted(jam['annotations'][int(i)]['data'])[int(j)]) - 1), dtype = np.float32)))
cnt_zero = cnt_zero + 1 # Keep
if cnt_col > 2:
cnt_col = 0
MIDI_arr[cnt_row, cnt_col] = sorted(jam['annotations'][int(i)]['data'])[int(j)][int(k)]
cnt_col = cnt_col + 1
MIDI_dat = np.zeros((cnt_row + 1, cnt_col), dtype = np.float32)
cnt_col2 = 0
for n in range(0, cnt_row + 1):
for m in range(0, cnt_col):
if cnt_col2 > 2:
cnt_col2 = 0
MIDI_dat[n, cnt_col2] = MIDI_arr[n, cnt_col2]
cnt_col2 = cnt_col2 + 1
# Return the unique MIDI notes played (available in MIDI_val)
MIDI_dat_dur = np.copy(MIDI_dat)
for r in range(0, len(MIDI_dat[:, 0])):
MIDI_dat_dur[r, 0] = MIDI_dat[r, 0] + MIDI_dat[r, 1]
tab_1, = np.where(np.logical_and(MIDI_dat[:, 0] >= start, MIDI_dat[:, 0] <= stop))
tab_2, = np.where(np.logical_and(MIDI_dat_dur[:, 0] >= start, MIDI_dat_dur[:, 0] <= stop))
tab_3, = np.where(np.logical_and(np.logical_and(MIDI_dat[:, 0] < start, MIDI_dat_dur[:, 0] > stop), MIDI_dat[:, 1] > int(stop-start)))
if tab_1.size != 0 and tab_2.size == 0 and tab_3.size == 0:
tab_ind = tab_1
if tab_1.size == 0 and tab_2.size != 0 and tab_3.size == 0:
tab_ind = tab_2
if tab_1.size == 0 and tab_2.size == 0 and tab_3.size != 0:
tab_ind = tab_3
if tab_1.size != 0 and tab_2.size != 0 and tab_3.size == 0:
tab_ind = np.concatenate([tab_1, tab_2])
if tab_1.size != 0 and tab_2.size == 0 and tab_3.size != 0:
tab_ind = np.concatenate([tab_1, tab_3])
if tab_1.size == 0 and tab_2.size != 0 and tab_3.size != 0:
tab_ind = np.concatenate([tab_2, tab_3])
if tab_1.size != 0 and tab_2.size != 0 and tab_3.size != 0:
tab_ind = np.concatenate([tab_1, tab_2, tab_3])
if tab_1.size == 0 and tab_2.size == 0 and tab_3.size == 0:
tab_ind = []
if len(tab_ind) != 0:
MIDI_val = np.zeros((len(tab_ind), 1), dtype = np.float32)
for z in range(0, len(tab_ind)):
MIDI_val[z, 0] = int(round(MIDI_dat[tab_ind[z], 2]))
elif len(tab_ind) == 0:
MIDI_val = []
MIDI_val = np.unique(MIDI_val)
if MIDI_val.size >= 6:
MIDI_val = np.delete(MIDI_val, np.s_[6::])
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-56-070b180aefc0> in <module>
5
6 # Grab all relevant MIDI data (available in MIDI_dat)
----> 7 for i in range(0, len(jam['annotations'])):
8 if jam['annotations'][int(i)]['namespace'] == 'note_midi':
9 for j in range(0, len(sorted(jam['annotations'][int(i)]['data']))):
NameError: name 'jam' is not defined
Now i'm kinda new to coding, so i'm not quite sure what jam is referring to, but since i was following a tutorial, i really don't understand why it isn't defined? Thank you in advance for helping a beginner out.
you need to declare a variable jam and assign it a value from where ever you are getting it, python will not allow declaration in this manner.
cnt_row = -1
cnt_col = 0
cnt_zero = 0
jam = MIDI_dat <------- (or the variable from which you are accessing the data from)
# Grab all relevant MIDI data (available in MIDI_dat)
for i in range(0, len(jam['annotations'])):
if jam['annotations'][int(i)]['namespace'] == 'note_midi':
for j in range(0, len(sorted(jam['annotations'][int(i)]['data']))):
cnt_row = cnt_row + 1
for k in range(0, len(sorted(jam['annotations'][int(i)]['data'])[int(j)]) - 1):
if cnt_zero == 0:
MIDI_arr = np.zeros((len(sorted(jam['annotations'][int(i)]['data'])), len(sorted(jam['annotations'][int(i)]['data'])[int(j)]) - 1), dtype = np.float32)
cnt_zero = cnt_zero + 1
if cnt_zero > 0:
MIDI_arr = np.vstack((MIDI_arr, np.zeros((len(sorted(jam['annotations'][int(i)]['data'])), len(sorted(jam['annotations'][int(i)]['data'])[int(j)]) - 1), dtype = np.float32)))
cnt_zero = cnt_zero + 1 # Keep
if cnt_col > 2:
cnt_col = 0
MIDI_arr[cnt_row, cnt_col] = sorted(jam['annotations'][int(i)]['data'])[int(j)][int(k)]
cnt_col = cnt_col + 1
Related
I am looking for a converting from TV to python. Just a little code. This is the code in tradingview :
last_signal = 0
long_final = longCond and (nz(last_signal[1]) == 0 or nz(last_signal[1]) == -1)
short_final = shortCond and (nz(last_signal[1]) == 0 or nz(last_signal[1]) == 1)
last_signal := long_final ? 1 : short_final ? -1 : last_signal[1]
for variable :
-> longCond and shortCond, i have the right value (I compared between plot)
But for others, i have some differences (i think, because of last_signal)
this is my code in python :
for x in range(0,len(mavi),1):
last_signal[i] = 0
if x == 0:
longCond_tmp = 0
shortCond_tmp = 0
last_signal_tmp = 0
short_final_tmp = 0
long_final_tmp = 0
else:
if ((longCond_tmp and ((last_signal[i-1])) == 0) or ((last_signal[i-1]) == -1)):
long_final_tmp = 1
else:
long_final_tmp = 0
if ((shortCond_tmp and ((last_signal[i-1])) == 0) or ((last_signal[i-1]) == 1)):
short_final_tmp = 1
else:
short_final_tmp = 0
if long_final_tmp != 0:
last_signal_tmp = 1
else:
if short_final_tmp != 0:
last_signal_tmp = -1
else:
last_signal_tmp = last_signal[i-1]
last_signal[i] += last_signal_tmp
Are there errors in my script in python ?
Ok i found.
Just the number of "(" in
if ((longCond_tmp and ((last_signal[i-1])) == 0) or ((last_signal[i-1]) == -1)):
long_final_tmp = 1
else:
long_final_tmp = 0
if ((shortCond_tmp and ((last_signal[i-1])) == 0) or ((last_signal[i-1]) == 1)):
short_final_tmp = 1
else:
short_final_tmp = 0
This question already has answers here:
Why Python recursive function returns None [duplicate]
(1 answer)
Recursive function does not return specified value
(2 answers)
Closed 1 year ago.
I have written a maze solver program. I want the PathFinder function to return True if a path is found and then print the path or else simply return False. But my program always keeps returning False even if a path is found. It would be great if you guys can help me figure this out.
def findPaths(m,path,i,j):
r,c = len(m), len(m[0])
if i == r-1 and j == c-1:
print(path)
return True
#explore
path.append(m[i][j])
# move down
if i != r-1 and m[i+1][j] == '↓ ':
findPaths(m,path,i+2,j)
#move up
if i < 0 and m[i-1][j] == '↑ ':
findPaths(m,path,i-2,j)
#move right
if j != c-1 and m[i][j+1] == '→':
findPaths(m,path,i,j+2)
#move left
if j > 0 and m[i][j-1] == '←':
findPaths(m,path,i,j-2)
path.pop()
def maze(r,c):
m = []
for i in range(r):
row = []
for j in range(1, c + (c)):
rand_num = str(randint(1, 99))
if j % 2 != 0:
if len(rand_num) == 1:
row.append(' ' + rand_num)
else:
row.append(rand_num)
else:
row.append('?')
m.append(row)
up_left_count = r * c // 3
down_right_count = r * c * 2 // 3
for v in range(r + (r - 1)):
vertical_lst = []
for each in range(1, c + c):
if each % 2 == 0:
vertical_lst.append(' ')
else:
vertical_lst.append('? ')
if v % 2 != 0:
m.insert(v, vertical_lst)
idx_i = []
idx_j = []
idx_v_i = []
idx_v_j = []
for i in range(len(m)):
for j in range(len(m[0])):
if i % 2 == 0 and j % 2 != 0:
idx_i.append(i)
idx_j.append(j)
for v_i in range(len(m)):
for v_j in range(len(m[0])):
if v_i % 2 != 0 and v_j % 2 == 0:
idx_v_i.append(v_i)
idx_v_j.append(v_j)
idx_i = list(set(idx_i))
idx_j = list(set(idx_j))
idx_v_i = list(set(idx_v_i))
idx_v_j = list(set(idx_v_j))
for count in range(up_left_count):
i_int = randint(0, len(idx_i) - 1)
j_int = randint(0, len(idx_j) - 1)
if m[i_int][j_int] != '←':
m[idx_i[i_int]][idx_j[j_int]] = '←'
for count_v in range(up_left_count):
i_v_int = randint(0, len(idx_v_i) - 1)
j_v_int = randint(0, len(idx_v_j) - 1)
if m[i_v_int][j_v_int] != '↑':
m[idx_v_i[i_v_int]][idx_v_j[j_v_int]] = '↑ '
for i in range(len(m)):
for j in range(len(m[0])):
if i % 2 == 0 and j % 2 != 0:
if m[i][j] == '?':
m[i][j] = '→'
for i in range(len(m)):
for j in range(len(m[0])):
if i % 2 != 0 and j % 2 == 0:
if m[i][j] != '↑ ':
m[i][j] = '↓ '
m[0][0] = "S"
m[-1][-1] = "D"
for i in range(len(m)):
for j in range(len(m[0])):
print(m[i][j], end=" ")
print()
path = []
return findPaths(m, path, 0,0)
if maze(5,6):
print('True')
else:
print('False')
https://www.hackerrank.com/challenges/designer-door-mat/problem
Below is my submission:
n = input().split(' ')
rows, columns = int(n[0]), int(n[1])
if(rows % 2 == 1 and columns == 3*rows):
printale = ''
j = 1
k = rows - 7
for i in range(int(rows/2), -1, -1):
printale = '---'*i + '.|.'*j + '---'*i
if(i == 0):
print('-'*int(j+k/2) + 'Welcome' + '-'*int(j+k/2))
j -= 2
else:
print(printale)
j += 2
for l in range(1, int(rows/2)+1):
printale = '---'*l + '.|.'*j + '---'*l
print(printale)
j -= 2
Is there anything wrong with the code?
Yes, there is. The "WELCOME" in the problem statement is all-caps.
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
If I have 2 numbers in binary form as a string, and I want to add them I will do it digit by digit, from the right most end. So 001 + 010 = 011
But suppose I have to do 001+001, how should I create a code to figure out how to take carry over responses?
bin and int are very useful here:
a = '001'
b = '011'
c = bin(int(a,2) + int(b,2))
# 0b100
int allows you to specify what base the first argument is in when converting from a string (in this case two), and bin converts a number back to a binary string.
This accepts an arbitrary number or arguments:
>>> def bin_add(*bin_nums: str) -> str:
... return bin(sum(int(x, 2) for x in bin_nums))[2:]
...
>>> x = bin_add('1', '10', '100')
>>> x
'111'
>>> int(x, base = 2)
7
Here's an easy to understand version
def binAdd(s1, s2):
if not s1 or not s2:
return ''
maxlen = max(len(s1), len(s2))
s1 = s1.zfill(maxlen)
s2 = s2.zfill(maxlen)
result = ''
carry = 0
i = maxlen - 1
while(i >= 0):
s = int(s1[i]) + int(s2[i])
if s == 2: #1+1
if carry == 0:
carry = 1
result = "%s%s" % (result, '0')
else:
result = "%s%s" % (result, '1')
elif s == 1: # 1+0
if carry == 1:
result = "%s%s" % (result, '0')
else:
result = "%s%s" % (result, '1')
else: # 0+0
if carry == 1:
result = "%s%s" % (result, '1')
carry = 0
else:
result = "%s%s" % (result, '0')
i = i - 1;
if carry>0:
result = "%s%s" % (result, '1')
return result[::-1]
Can be simple if you parse the strings by int (shown in the other answer). Here is a kindergarten-school-math way:
>>> def add(x,y):
maxlen = max(len(x), len(y))
#Normalize lengths
x = x.zfill(maxlen)
y = y.zfill(maxlen)
result = ''
carry = 0
for i in range(maxlen-1, -1, -1):
r = carry
r += 1 if x[i] == '1' else 0
r += 1 if y[i] == '1' else 0
# r can be 0,1,2,3 (carry + x[i] + y[i])
# and among these, for r==1 and r==3 you will have result bit = 1
# for r==2 and r==3 you will have carry = 1
result = ('1' if r % 2 == 1 else '0') + result
carry = 0 if r < 2 else 1
if carry !=0 : result = '1' + result
return result.zfill(maxlen)
>>> add('1','111')
'1000'
>>> add('111','111')
'1110'
>>> add('111','1000')
'1111'
It works both ways
# as strings
a = "0b001"
b = "0b010"
c = bin(int(a, 2) + int(b, 2))
# as binary numbers
a = 0b001
b = 0b010
c = bin(a + b)
you can use this function I did:
def addBinary(self, a, b):
"""
:type a: str
:type b: str
:rtype: str
"""
#a = int('10110', 2) #(0*2** 0)+(1*2**1)+(1*2**2)+(0*2**3)+(1*2**4) = 22
#b = int('1011', 2) #(1*2** 0)+(1*2**1)+(0*2**2)+(1*2**3) = 11
sum = int(a, 2) + int(b, 2)
if sum == 0: return "0"
out = []
while sum > 0:
res = int(sum) % 2
out.insert(0, str(res))
sum = sum/2
return ''.join(out)
def addBinary(self, A, B):
min_len, res, carry, i, j = min(len(A), len(B)), '', 0, len(A) - 1, len(B) - 1
while i>=0 and j>=0:
r = carry
r += 1 if A[i] == '1' else 0
r += 1 if B[j] == '1' else 0
res = ('1' if r % 2 == 1 else '0') + res
carry = 0 if r < 2 else 1
i -= 1
j -= 1
while i>=0:
r = carry
r += 1 if A[i] == '1' else 0
res = ('1' if r % 2 == 1 else '0') + res
carry = 0 if r < 2 else 1
i -= 1
while j>=0:
r = carry
r += 1 if B[j] == '1' else 0
res = ('1' if r % 2 == 1 else '0') + res
carry = 0 if r < 2 else 1
j -= 1
if carry == 1:
return '1' + res
return res
#addition of two binary string without using 'bin' inbuilt function
numb1 = input('enter the 1st binary number')
numb2 = input("enter the 2nd binary number")
list1 = []
carry = '0'
maxlen = max(len(numb1), len(numb2))
x = numb1.zfill(maxlen)
y = numb2.zfill(maxlen)
for j in range(maxlen-1,-1,-1):
d1 = x[j]
d2 = y[j]
if d1 == '0' and d2 =='0' and carry =='0':
list1.append('0')
carry = '0'
elif d1 == '1' and d2 =='1' and carry =='1':
list1.append('1')
carry = '1'
elif (d1 == '1' and d2 =='0' and carry =='0') or (d1 == '0' and d2 =='1' and
carry =='0') or (d1 == '0' and d2 =='0' and carry =='1'):
list1.append('1')
carry = '0'
elif d1 == '1' and d2 =='1' and carry =='0':
list1.append('0')
carry = '1'
else:
list1.append('0')
if carry == '1':
list1.append('1')
addition = ''.join(list1[::-1])
print(addition)
Not an optimal solution but a working one without use of any inbuilt functions.
# two approaches
# first - binary to decimal conversion, add and then decimal to binary conversion
# second - binary addition normally
# binary addition - optimal approach
# rules
# 1 + 0 = 1
# 1 + 1 = 0 (carry - 1)
# 1 + 1 + 1(carry) = 1 (carry -1)
aa = a
bb = b
len_a = len(aa)
len_b = len(bb)
min_len = min(len_a, len_b)
carry = 0
arr = []
while min_len > 0:
last_digit_aa = int(aa[len(aa)-1])
last_digit_bb = int(bb[len(bb)-1])
add_digits = last_digit_aa + last_digit_bb + carry
carry = 0
if add_digits == 2:
add_digits = 0
carry = 1
if add_digits == 3:
add_digits = 1
carry = 1
arr.append(add_digits) # will rev this at the very end for output
aa = aa[:-1]
bb = bb[:-1]
min_len -= 1
a_len_after = len(aa)
b_len_after = len(bb)
if a_len_after > 0:
while a_len_after > 0:
while carry == 1:
if len(aa) > 0:
sum_digit = int(aa[len(aa) - 1]) + carry
if sum_digit == 2:
sum_digit = 0
carry = 1
arr.append(sum_digit)
aa = aa[:-1]
else:
carry = 0
arr.append(sum_digit)
aa = aa[:-1]
else:
arr.append(carry)
carry = 0
if carry == 0 and len(aa) > 0:
arr.append(aa[len(aa) - 1])
aa = aa[:-1]
a_len_after -= 1
if b_len_after > 0:
while b_len_after > 0:
while carry == 1:
if len(bb) > 0:
sum_digit = int(bb[len(bb) - 1]) + carry
if sum_digit == 2:
sum_digit = 0
carry = 1
arr.append(sum_digit)
bb = bb[:-1]
else:
carry = 0
arr.append(sum_digit)
bb = bb[:-1]
else:
arr.append(carry)
carry = 0
if carry == 0 and len(bb) > 0:
arr.append(bb[len(bb) - 1])
bb = bb[:-1]
b_len_after -= 1
if carry == 1:
arr.append(carry)
out_arr = reversed(arr)
out_str = "".join(str(x) for x in out_arr)
return out_str