'enumerate' function breaks loop? python3 - loops

def main():
x = open("textfile.txt", "r")
#o = enumerate(x.readlines())
for i in x:
print(i, end="")
x.close
if __name__ == "__main__": main()
If I uncomment the 'o' object this script will not run.
Could someone please tell me why that is?
:python3.3

you mean you don't get output, right?
that's because x.readlines() isn't a generator - it actually reads all the data out of x. and then gives that to o, wrapped with an enumerator.
so when you do
for i in x:
there's no more data to be read - nothing to do.
you could do:
for i,text in o:
print '%d: %s'%(i, text)
and that would work...

Related

How to use a While Loop to repeat the code based on the input variable

i'm having a rough time trying to do a loop with the while function.
Basicly i want the code to show me all prime numbers from 0 to the number i wrote in input.
Then, to ask a question if i want to do it one more time (if yes to repeat the code from the start) or if not to exit.
How i got it now is just to repeat the last results infinitely.
All results i found online with the while loop don't really explain how to repeat a certain part of the code.
I'm by no means even a little bit educated when it comes to this stuff so if its a stupid question, please forgive me.
# Python program to print all primes smaller than or equal to
# n using Sieve of Eratosthenes
def start(welcome):
print ("welcome to my calculation.")
value = input("number?:\n")
print(f'you have chosen: {value}')
value = int(value)
def SieveOfEratosthenes(n):
prime = [True for i in range(n + 1)]
p = 2
while (p * p <= n):
if (prime[p] == True):
for i in range(p ** 2, n + 1, p):
prime[i] = False
p += 1
prime[0] = False
prime[1] = False
print("Primary numbers are:")
for p in range(n + 1):
if prime[p]: print(p)
# driver program
if __name__ == '__main__':
n = value
SieveOfEratosthenes(n)
pitanje = input("do you want to continue(yes/no)?")
while pitanje == ("yes"):
start: SieveOfEratosthenes(n)
print("continuing")
if pitanje == ("no"):
print("goodbye")
strong text
Firstly you should remove
value = input("number?:\n")
print(f'you have chosen: {value}')
value = int(value)
from the top of your code, everything must be inside your __main__ program.
Basically what you need to do is create a main While loop where your program is gonna run, it will keeps looping until the response is not "yes".
For each iteration, you ask a new number at the beggining and if it has to keep looping at the end.
Something like this:
# driver program
if __name__ == '__main__':
# starts as "yes" for first iteration
pitanje = "yes"
while pitanje == "yes":
# asks number
value = input("number?:\n")
print(f'you have chosen: {value}')
value = int(value)
# show results
start: SieveOfEratosthenes(value)
# asks for restart
pitanje = input("do you want to continue(yes/no)?")
#if it's in here the response wasn't "yes"
print("goodbye")

How can I fix this Array?

#!/bin/python3
b = []
def rotate(d,a):
if d == 0:
return a
b = []
for i in range(len(a)):
b.insert(i-1,a[i])
a = b
rotate(d-1,b)
if __name__ == '__main__':
d = 4
a = ['1','2','3','4','5']
print(rotate(d,a))
I don't know why but when i return 'a' it it prints none. Can anyone help me with this
your issue is the missing return statement when rotate is called recursively:
def rotate(d,a):
if d == 0:
return a
#....
rotate(d-1,b) # <---- here
if you call rotate(d, a) with d > 0, you enter the recursion rotate(d-1,b)...but you throw away the result and python instead returns None. this is because in python any method call that doesn't explicitly return a value, always returns None...and your initial call to rotate(d, a) with d > 0 never passed by a return statement (only the recursive call with d = 0 does, but you throw away that result)...so it returns None.
this should fix your problem:
def rotate(d,a):
if d == 0:
return a
#....
return rotate(d-1,b) # propagate the calculated value back up
see also: Why does my recursive function return None?

When to use `each` and when to use the `for` loop in Groovy

When do we use the each closure and when do we use the for loop in Groovy. Both effectively do the same thing.
groovy:000> a = [1, 2, 3, 4]
===> [1, 2, 3, 4]
groovy:000> a.each {
groovy:001> println it
groovy:002> }
1
2
3
4
===> [1, 2, 3, 4]
groovy:000> for (it in a) {
groovy:001> println it
groovy:002> }
1
2
3
4
===> null
The each closure returns the list. So I can probably use it instead of the for loop but not vice versa, correct?
The for loop is probably somewhat faster and more memory efficient, since the each construct is syntactic sugar. But I can't imagine a situation where it would really make a difference.
By my lights, the only significant difference is you can't terminate an each closure without throwing an exception. You can terminate a for loop with a break.
I do think the each construct reads a bit more idiomatic.
for loop is faster as You can in this question and this answer, but remember that premature optimization is the root of all evil in programming so I can't find any scenario that it really makes difference.
each also returns the whole, unmodified collection that it was operating on and here is a particular scenario that OP found it useful. for construct doesn't return anything.
It is generally Groovier to prefer each, because changing the code will be easier in the future. The each method is related to a family of functional methods that are ubiquitous in Groovy; by contrast, the for loop is mired in the imperative style of Java.
As a starting example, imagine that we want foo to call bar for each item:
def bar = { println it }
def foo = { def a ->
a.each { bar it }
}
foo( [1,2,3,4] )
Now, what if we want to call bar only for even numbers:
def bar = { println it }
def foo = { def a ->
a.findAll{ (it % 2) == 0 }.each{ bar it }
}
foo( [1,2,3,4] )
What if we discover that bar needs the list index of the item?
def bar = { def item, def index -> println "${index} ${item}" }
def foo = { def a ->
a.eachWithIndex{ def x, def i -> bar x, i }
}
foo( [1,2,3,4] )
Try writing these examples with the for loop. Sure, it can be done, but the changes seem inelegant. (Note, as mentioned in comments, you'll want to learn collect and other methods. For vs each is somewhat a false dichotomy.)

Inline Python "for" to read lines from file and append to list

I have this code:
self.y_file = with open("y_file.txt", "r") as g: y_data.append(line for line in g.readlines())
But it doesn't seem to work and I am more than sure the problem lies within 1) How I open the file (with) and that for loop. Any way I could make this work?
you can just open and read. If you want auto-close you need to wrap it in function
self.y_file = open('y_file.txt').readlines()
Or:
def read_file(fname):
with open(fname) as f:
return f.readlines()
self.y_file = read_file('y_file.txt')

How to execute octave code line-by-line

If I start an octave interactive shell, I can type:
octave:1> function y = foo(x)
> y = x + 2;
> endfunction
octave:2> foo(7)
ans = 9
The interpreter knows to wait for the rest of the function definition.
However, if I do
octave:1> eval("function y = foo(x)");
octave:2> eval("y = x + 2;");
octave:3> eval("endfunction");
it evaluates each line as if it were alone. So it defines a function foo which does nothing, and gives errors for the second two lines.
Is there any way to get eval to operate the same as the interpreter? Ultimately, I would like to create an octave script which executes another script, but is able to do other things in between. Is there any way to tell eval to wait for the rest of the command (the way the interactive environment does)? Alternatively, is there a way to feed commands to the interactive interpreter programmatically?
Thank you.
To answer your exact question, I see two immediate ways to do it:
octave> eval ("function y = foo(x) ...
y = x + 2; ...
endfunction")
octave> eval ("function y = foo(x)\n y = x + 2;\n endfunction")
The thing is that you can't split each line in multiple evals, it doesn't make sense. You want to pass a single string with all of the code. Also, you can use the source function to execute code from other files.
Without knowing all the details of what're you're trying to do, I'm guessing you could have your code use input to wait for input from the other code. Or just turn your other script into functions, and call them from your main script.

Resources