python error UnboundLocalError and issue with logic - python-3.x

This is what I've written:
def logic( arr , r , l ):
arr = []
i == 0
if (arr[i]) == (i +1) * i :
print('True')
i = i + 1
else :
print('False')
return(arr )
arr = list(map(int, input().split()))
r = int(input())
l = int(input())
print(logic(arr,r,l))
This is what we need:
You task is to calculate a boolean array b, where b[i] = true if there exists an integer x,
such that a[i] = (i + 1) * x and l ≤ x ≤ r. Otherwise, b[i] should be set to false.
Example
For a = [8, 5, 6, 16, 5], l = 1, and r = 3, the output should be logic(a, l, r) = [false, false, true, false, true].
For a[0] = 8, we need to find a value of x such that 1 * x = 8, but the only value that would work is x = 8 which doesn't satisfy the boundaries 1 ≤ x ≤ 3, so b[0] = false.
For a[1] = 5, we need to find a value of x such that 2 * x = 5, but there is no integer value that would satisfy this equation, so b[1] = false.
For a[2] = 6, we can choose x = 2 because 3 * 2 = 6 and 1 ≤ 2 ≤ 3, so b[2] = true.
Below is the error:
UnboundLocalError: local variable 'i' referenced before assignment

You are using i == 0. This is an equals to. This is not asigning the variable. I think you are looking for i = 0. == sign is used in If statements etc.
Also may I ask why you are using the parameters arr , r & l in your logic function. But assign them inside the function?
EDIT: I have not programmed in python for a while and missed the indent

Related

Why is the function returning value of stack as None

I'm not able to figure out why the path variable on last line of the code is being printed out as None. As you can see the second last line of the code is calling the DFS function to find the path between two nodes in a tree (I'm giving a tree as input). I've printed out the value of the stack also before returning it to make sure that it is not None and while being printed inside DFS function it is not None. But I'm not able to understand why it is None when it is returned and stored in path variable. I gave this as input
1
6 1
4 2 1 3 5 2
1 2
2 3
2 4
1 5
5 6
And the out put came as
{0: [1, 4], 1: [0, 2, 3], 2: [1], 3: [1], 4: [0, 5], 5: [4]}
[0, 1, 3]
None
Here is the code for reference
def DFS(adj,x, y,stack,vis):
stack.append(x)
if (x == y):
print(stack)
return stack
vis[x] = 1
if (len(adj[x])>0):
for j in adj[x]:
if (vis[j]==0):
DFS(adj,j,y,stack,vis)
del stack[-1]
T = int(input())
for a in range(T):
N,Q = input().split()
N = int(N)
Q = int(Q)
wt = [int(num) for num in input().split(" ")]
adj = {}
for i in range(N):
adj[i] = []
for b in range(N-1):
u,v = input().split()
u = int(u) - 1
v = int(v) - 1
adj[u].append(v)
adj[v].append(u)
print(adj)
vis = [0]*N
stack = []
path = DFS(adj,0,3,stack,vis)
print(path)
Simple equivalent of your code:
def recursive_func(x):
if x > 0:
return x
else:
x += 1
recursive_func(x)
x = 5
x = recursive_func(x)
print(x)
x = 0
x = recursive_func(x)
print(x)
Output:
5
None
What's happening here?
x, with a value of 5 is sent to recursive_func.
x is greater than 0, so 5 is returned. This is seen in the output.
x, with a value of -5 is sent to recursive_func.
x is not greater than 0, so 1 is added to x.
x, with a value of 1, is then sent to a different recursive_func.
This recursive_func returns 1 because 1 > 0.
This response gets passed to the first recursive_func where the line recursive_func(x) becomes 1, but we don't do anything with it.
recursive_function hits the end of its code, without returning a value. By default None is returned to our main body.
x = recursive_func(x) has become x = None
None is output.
Given this information, why does the following code perform differently?
Simple modification of your code:
def recursive_func_v2(x):
if x > 0:
return x
else:
x += 1
return recursive_func_v2(x)
x = 5
x = recursive_func_v2(x)
print(x)
x = 0
x = recursive_func_v2(x)
print(x)
Output:
5
1

How to Sort a table of strings according to the order defined by another table of strings (Lua)

I have 2 lua tables:
OrderTbl = {'Hello', 'Question', 'Answer', 'Bye'}
UnsortedTbl = {'Question', 'Bye, 'Bye', 'Question', 'Hello', 'Something'}
How to sort UnsortedTbl in order given by OrderTbl? (Fields not found in OrderTbl are placed in the end of result table, unsorted)
I have translated a sample of code from Java, and it works with numbers. Here it is:
function first(arr, low, high, x, n)
if high >= low then
-- (low + high)/2
local mid = low + math.floor((high - low) / 2)
if (mid == 1 or x > arr[mid - 1]) and arr[mid] == x then
return mid
end
if x > arr[mid] then return first(arr, (mid + 1), high, x, n) end
return first(arr, low, (mid - 1), x, n)
end
return nil
end
-- Sort A1 according to the order
-- defined by A2
function sortAccording(A1, A2)
local m=#A1
local n=#A2
-- The temp array is used to store a copy
-- of A1{} and visited{} is used to mark the
-- visited elements in temp{}.
local temp = {}
local visited = {}
for i = 1, m do
temp[i] = A1[i]
visited[i] = 0
end
-- Sort elements in temp
table.sort(temp)
-- for index of output which is sorted A1{}
local ind = 0
-- Consider all elements of A2{}, find them
-- in temp{} and copy to A1{} in order.
for i = 1, n do
-- Find index of the first occurrence
-- of A2[i] in temp
local f = first(temp, 1, m, A2[i], m+1)
-- If not present, no need to proceed
if not f then
-- continue
else
-- Copy all occurrences of A2[i] to A1{}
j = f
while j < m and temp[j] == A2[i] do
A1[ind] = temp[j]
ind = ind + 1
visited[j] = 1
j = j + 1
end
end
end
-- Now copy all items of temp{} which are
-- not present in A2{}
for i = 1, m do
if visited[i] == 0 then
ind = ind + 1
A1[ind] = temp[i]
end
end
end
function printArray(arr)
for i = 1, #arr do
print(arr[i] .. " ")
end
end
-- Driver program to test above function.
local A1 = {2, 1, 2, 5, 7, 1, 9, 3, 6, 8, 8}
local A2 = {2, 1, 4, 3, 6, 5, 8, 7}
sortAccording(A1, A2)
printArray(A1)
I don't quite understand how to make it work with strings. Could you help me?
You can use the form of table.sort that accepts a custom comparator:
local OrderTbl = {'Hello', 'Question', 'Answer', 'Bye'}
local UnsortedTbl = {'Question', 'Bye', 'Bye', 'Question', 'Hello', 'Something', 'Else'}
-- convert the order to hash that can be easily queried
for idx, val in ipairs(OrderTbl) do OrderTbl[val] = idx end
local maxIdx = #OrderTbl + 1 -- this will mark "missing" elements
-- pass a custom comparator that will check OrderTbl
table.sort(UnsortedTbl, function(a, b)
local pa = OrderTbl[a] or maxIdx -- desired index of a
local pb = OrderTbl[b] or maxIdx -- desired index of b
if pa == pb then return a < b end -- sort by name
return pa < pb -- sort by index
end)

Sum of Two Arrays - Python

Two random integer arrays/lists have been given as ARR1 and ARR2 of size N and M respectively. Both the arrays/lists contain numbers from 0 to 9(i.e. single digit integer is present at every index). The idea here is to represent each array/list as an integer in itself of digits N and M.
You need to find the sum of both the input arrays/list treating them as two integers and put the result in another array/list i.e. output array/list will also contain only single digit at every index.
NOTE:
The sizes N and M can be different.
Output array/list(of all 0s) has been provided as a function argument. Its size will always be one more than the size of the bigger array/list. Place 0 at the 0th index if there is no carry.
No need to print the elements of the output array/list.
def sumOfTwoArrays(arr1, n, arr2, m, output) :
#Your code goes here
#Taking Input Using Fast I/O
def takeInput() :
n = int(stdin.readline().rstrip())
if n == 0 :
return list(), 0
arr = list(map(int, stdin.readline().rstrip().split(" ")))
return arr, n
#to print the array/list
def printList(arr, n) :
for i in range(n) :
print(arr[i], end = " ")
print()
#main
t = int(stdin.readline().rstrip())
while t > 0 :
arr1, n = takeInput()
arr2, m = takeInput()
outputSize = (1 + max(n, m))
output = outputSize * [0]
sumOfTwoArrays(arr1, n, arr2, m, output)
printList(output, outputSize)
t -= 1
Sample Input:
1
3
6 2 4
3
7 5 6
Sample Output:
1 3 8 0
This problem can be solved by a simple function like this:
(Note - you can made adjustment on the last line of return result if needed to meet the "strange requirement" of - 'place 0 at the 0th index if there is no carry'. It's left as a trivial exercise. )
def sum_two_array(L1, L2):
carry, total = 0, 0
m, n = len(L1), len(L2)
k = max(m, n)
result = [0] + [0] * k # add +1
for i in range(1, k+1):
a = L1[m-i] if m - i >= 0 else 0
b = L2[n-i] if n - i >= 0 else 0
total = a + b + carry
result[k-i + 1] = total % 10
carry = total // 10
if carry > 0: result[0] = carry
return result if result[0] != 0 else result[1:]
if __name__ == '__main__':
L1 = [6, 4, 4]
L2 = [7, 5, 6]
print(sum_two_array(L1, L2)) # [1, 4, 0, 0]
print(sum_two_array([6, 2, 4], [7, 5, 6])) # [1, 3, 8, 0]
print(sum_two_array([1, 2, 4], [8, 0])) # [2, 0, 4]
JAVA CODE:
import java.lang.Math;
public class Solution {
public static void sumOfTwoArrays(int arr1[], int arr2[], int output[]) {
int n = arr1.length; //size of arr1
int m = arr2.length; //size of arr2
int o = n+1; //size of output array
int sum1 = 0, sum2=0, totalSum=0;
//storing sum of arr1 in sum1
for(int i=0; i<n; i++)
{
sum1+= arr1[i] * Math.pow(10,(n-1-i));
}
//storing sum of arr2 in sum2
for(int i=0; i<m; i++)
{
sum2+= arr2[i] * Math.pow(10, (m-1-i));
}
totalSum = sum1+sum2;
//storing totalSum in reverse order in output array
for(int i=o-1; i>=0; i--)
{
output[i] = totalSum % 10;
totalSum = totalSum/10;
}
}
}
Explanation:
condition: arr1[n], arr2[m], output[n+1]
Instead of calculating sum of unit, tens, and so on digits of both the arrays.
we first calculate the sum1 of arr1, and sum2 of arr2, by using:
number at index * (10 ^ ((n-1) - index)) concept.
sum1 and sum2 are equal to the n and m sized numbers of respective arrays
we store totalSum = sum1+sum2
we store totalSum's every digit in output[n+1] array
we store it in reverse order by using % and / operations

I am writing a code based on some formulas;but my if statement does not seem to work(line 33)

W = int(input('Enter weight:'))
b = [1.2, 1.3, 1.4, 1.5, 1.6, 1.7, 1.8, 1.9, 2.0]
AR = [1, 2, 3, 4, 5]
T = [50.99238, 50.05062, 49.07943, 48.05919, 47.00952, 45.92061, 44.79246, 43.62507, 42.42825, 41.18238, 39.90708, 38.60235, 37.24857, 35.86536, 34.4331, 32.97141, 31.48029, 29.94012, 28.37052, 26.76168, 25.1136]
CL = [1.0]
CD = [0.5]
clmax = 2
n = 0
z = 0
while b[n] < 2.1 :
while AR[z]< 5.1:
cl = CL[n]
cd = CD[z]
s = ((b[n]*b[n])/AR[z])
V = ((2*W*9.81)/(1.2*s*clmax) ** 0.5)*1.1
vlof = V/1.41
Vlof = round(vlof)
D = 0.5*cd*1.2*Vlof*Vlof*s
L = 0.5*cl*1.2*Vlof*Vlof*s
a = (9.81/W)*(T[Vlof]-D-O.O5(W-L))
Sg = (V*V)/(2*a)
if Sg <= 30:
print('IT WILL TAKEOFF')
else:
print('It will NOT takeoff')
t/c = int(input('t/c ratio is:'))
l = int(input('Taper ratio is:'))
f = 0.005(1+1.5*((l-0.6)**2))
e = (1/((1+0.12*V*V*0.003*0.003)(1+(0.142+(f*AR[z]*(10*t/c)**0.33)
+(0.1/(4+AR[z])**0.8))
if z <= 5: # line 33 #
z +=1
else :
break
n+=1
OUTPUT:
File "<ipython-input-49-d7d52927efb2>", line 33
if z <= 5:
^
SyntaxError: invalid syntax
This is a code which should tell me whether my aircraft will takeoff or not (on the input of a weight)
I cannot seem to understand the reason why is this syntax invalid ?
There are several errors in the code you provided. I tried to clean it up as best as I could. The following does not cause an error by default. This does not mean that the code does what it is supposed to do. You should still check that.
Your lists like CL and CD do not contain enough elements for most cases which will cause IndexError: list index out of range. You should extend those lists or use a different kind of logic to make sure this does not happen.
W = int(input('Enter weight:'))
b = [1.2, 1.3, 1.4, 1.5, 1.6, 1.7, 1.8, 1.9, 2.0]
AR = [1, 2, 3, 4, 5]
T = [
50.99238, 50.05062, 49.07943, 48.05919, 47.00952, 45.92061, 44.79246,
43.62507, 42.42825, 41.18238, 39.90708, 38.60235, 37.24857, 35.86536,
34.4331, 32.97141, 31.48029, 29.94012, 28.37052, 26.76168, 25.1136
]
CL = [1.0]
CD = [0.5]
clmax = 2
n = 0
z = 0
while b[n] < 2.1:
while AR[z] < 5.1:
cl = CL[n]
cd = CD[z]
s = ((b[n]*b[n])/AR[z])
V = ((2*W*9.81)/(1.2*s*clmax) ** 0.5)*1.1
vlof = V/1.41
Vlof = round(vlof)
D = 0.5*cd*1.2*Vlof*Vlof*s
L = 0.5*cl*1.2*Vlof*Vlof*s
# O.O5 -> 0.05*: you used the letter 'O' instead of '0' (zero). also
# you always have to use * if you want to multiply something. you
# cannot leave it out.
a = (9.81/W)*(T[Vlof]-D-0.05*(W-L))
Sg = (V*V)/(2*a)
if Sg <= 30:
print('IT WILL TAKEOFF')
else:
print('It will NOT takeoff')
# t/c -> t_c: you cannot use special characters when defining
# variables. best stick to lower- and upper-case letters,
# the underscore and numbers.
t_c = int(input('t/c ratio is:'))
l = int(input('Taper ratio is:'))
# a whole lot of closing parentheses and '*' were missing here. also
# cleaned up the formatting
f = 0.005*(1+1.5*((l-0.6)**2))
e = (
1 / (
(1+0.12*V*V*0.003*0.003)*(
1 + (
0.142+(f*AR[z]*(10*t_c)**0.33)
+ (0.1/(4+AR[z])**0.8)
)
)
)
)
# in Python, space has meaning. it determines which part of the code
# is executed at which level in the routine. you cannot chose it
# arbitrarily.
if z <= 5:
z += 1
else:
break
n += 1

Printing fibonacci series using lists in python

I am relatively a noobie in programming and trying to learn python. I was trying to implement a Fibonacci series into a list within 10.
fibo= [0,1]
for k in range(11):
i= fibo[-1]
j = fibo[-2]
k= fibo[i]+fibo[j]
fibo.append(k)
k=+1
print(fibo)
Not sure what I did wrong? Any help is really appreciated!
Output:
[0, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2]
You can use this code to print fibonacci series upto N.
N = int(input()) # Length of fibonacci series
fibo = [0, 1]
a = fibo[0]
b = fibo[1]
for each in range(2, N):
c = a + b
a, b = b, c
fibo.append(c)
print(fibo[:N])
OUTPUT
N = 10
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
I can see few issues here:
fibo = [0,1]
# Your loop should start at index 2, otherwise
# you will try to access fibo[-2] and fibo[-1] with k=0
# and fibo[-1] and fibo[0] with k=1
# Also, if you only want 10 values, you should change 11
# to 10 since fibo already has two values.
# for k in range(11):
for k in range(2, 10):
# You don't want the content of fibo, but the indexes!
# i = fibo[-1]
# j = fibo[-2]
i = k - 1
j = k - 2
# You are already using k, so you need to use an other variable
# k = fibo[i] + fibo[j]
v = fibo[i] + fibo[j]
fibo.append(v)
# You don't need k+=1 because it will be incremented
# according to range(2, 10). The loop will start with
# k = 2 and it will stop when k = 9
# k += 1
print(fibo)
Your code did not crash because you technically can access fibo[-1] and fibo[-2]. It will respectively return the last value of your array, and the value before the last one.

Resources