When I am running this program, then it is printing "Calling function" but the function call after that is not working. When I am calling the function in Idle, then it is working fine. Where is the mistake?
def find(word, letter):
index = 0
while index < len(word):
if word[index] == letter:
return index
index = index + 1
return -1
print('Calling function')
find('banana', 'a')
The function is returning some value.
Try this:
def find(word, letter):
index = []
i = 0
while i < len(word):
if word[i] == letter:
index.append(i)
i = i + 1
return index
print('Calling function')
print find('banana', 'a')
Related
In the function of find_shortest_func, i think if now position isn't "T" which is also known as the terminal or exit, then i will try to find for direction and see if it is "T", if not, check if it is space and i can go there. Besides, tell the next state function now output and dic to tell the place where i visited. But some errors occur and I don't know why.
I think the problem may occur where I tried to deepcopy the output list
import copy
def set_symbol(symbol_name):
def set_symbol_decorator(func):
def wrapper(self, symbol):
setattr(self, symbol_name, symbol)
return wrapper
return set_symbol_decorator
class Maze:
space_symbol = " "
obstacle_symbol = "X"
path_symbol = "•"
output = []
dis = 0
def __init__(self, input_string):
self.maze = []
if input_string.endswith("txt"):
with open(input_string) as f:
count = 0
for line in f.readlines():
self.maze.append([])
for j in line:
if j != '\n':
self.maze[count].append(j)
count += 1
else:
count = 0
for i in input_string.split("\n"):
self.maze.append([])
for j in i:
self.maze[count].append(j)
count += 1
def __str__(self):
output_string = ""
for i in range(20):
for j in range(20):
output_string += self.maze[i][j]
output_string += "\n"
return output_string
#set_symbol("space_symbol")
def set_space_symbol(self, change):
pass
#set_symbol("obstacle_symbol")
def set_obstacle_symbol(self, change):
pass
#set_symbol("path_symbol")
def set_path_symbol(self, change):
pass
def find_shortest_func(self, position: tuple, d: dict, out: list, dis: int):
dic = copy.deepcopy(d)
output = copy.deepcopy(out)
dic[(position[0], position[1])] = 1
output.append((position[0], (position[1])))
dis += 1
if self.maze[position[0]][position[1]] != "T":
if position[0]+1 < 20 and self.maze[position[0]+1][position[1]] == self.space_symbol and (position[0]+1, position[1]) not in dic:
self.find_shortest_func(
(position[0]+1, position[1]), dic, output, dis)
if position[1]+1 < 20 and self.maze[position[0]][position[1]+1] == self.space_symbol and (position[0], position[1]+1) not in dic:
self.find_shortest_func(
(position[0], position[1]+1), dic, output, dis)
if position[0]-1 >= 0 and self.maze[position[0]-1][position[1]] == self.space_symbol and (position[0]-1, position[1]) not in dic:
self.find_shortest_func(
(position[0]-1, position[1]), dic, output, dis)
if position[1]-1 >= 0 and self.maze[position[0]][position[1]-1] == self.space_symbol and (position[0], position[1]-1) not in dic:
self.find_shortest_func(
(position[0], position[1]-1), dic, output, dis)
if self.maze[position[0]][position[1]] == "T":
if dis < self.dis:
self.output = copy.deepcopy(output)
self.dis = dis
return
def find_shortest_path(self):
d = dict()
output = []
dis = -1
self.find_shortest_func((1, 0), d, output, dis)
return self.output, self.dis
I'm trying to create a function. Function; it will simply be designed to increase the last letter sequence from its position in the alphabet or letter list.
import time
def CountDown(text,reply=3):
abc = list("ABCDEFGHIJ")
c = 1
text_list = list(text)
while 1:
Index = abc.index(text_list[-c])
if not list(filter(lambda a: a!=abc[-1], text_list)):
return "".join(text_list)
if text_list[-c] == abc[-1]:
text_list[-c] = abc[0]
c += 1
continue
else:
s=1
while 1:
text_list[-c] = abc[(Index+s) if (Index+s)<len(abc) else 0]
if text_list.count(abc[(Index+s) if (Index+s)<len(abc) else 0])+1<reply:
break
s+=1
text_list[-c] = abc[(Index+s) if (Index+s)<len(abc) else 0]
return "".join(text_list)
if __name__ == "__main__":
code="ABHD"
while 1:
code=CountDown(code)
time.sleep(0.5)
print(code)
OUTPUT:
ABHE
ABHF
ABHG
ABHI
ABHJ
ABIA
ABIC
ABID
ABIE
ABIF
ABIG
ABIH
ABIJ
ABJA
ABJC
ABJD
ABJE
ABJF
ABJG
ABJH
ABJI
....(idling)
The code doesn't give an output after a while. I think there is something wrong.
How can I fix this code sample?
for example
def ex(n):
for i in range(n):
return i
n = int(input("enter : " ))
x = ex(n)
print(x)
i'm trying to print values from 0 to 10 one by one. But, it just returning only 0 with this method.
That's because return gets out of the function (stops the function) and returns one value
you can try this:
def ex(n):
for i in range(n+1):
print(i)
n = int(input("enter : " ))
x = ex(n)
print(x)
or this if you need a returning value
def ex(n):
nlist = []
for i in range(n+1):
nlist.append(i)
return nlist
n = int(input("enter : " ))
x = ex(n)
for i in range(len(x)):
print(x[i])
or just use yield:
def ex(n):
for i in range(n+1):
yield i
n = int(input("enter : " ))
x = ex(n)
for i in x:
print(i)
So, there's a couple ways of playing this, and it depends on your intent. If you want ex to return a string of the numbers 0 to 10, given 10, you can just do:
def ex(n):
return " ".join([str(x) for x in range(n+1)])
If you want to return a generator, a thing that returns an iterable, you can do:
def ex(n):
for i in range(n+1):
yield i
n = int(input("enter : " ))
for x in ex(n):
print(x)
I am trying merge sort but the values in the list is not updating . I know arguments are passed by assignments .but how this code is not working
def mergeSort(arr):
#add code here
if len(arr) <2 :
return
mid = len(arr)//2
s1 = arr[:mid]
s2 = arr[mid:]
mergeSort(s1)
mergeSort(s2)
i= 0 ; j =0
while i+j < len(arr):
if i<len(s1) or j ==len(s2) and s1[i] <s2[j] :
arr[i+j] = s1[i]
i +=1
else :
arr[i+j] = s2[j]
j +=1
return arr
mergeSort(arr)
for ex arr =[5,4,3,2,1]
the output is same arr,
but this code is working fine
def mergeSort(arr):
#add code here
if len(arr)>1:
mid=len(arr)//2
l=arr[:mid]
r=arr[mid:]
mergeSort(l)
mergeSort(r)
i=j=k=0
while i<len(l) and j<len(r):
if l[i]<r[j]:
arr[k]=l[i]
i+=1
else:
arr[k]=r[j]
j+=1
k+=1
while i<len(l):
arr[k]=l[i]
i+=1
k+=1
while j<len(r):
arr[k]=r[j]
j+=1
k+=1
return arr
mergeSort(arr)
I don't know what i'm missing ? How the one is updating outer array and one not.
I've been working on a problem I don't understand why the recursive function step returns None?
here is the code :
import sys
def minIndx(list):
x=10
indx=0
for i in range(len(list)):
if (list[i]<x):
x=list[i]
indx=i
return indx
def steps(arr,sum1,sum2,x):
i = minIndx(arr)
del arr[i]
sum1 = sum(arr)
if (sum1 + 9*x >= sum2):
return x
else: steps(arr,sum1,sum2,x+1)
s=input()
digits1=[]
digits2=[]
for i in range(len(s)):
if (i>2):break
digits1.append(int(s[i]))
for i in range(len(s)):
if (i<3):continue
digits2.append(int(s[i]))
sumLeft = sum(digits1)
sumRight = sum(digits2)
print(steps(digits1,sumLeft,sumRight,1))
for the test case : 123456,
the step function prints None as well as the print function
It could be because you're not returning your recursive call. What is your expected output here? When I return the recursive call to steps I get a value of 2 for an input of 123456.