fibbonnacci. sequence UnboundLocalError - python-3.x

I've been working on this Fibbonacci sequence function. I am essentially returning a list of the Fibbonacci sequence by growing out a returned list respective to the number sequence that is generated by passing in a particular number. however I'm encountering an error within my for loop at the if statement within that for loop. it states UnboundLocalError: local variable 'new_list' referenced before assignment. Does anyone have a clue how to remedy this? Any help will be appreciated. thanks
def fib_n(num):
if num < 0:
print("You have entered incorrect output")
elif num == 0:
new_list = []
else:
for index in range(1,num):
if index == 1 or index == 2:
new_list.append(1)
continue
new_list.append(new_list[index - 1] + new_list[index - 2])
return new_list

Related

Skipping a value in a range within a for loop

So the course I'm in posted an exercise:
# Modify the code inside this loop to stop when i is exactly divisible by 11
for i in range(0, 100, 7):
print(i)
I added:
if i % 11 == 0:
break
However my code gets stuck on the first value as it is 0 thus ending the program.
What function would I use to skip over the first value and proceed with the rest of the range?
Any help would be greatly appreciated!
To "skip over" a certain value (here 0), you can use python's continue
for i in range(0, 100, 7):
print(i)
if i == 0:
continue
if i % 11 == 0:
break
This is like a break statement, but it returns you to the top of the loop instead of skipping to the end of it.
You could also do as below:
print(0)
for i in range(1, 100, 7):
print(i)
if i % 11 == 0:
break
Print the first value and start the loop from index 1.

Dynamic Programming Primitive calculator code optimization

I am currently doing coursera course on algorithms. I have successfully completed this assignment. All test cases passed. My code looks messy and I want to know if there is any thing availiable in Python which can help run my code faster. Thanks
The problem statement is as follows: You are given a primitive calculator that can perform the following three operations with
the current number 𝑥: multiply 𝑥 by 2, multiply 𝑥 by 3, or add 1 to 𝑥. Your goal is given a
positive integer 𝑛, find the minimum number of operations needed to obtain the number 𝑛
starting from the number 1.
# Uses python3
import sys
def optimal_sequence(m):
a=[0,0]
for i in range(2,m+1):
if i%3==0 and i%2==0:
a.append(min(a[i//2],a[i//3],a[i-1])+1)
elif i%3==0:
a.append(min(a[i//3],a[i-1])+1)
elif i%2==0:
a.append(min(a[i//2],a[i-1])+1)
else:
a.append((a[i-1])+1)
return backtrack(a,m)
def backtrack(a,m):
result=[]
result.append(m)
current = m
for i in range(a[-1],0,-1):
if current%3==0 and a[current//3]==(i-1):
current=current//3
result.append(current)
elif current%2==0 and a[current//2]==(i-1):
current = current//2
result.append(current)
elif a[current-1]==(i-1):
current = current-1
result.append(current)
return result
n = int(input())
if n == 1:
print(0)
print(1)
sys.exit(0)
a= (optimal_sequence(n))
print(len(a)-1)
for x in reversed(a):
print(x,end=" ")
I would use a breadth first search for number 1 starting from number n. Keep track of the numbers that were visited, so that the search backtracks on already visited numbers. For visited numbers remember which is the number you "came from" to reach it, i.e. the next number in the shortest path to n.
In my tests this code runs faster than yours:
from collections import deque
def findOperations(n):
# Perform a BFS
successor = {} # map number to next number in shortest path
queue = deque() # queue with number pairs (curr, next)
queue.append((n,None)) # start at n
while True:
curr, succ = queue.popleft()
if not curr in successor:
successor[curr] = succ
if curr == 1:
break
if curr%3 == 0: queue.append((curr//3, curr))
if curr%2 == 0: queue.append((curr//2, curr))
queue.append((curr-1, curr))
# Create list from successor chain
result = []
i = 1
while i:
result.append(i)
i = successor[i]
return result
Call this function with argument n:
findOperations(n)
It returns a list.

who to pass index of a loop (for loop) in python

I put this pre defined part in my python code, the aim of code is to get last 2 digits and put it on cluster list based on the predefined logic in cluster (index as list[1] and variable of index in cluster(2).
Now I have problem with my loop that says there are indentation error.
def find_min(matrix=[]):
i,j=0,0
min1=[1000,0,0]
while i <len(matrix):
while j <len(matrix):
if matrix[i][j] != 0:
if min1[0]>matrix[i][j]:
min1[0]=matrix[i][j]
min1[1]=i
min1[2]=j
j+=1
j=0
i+=1
return min1[1:]
def check_min(variable,list2=[]):
i=0
min=1000
list3=list2[:]
result=0
while i<len(list3):
if variable-list3[i]>0:
result=variable-list3[i]
list3[i]=result
else:
result=list3[i]-variable
list3[i]=result
i+=1
i=0
while i<len(list3):
if min>list3[i]:
min=list3[i]
i+=1
return min
def grouped(variable,cluster=[]):
cluster1=cluster[:]
k=0
list3=[]
index=0
while k<3:
index=k
if variable in cluster1[index]:
list3.append(1)
list3.append(cluster[index])
return list1
else:
continue
K+=1
return [0,-1]
list1=[10,11,30,40,70,80]
cluster=[[0,1][10,11],[2,3],[30,40],[],[]]
Then I want to have this loop to work but it shows me idiot errors!
w, h = len(list1), len(list1)
matrix = [[None for x in range(w)] for y in range(h)]
i,j,z=0,0,0
check=0
check2=0
k,e=0,0
flag1=0
index1,index2=0,0
index_i=0
index_j=0
index_cluster_i=0
index_cluster_j=0
temp1=[]
while i <len(list1):
index1=i
while j <len(list1):
index2=j
#if i is in a cluster already
temp1=grouped(index1,cluster)
index_i=temp1[0]
index_cluster_i=temp1[1]
#if j is in a cluster already
temp1=grouped(index2,cluster)
index_j=temp1[0]
index_cluster_j=temp1[1]
if(i>j):
matrix[i][j]=0
elif (index_i==1 and index_j==1):
matrix[i][j]=0
elif(index_i==1 and index_j==0):
matrix[i][j]=check_min(list1[j],cluster[index_cluster_i])
elif(index_i==0 and index_j==0):
if list1[i]>list1[j]:
matrix[i][j]=list1[i]-list1[j]
else:
matrix[i][j]=list1[j]-list1[i]
j+=1
i+=1
error is:
unindent does not match any outer indentation level
This error is for improper indentations align each block under its statement.
Like:
if i === True:
pass
else:
pass

How to keep the ID the same for a list when appending

Trying to obtain a list without changing the ID of the original list and the list can only contain spaces between each element.
I keep getting this error and I am unable to find a way to keep its ID the same whilst having only spaces in between each element whilst printing it out.
newlist=[array[x] for x in range(len(array)) if x !=0]
array=[]
array.append(newlist)
newlist=[]
print(' '.join(array))
TypeError: sequence item 0: expected str instance, list found
The error message is for the last line
while ans:
ans=input("\nSelect an option?\n")
if ans=="A":
if len(array) < 10:
A = list(input('\nInput string: \n'))
if len(A) == 1 and str(A):
array += A
if len(array) == 10:
print( "Invalid input\n")
elif ans=="P":
print(' '.join(array))
elif ans=="N":
newlist=[array[x] for x in range(len(array)) if x !=0]
array=[]
array.append(newlist)
newlist=[]
print(' '.join(array))
elif ans=="M":
print(id(array))
This is what half the code looks like.
What I intend is that the ID should always stay the same and when N is inputted the first element of the array is removed
No use of pop, del, remove, slicing and index is allowed
What about "clear" then? :) Python 3.3 and higher
elif ans=="N":
newlist=[array[x] for x in range(len(array)) if x !=0]
array.clear()
array.extend(newlist)
print(' '.join(array))

Update list in for loop using list.append

The variable mult is not updated as the program runs. What is the issue with this code? The run results show me that the loop is actually working as I wanted but for the list update and final print
number = 18
for i in range(int(number/2)):
i += 1
mults = []
if number % i == 0:
mults = mults.append(i)
print(i)
elif number % i != 0:
pass
elif i == int(number/2):
print(mults)
with this other code I get the error: AttributeError: 'NoneType' object has no attribute 'append'
number = 18
mults = []
for i in range(int(number/2)):
i += 1
if number % i == 0:
mults = mults.append(i)
print(i)
elif number % i != 0:
pass
print(mults)
number = 18
mults = []
for i in range(int(number/2)):
i += 1
if number % i == 0:
mults.append(i)
print(i)
elif number % i != 0:
pass
print(mults)
Few notes, move mults outside of the for loop so you aren't over writing it every time the loop runs.
You don't need that last elif statement, just print(mults) when the for loop is done, is basically the last elif statement.
mults.append(i) is in line meaning it changes the list mults automatically and you don't need to reassign it.

Resources