Python eval() and exec() [closed] - python

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
Is there a way I can use Python eval() and/or exec() to maintain state between program runs without writing data to a file or database.
Here's the question more specifically. I want to write a program that prints out a number and then keeps adding 1 to itself every time it's run again without persisting any variable in a file or database.
I got asked this question in a recent interview.
Any help appreciated.

Disclaimer: I do not recommend doing this. 99.999% of the time, it's better to store serializable information in its own file.
If by "without writing data to a file", you mean "without writing data to its own file",
you can open the Python file that is running and rewrite the data in-place:
import re
x = 0
print "The value of the variable x is: {}".format(x)
with open("test.py") as file:
data = file.read()
data = re.sub(r"x = (\d+)", "x = {}".format(x+1), data)
with open("test.py", "w") as file:
file.write(data)
Now the value will change with each subsequent execution.
C:\Users\Kevin\Desktop>test.py
The value of the variable x is: 0
C:\Users\Kevin\Desktop>test.py
The value of the variable x is: 1
C:\Users\Kevin\Desktop>test.py
The value of the variable x is: 2
C:\Users\Kevin\Desktop>test.py
The value of the variable x is: 3
C:\Users\Kevin\Desktop>test.py
The value of the variable x is: 4
But again, it's preferable to just keep the data in a separate file, using for example shelve:
import shelve
d = shelve.open("data.dat")
if "x" not in d:
d["x"] = 0
print "The value of x is: {}".format(d["x"])
d["x"] += 1
Or perhaps json if you value human-readability:
import json
try:
with open("data.dat") as file:
d = json.load(file)
except IOError: #first execution. file doesn't exist yet.
d = {"x":0}
print "The value of x is: {}".format(d["x"])
d["x"] += 1
with open("data.dat", "w") as file:
json.dump(d, file)
Or even a full-fledged database if you've got a lot of data.

This should ideally be code-golf, but it was fun!
Here is a solution using exec and eval as you requested.
The code is 15 lines long, on each run an additional line (z=1) is added to the .py file
and what is printed is number of lines in file now - 15, thus printing increments on each run
initial_num_lines = 15
def get_lines_in_file():
f = open('evalexec.py', 'r')
num_lines = len(f.readlines())
return num_lines
lines = str(get_lines_in_file() - initial_num_lines)
print eval(lines+'+1')
exec_code = '''
f = open('evalexec.py', 'a')
f.write("\\nz=1")
f.close()
'''
exec(exec_code)
OUTPUT:
>python evalexec.py
0
>python evalexec.py
1
>python evalexec.py
2
>python evalexec.py
3

You can use the file stats to keep track of the last modified value (which is an integer), and update it each run using os.utime:
import os
last_modified = os.stats(__file__).st_mtime
print(int(last_modified))
os.utime(__file__, (last_modified, last_modified + 1))
Consecutive runs:
Petes-Mac:~ petewood$ python inc.py
1486149574
Petes-Mac:~ petewood$ python inc.py
1486149575
Petes-Mac:~ petewood$ python inc.py
1486149576

Related

How can I make a multiplayer variable, so when someone adds one everyone's screen shows the variable (+1)?

I am trying to make a project that requires a multiplayer variable. For example, if I made a variable called "x" and someone said x += 1 then everyone's x would be one more. Could someone please tell me if there is some kind of module that can do this, or if it is impossible?
Thank you
well you can use a class like so...
class Myclass:
x = 0
now when you do Myclass.x + 1
Myclass.x will equal 1 for everyone that uses Myclass.x.
You could also use global variable.
Also what do you mean by everyone. Are they all going to be having their own process of the application running? You could just do math on variables in a shared .txt document or something like...
to read x you could do ...
mytext.txt
x=100
code.py
def readx():
with open('mytext.txt', 'r') as fp:
data = fp.readlines()
x = 0
for line in data:
if line.startswith('x'):
value = line.split('=')[1] # [0] = x [1] = 100
x = int(value)
print(x) # 100
and to change x you can do ...
code.py
def writex(value):
with open('mytext.txt', 'w') as fp:
fp.write(f'x={value}')
so you can have something like...
input = int('Type here: ') # output: Type here:
Friends console
output: Type here: x += 1
you just write the input into the text file
writex(input)
and x+=1 value gets written to first like of the text.txt file etc.
or you could use sockets and so on.
You could also use global variable.

Python sort by objects [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
How can I sort by name and age in PYTHON?
I have the following list in .txt file:
John, 14
Mike, 18
Marco, 25
Michael, 33
I want to sort this by name and by age. I wrote this code but it doesn't work:
file = open("people.txt", "r")
data = file.readlines()
i = 0
for line in data:
name, age = line.split(',')
list = [name, age]
i += 1
print("For sorting by name press (1);")
print("For sorting by age press (2);")
z = eval(input())
if z == 1:
list.sort(key=lambda x: x.name, reverse=True)
print([item.name for item in list])
Thank you very much guys :)
Here's one approach:
with open("so.txt", "r") as f:
lines = [line.split(',') for line in f]
print("For sorting by name press (1);")
print("For sorting by age press (2);")
z = int(input())
if z == 1:
lines.sort(key=lambda x: x[0], reverse=True)
print([item[0] for item in lines])
Using:
a context manager to handle automatic file closure (this is the with)
the for line in f iterator to loop over the file's lines one at a time
a list comprehension to split the lines into lists as needed
int instead of eval
changing all line.name references to line[0] -- you could make the lines proper classes (or namedtuples if you wanted the .name access.
Though, in general, solutions for parsing csv files exist (e.g. csv -- there were a few more issues in your code than just that.

How to change the numerical value of a variable after it has already been defined? [duplicate]

This question already has answers here:
Keeping the data of a variable between runs of code
(3 answers)
Closed 4 years ago.
How do you change the value of a variable after it has already been defined, and then next time you run the program, have the variable changed to the new value.
p = 0
result = int(input("Test "))
if result == 3:
points = p+3
p = points
Basically, I need it so that next time I run this code, "p" has been set to 3, and then the time after that, it changes to 6, as so on.
import os
with open('tmp.txt', 'r') as file:
p = file.read()
os.remove("tmp.txt")
result = int(input("Test "))
if result == 3:
points = int(p)+3
p = points
with open('tmp.txt', 'w') as file:
file.write(str(p))
Try this out. Create a file "tmp.txt" in the same folder as your code before running the script.

struggling with python homework [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I got a .txt file with some lines in it:
325255, Jan Jansen
334343, Erik Materus
235434, Ali Ahson
645345, Eva Versteeg
534545, Jan de Wilde
345355, Henk de Vries
Write a program that starts with opening the file kaartnummers.txt
Determine the number of lines and the largest card number in the file. Then print these data.
my code isnt finished yet but i tried atleast!:
def kaartinfo():
lst = []
infile = open('kaartnummers.txt', 'r')
content = infile.readlines()
print(len(content))
for i in content:
print(i.split())
kaartinfo()
I know that my program opens the file and counts the number of lines in it.. all after that is wrong <3
I can't figure out how to get the max number in the list.. Please if you got an answer use simple readable Python Language.
I'm not good at python, and there are probably much more elegant solutions, but this is how I would do it. Some may say this is like C++/Java in python, which many tend to avoid.
def kaartinfo():
lst = []
infile = open('kaartnummers.txt', 'r')
content = infile.readlines()
for i in content:
value = i.split(',')
value[0] = int(value[0])
lst.append(value)
return lst
Use the kaartinfo() function to retrieve a list
my_list = kaartinfo()
Assume first value is the maximum
maximumValue = my_list[0][0]
Go through every value in the list, check if they are greater than the current maximum
# if they are, set them as the new current maximum
for ele in my_list:
if ele[0] > maximumValue:
maximumValue = ele[0]
when the above loop finishes, maximum value will be the largest value in the list.
#Convert the integer back to a string, and print the result
print(str(maximumValue) + ' is the maximum value in the file!')
This should be enough to do the job:
with open('kaartnummers.txt', 'r') as f:
data = f.readlines()
print('There are %d lines in the file.' % len(data))
print('Max value is %s.' % max(line.split(',')[0] for line in data))
Given the input file you provided, the output would be:
There are 6 lines in the file.
Max value is 645345.
Of course, you can put it in a function if you like.

Code trouble with python

I'm having some trouble here. For my CS assignment, I have to have python take data from a file on my pc and run the data through my program.
So, this code works fine on http://repl.it/languages/Python, but not in python. I'm assuming because my line of code has some Python 2.0 lines of code? I can't seem to fix it. Can you guys help? And, another small question except this one. I have to input some code in my program to take data from a file and run it through my program as I stated above. I have this.
import math
def mean(values):
average = sum(values)*1.0/len(values)
return average
def deviation(values):
length = len(values)
m = mean(values)
total_sum = 0
for i in range(length):
total_sum += (values[i]-m)**2
root = total_sum*1.0/length
return math.sqrt(root)
def median(values):
if len(values)%2 != 0:
return sorted(values)[len(values)/2]
else:
midavg = (sorted(values)[len(values)/2] + sorted(values)[len(values)/2-1])/2.0
return midavg
def main():
x = [15, 17, 40, 16, 9]
print mean(x)
print deviation(x)
print median(x)
main()
How do I specifically have the program take data from the file and run it through my program? The data is just a bunch of numbers, by the way. It's been giving me trouble for some hours now. Thanks if you can help out.
This is what I know about the opening/closing file stuff so far
f = open("filename.txt")
data = f.readlines()
f.close()
Apparently you are using python2.x:
I'm assuming because my line of code has some Python 2.0 lines of code?
So yes, you do have a problem: In python3.x, print became a function.
Thus, your prints need to be changed:
print mean(x)
print deviation(x)
print median(x)
Becomes
print(mean(x))
print(deviation(x))
print(median(x))
Also, your part about opening and closing files is unclear.

Categories

Resources