why won't this python program start? - python

I copied the source code of a python program written by someone else on a tutorial forum and I have made a few modifications to it to match my own needs
the original was meant to run in the python shell i believe and i got it to run in the shell but I need to save it to python IDLE and run it from there
I am using python 3.2.3 IDLE btw
this is what I have written:
def fibonacci(previous=0,current=1):
n = int(input("Calculate fibonacci sequence value up to: "))
if previous > current:
previous,current = current, previous
yield previous
yield current
while True:
current,previous = previous+current,current
yield current
x = fibonacci()
for i in range(n):
print(next(x))
fibonacci()
it doesn't run, like no errors pop up i just get the arrows: >>
that's it nothing happens.

The program does start and runs through. Unfortunately, by using yield in the function, you make it a generator, and the generator gets only constructed in the last line, but never evaluated.
Instead, you want to outdent the last four lines:
def fibonacci(previous=0,current=1):
if previous > current:
previous,current = current, previous
yield previous
yield current
while True:
current,previous = previous+current,current
yield current
n = int(input("Calculate fibonacci sequence value up to: "))
x = fibonacci()
for i in range(n):
print(next(x))

Related

Omit in for loop in Python

I have a function to move between the given range of values, but I would like to add in my function a parameter that will be an array which would contain the numbers which must be skipped while my function run iteration
my function:
nums = []
def loopIteration(minValue, maxValue):
minValue += 1
for i in range(maxValue-minValue+1):
num = i+minValue
nums.append(Num('numbers_{}'.format(i)))
#function call
loopIteration(4,25)
i want to add in my function call an parameter like this:
loopIteration(4,25,[8,9,16])
thanks for any answers :)
You can use continue to skip certain is:
def loopIteration(minValue, maxValue, skip=set()):
for i in range(minValue + 1, maxValue + 1):
if i in skip:
continue
cells.append(Cell("numbers_{}".format(i)))
Continue is a Python syntax which would allow you to pass iteration in a for loop. Usually, continue can make it quite hard to follow flow later on, if you ever wish to look back on your script. Here is what you could do:
def loopInteration(minValue, maxValue, skipNums):
for number in range(maxValue-minValue+1):
if number in skipNums:
continue
num = i+minValue
nums.append(Num("numbers_{}".format(i)))
loopIteration(4,25,[NUMBERS HERE])

Python recursive return using dict.get

I'm writting a code for rock scissor paper game. But when I run it, it falls into infinite loop.
The problem happened in following code. Why this code result in infinite loop for any input value?
(my python version is 3.5.0)
class Peoples(object):
def recept(self):
u = input('choose..r or s or p: ')
print('choice: ',{'r':'rock','s':'scissor','p':'p'}.get(u,'{} (wrong input)'.format(u)))
return {'s':0,'r':1,'p':2}.get(u,self.recept())
P=Peoples()
P.recept()
Because the second argument of get gets executed regardless of whether it will ultimately be used by get. You ought to break it up into multiple lines so it only recursively calls when necessary:
d = {'s':0,'r':1,'p':2}
if u in d:
return d[u]
else:
return self.recept()
But really, it would be preferable to not use recursion at all, since you'll hit the maximum recursion depth and crash after the user chooses an invalid input enough times in a row.
def recept(self):
d = {'s':0,'r':1,'p':2}
while True:
u = input('choose..r or s or p: ')
print('choice: ',{'r':'rock','s':'scissor','p':'p'}.get(u,'{} (wrong input)'.format(u)))
if u in d:
return d[u]

Issue with calling a function inside a while loop

I don't know if this is a simple question or not, but I couldn't find anything on it so I figured I would ask it.
I try to call a function in a while loop but it keeps on returning the same result until the condition is completed. The function main() is imported from another file and return a list with two elements [a,b].
Those two elements are generated randomly, therefor they should change after every step. The function works perfectly fine if I call it on its own.
Here is my code so far, I hope someone can help me:
I thought there was something wrong with my list x so I tried to delete it after every step, but it doesn't change anything.
from some_module import main
def loop(variable):
i = 0
while i <= 5 :
x = main(variable)
a ,b = x[0], x[1]
print a, b
del x[:]
i += 1
The code for main() is :
def main(file):
iniciate(file)
obtain_neighbours(initial_solution())
get_all_costs(get_all_solutions())
return get_best_solution()
And the random choice appears in the function initial_solution() :
#those list are being updated at every step
So = []
I_assign = []
I_available = ['1','2','3','4',...,'n']
def initial_solution():
while len(I_available) != 0:
update_I_assign()
random_task = random.choice(I_assign)
So.append(random_task)
I_available.remove(random_task)
return So
def get_best_solution():
if min(i for i in all_cost) < calculate_cost(fill_station(So)):
best_solution = solutions[all_cost.index(min(i for i in all_cost))]
return [min(i for i in all_cost),best_solution]
else:
best_solution = fill_station(So)
return [calculate_cost(fill_station(So)),best_solution]
It's pretty hard for me to show the rest of the code here because it's quite long. Hope the update helps you understand.

How to run and check this code? (Python basics)

Basically, my question is about how to run this code? Finding the second smallest number from the given list using divide-and-conquer. I tried with print..But it gives me nothing. Just wanna see how this code works. Sorry for simple question, totally New in Python.
Well, just use a function call to run it, and a print to print it:
def two_min(arr):
n = len(arr)
if n==2: # Oops, we don't consider this as comparison, right?
if arr[0]<arr[1]: # Line 1
return (arr[0], arr[1])
else:
return (arr[1], arr[0])
(least_left, sec_least_left) = two_min(arr[0:n/2])
(least_right, sec_least_right) = two_min(arr[n/2:])
if least_left < least_right: # Line 2
least = least_left
if least_right < sec_least_left: # Line 3
return (least, least_right)
else:
return (least, sec_least_left)
else:
least = least_right
if least_left < sec_least_right: # Line 4
return (least, least_left)
else:
return (least, sec_least_right)
print two_main([12,2])
If you'd like to know how this works, you can take a look at the online python visualizer. Link.

How do I keep a list of numbers I have already enountered?

I am currently working on a BASIC simulator in Python, as the title suggests. Here is my code for this problem:
def getBASIC():
l = []
x = 1
while x == 1:
i = input()
l.append(i)
if len(i.split()) != 3:
x = 0
return l
def findLine(prog, target):
for l in range(0, len(prog)):
progX = prog[l].split()
if progX[0] == target:
return l
def execute(prog):
location = 0
visited = [False] * len(prog)
while True:
T = prog[location].split()[2]
location = findLine(prog, T)
visited[location] = True
if visited[len(visited)-1] == False:
return "infinite loop"
else:
return "success"
The first function does what it is intended to do -- convert input of BASIC code into a list. The second function, findLine also does what it is intended to do, in that it finds the item which contains the string equal to the input. The last function, however, I cannot get to work. I know what I have to do, and that is to check whether or not a part of it has been visited twice. I cannot figure out how to do this, due to the existence of the while loop. As a result of this, the second half of that function is just placeholder. If you could help me figure out how to solve this, it would be greatly appreciated. Thanks.
You keep a list of places that have been visited (you already do this) and then when you encounter a goto, you check if it does to a line that already have been visited, and if it has been visited, you exit.
One mistake right now is that you make a list that is as long as the program is. That's pretty pointless. Just keep a list of the visited line numbers instead, and check with
if current_line in visited:
Try adding an if statement declaring a line in the visited list to be true when it is encountered in the loop. This is my solution:
def execute(prog):
location = 0
visited=[False]*len(prog)
while True:
if location==len(prog)-1:
return "success"
if visited[location]==True:
return "infinite loop"
if visited[location]==False:
visited[location]=True
line2strings=prog[location].split()
T=line2strings[-1]
location=findLine(prog, T)

Categories