name 'count' is not defined in python - python-3.x

I have this code in python and I am trying to make a counter for the iteration of the binary search (yeah I know it is incomplete...), but I am stuck with the variable inside the function, when i try to print the variable count I get this error
name 'count' is not defined in python
can someone explain why i get this error?
import csv
def binarySearch(arr, l, r, x):
count=0
while l <= r:
mid = int(l + (r - l) / 2)
# Check if x is present at mid
if arr[mid] == x:
return mid
# If x is greater, ignore left half
elif arr[mid] < x:
l = mid + 1
# If x is smaller, ignore right half
else:
r = mid - 1
# If we reach here, then the element
# was not present
return -1
with open('bl_printed_music_500.csv', newline='', encoding="utf-8-sig") as csvfile:
reader = csv.DictReader(csvfile)
arr=[]
for row in reader:
if row ["Publication date (standardised)"] != "":
arr.append(int(row["Publication date (standardised)"])) #create list for searching
list.sort(arr) #list must be sorted to work
#print (arr)
x = 1850 #year to search
# Function call
result = binarySearch(arr, 0, len(arr) - 1, x)
found = False
if result != -1:
found = True
print(found)
print(count)

I think it's because you defined count in binarySearch but try to use it outside of the method. Try using a global variable (define it outside of binarySearch), it should work.

You can return count as well.
For example:
def myFunc():
x = 5
y = 10
return x,y
a, b = myFunc()
print(a)
print(b)
This will be:
5
10
Note that, I could have written x, y = myFunc(). These x and y are not the same as the ones inside myFunc(). The latter are local to the function.
In your code, you can return your local count variable:
return mid, count #(A)
return -1, count #(A)
And get its value by:
result, count = binarySearch(arr, 0, len(arr)-1, x) #(B)
Again, these two count variables, (A) and (B) are different variables with different scopes.
See, for instance:
https://docs.python.org/3/faq/programming.html#why-am-i-getting-an-unboundlocalerror-when-the-variable-has-a-value
Alternatively, if a global variable, as suggested in the other answer, suits you best, you can see an example of its usage in the link.

Related

Values in list are sometimes switching and i dont know why

I'm programming a length conversion calculator in python. I will convert the input to a sheet. Then I compare the input (as a set) with the dictionary and pull the appropriate values. My problem is that sometimes the values in the list are stored in the opposite order than they should be. For example mm -> m should always be stored as [0, 3] in the list but sometimes it gets switched [3, 0] and I don't know why. I tried the import -> Orderedlist method. Still the same problem. Here is my code.
def prevod_delky():
x = None #vstup format list
y = None
z1 = {'mm':0, 'cm':1, 'dm':2, 'm':3}
x = input('Enter the value and conversion units. E.g. mm -> cm. \n')
x = x.lower().split(' ', 2)
try:
x[0].replace('.', '', 1).isdigit()
x[0] = float(x[0])
except:
print('Enter only digits!')
prevod_delky()
try:
y = {k: z1[k] for k in z1.keys() & set(x)}
y = list(y.values())
except:
print('Something went wrong!')
prevod_delky()
try:
a = abs(int(y[0] - y[1]))
if y[0] > y[1]:
for y in range(0, a):
x[0] = x[0] * 10
else:
for y in range(0, a):
x[0] = x[0] / 10
except:
print('Something went wrong')
finally:
print('The resulting length is {} {}'.format(x[0], x[2]))
prevod_delky()
I tried the import -> Orderedlist method.
I checked Python version (using 3.8.1)

Convert a number to binary in Python

Given a non-negative integer n, write a function to_binary/ToBinary which returns that number in a binary format.
This is my code but some tests don't pass.
I appreciate it if you help me fix my code:
def to_binary(n):
string = ""
if n > 2:
string = string + str(n % 2)
x = n // 2
while x >= 2:
i = x % 2
string = string + str(i)
x = x // 2
string = string + str(1)
l = len(string)
string[l::-1]
return int(string)
else:
if n == 1:
return 1
if n == 2:
return 10
Few points to note.
Changing the concatenation logic will generate the string in reverse. You won't have to reverse it in the end.
In [10]: s = ''
In [11]: for i in range(5):
...: s = s + str(i)
...:
In [12]: s
Out[12]: '01234'
In [13]: s = ''
In [14]: for i in range(5):
...: s = str(i) + s # add the existing string after i
...:
In [15]: s
Out[15]: '43210'
You don't require a different logic for numbers less than 2. You shouldn't have to hardcode anything unless you're using recursion. In which case, hardcoding is simply the base case.
You are not reversing the string at all.
s[::-1]
This does not reverse a string in-place. Strings in python are immutable. What you can do is,
s = s[::-1]
Not providing the limits in a slice syntax is the same as providing start and end values (0 and length). You don't have to explicitly write s[len(s)::-1].
Your logic is almost correct. Just remove everything and keep the while loop and the code will work.
def to_bin(x):
if x == 0:
return '0'
b = ''
while x > 0:
b = str(x%2) + b
x //= 2
return b
There are of course several ways to do this without writing code just by using the builtin features of python.
You could try the implementing the mathematical method of converting bases into Python. Every number can be expressed as the sum of the powers of a base. For binary, base 2, this would be N*2**n + ... + A*2**3 + B*2**2 + C*2**1 + D*2**0. The hardest part is finding N, but from there we can use divmod to solve for the other variables.
def get_highest_power(num, base=2):
n = 0
while True:
if base**(n+1) >= num:
break
n += 1
return n
def solve_for_coefficients(num, power, base=2):
coefficients = []
for p in range(power, -1, -1):
coef, num = divmod(num, base**p)
coefficients.append(coef)
return coefficients
leading_power = get_highest_power(1000)
coefficients = solve_for_coefficients(1000, leading_power)
In order to get the base conversion, just use something like int(''.join([str(i) for i in coefficients])). This method works for all bases less than 10, since bases after ten require letters (but then again, you could use look at the items in coefficients to get the letters).
If you just want to solve the problem "number to binary string", you could use simple python:
def to_binary(n):
return "{:b}".format(n)
Simply use bin() instead.
def to_binary(n):
return(bin(n)[2:])
to_binary(6)
'110'

counting number of pairs with same elem value in python list

I don't understand why the function is returning 4 while it should return 3. Thank you very much.
x = [10,20,20,10,10,30,50,10,20]
s = {}
count = 0
for item in x:
if (item in s):
s[item] += 1
else:
s[item] = 1
for z, w in s.items():
count += w/2
print(int(count))
From your description of what you said, of wanting to count pairs, then I believe you would want to round down the number being added to count instead of count overall, as 2 halves would end up making 1.
The following does return 3.
x = [10,20,20,10,10,30,50,10,20]
s = {}
count = 0
for item in x:
if (item in s):
s[item] += 1
else:
s[item] = 1
for z, w in s.items():
count += int(w/2)
print(count)
In Python, a single slash ”/“ does a regular divide that returns with decimals. A double slash “//“ returns a whole number rounded down. When you call int() on the number, it rounds it down to nearest whole number.
In your code, you get:
2+1.5+0.5+0.5=4.5
After calling int on 4.5, it becomes 4.
You are adding floats in the for loop, just change that to ints and it will add up to 3.
x = [10,20,20,10,10,30,50,10,20]
s = {}
count = 0
for item in x:
if (item in s):
s[item] += 1
else:
s[item] = 1
for z, w in s.items():
count += int(w/2)
print(int(count))

Change specific elements of a matrix puzzle - Python

I have to solve how to replace the elements below zero elements with zeros and output the sum of the remaining elements in the matrix.
For example, [[0,3,5],[3,4,0],[1,2,3]] should output the sum of 3 + 5 + 4 + 1 + 2, which is 15.
So far:
def matrixElementsSum(matrix):
out = 0
# locate the zeros' positions in array & replace element below
for i,j in enumerate(matrix):
for k,l in enumerate(j):
if l == 0:
break
out += l
return out
The code outputs seemingly random numbers.
Can someone fix what's wrong? Thanks
You can easily drop elements that are below a zero element is by using the zip function.
def matrixElementsSum(matrix):
out = 0
# locate the zeros' positions in array & replace element below
for i,j in enumerate(matrix):
# elements in the first row cannot be below a '0'
if i == 0:
out += sum(j)
else:
k = matrix[i-1]
for x, y in zip(j, k):
if y != 0:
out += x
return out
Now consider naming your variables a little more meaningfully. Something like:
def matrixElementsSum(matrix):
out = 0
# locate the zeros' positions in array & replace element below
for row_number, row in enumerate(matrix):
# elements in the first row cannot be below a '0'
if row_number == 0:
out += sum(row)
else:
row_above = matrix[row_number - 1]
for element, element_above in zip(row, row_above):
if element_above != 0:
out += element
return out
You should look into list comprehensions to make the code even more readable.

Generating Fibonacci series in Python

I want to simple generate the fibonacci series in Python. But somehow i don't see the correct series. For example if i input 3 then the correct answer should come with the series : 1 1 2 3
Below is my code.Can someone please point out what is wrong with this :
def genfibonacci(no):
if no <= 1:
return no
else:
sum = genfibonacci(no - 1) + genfibonacci(no - 2)
print (sum)
return(sum)
number = int(input())
genfibonacci(number)
Thanks in advance.
Part of your problem is printing while you calculate (apart from if no <= 1)
If we remove the print, and just show what you get as a result this will help:
def genfibonacci(no):
if no <= 1:
sum = no
else:
sum = genfibonacci(no-1) + genfibonacci(no-2)
return sum
>>> [genfibonacci(i) for i in range(4)]
[0, 1, 1, 2]
>>> [genfibonacci(i) for i in range(5)]
[0, 1, 1, 2, 3]
This range starts at 0, so you can remove that if you want.
Since genfibonacci for say 4 will call 32 and 2, which in turn will call 2 and 1, the print statement you have will happen for the same number more than once.
And not at all for the no <= 1.
There are so many ways to calculate fibonacci sesries in python..
Example 1: Using looping technique
def fib(n):
a,b = 1,1
for i in range(n-1):
a,b = b,a+b
return a
print fib(5)
Example 2: Using recursion
def fibR(n):
if n==1 or n==2:
return 1
return fib(n-1)+fib(n-2)
print fibR(5)
Example 3: Using generators
a,b = 0,1
def fibI():
global a,b
while True:
a,b = b, a+b
yield a
f=fibI()
f.next()
f.next()
f.next()
f.next()
print f.next()
Example 4: Using memoization
def memoize(fn, arg):
memo = {}
if arg not in memo:
memo[arg] = fn(arg)
return memo[arg]
fib() as written in example 1.
fibm = memoize(fib,5)
print fibm
Example 5: Using memoization as decorator
class Memoize:
def __init__(self, fn):
self.fn = fn
self.memo = {}
def __call__(self, arg):
if arg not in self.memo:
self.memo[arg] = self.fn(arg)
return self.memo[arg]
#Memoize
def fib(n):
a,b = 1,1
for i in range(n-1):
a,b = b,a+b
return a
print fib(5)
Here the Simplest Fibonacci Series represnted:
#Fibonacci series in Short Code
#initilize the base list
ls2=[0,1]
#user input: How many wants to print
c=int(input('Enter required numbers:'))
#fibonacci Function to add last two elements of list
ls2.extend((ls2[i-1]+ls2[i-2]) for i in range(2,c))
#This will print recuired numbers of list
print(ls2[0:c])
If you Want Create Function Then:
#Fibonacci series in Short Code
#initilize the base list
ls2=[0,1]
#user input: How many wants to print
c=int(input('Enter required numbers:'))
#fibonacci Function to add last two elements of list
def fibonacci(c):
ls2.extend((ls2[i-1]+ls2[i-2]) for i in range(2,c))
#This will print required numbers of list
print(ls2[0:c])
fibonacci(c)
Fibonacci using Recursive Function in Python:
def fibonacci(n, fib1=0, fib2=1):
if n<=1:
print(fib1)
return
else:
print(fib1)
fib = fib1 + fib2
fib1 = fib2
fib2 = fib
fibonacci(n - 1, fib1, fib2)
number = int(input())
fibonacci(number)
There are different methods you can use but I use the method of recursion because here you have to code less
def fib(n):
if n<=1:
return n
else:
return fib(n-1)+fib(n-2)
n = int(input())
for i in range(n):
print(fib(i),sep=' ',end=' ')

Resources