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.
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
Question: Write a program that reads table with given columns from input stream. Columns are name, amount, debt. Then filter the table (condition: debt is equal to 0). After that increase debt by 42% then print results.
I am a beginner in Python and have tried multiple times but still couldn't fixed the problem. Help will be much appreciated.
Input:
10
Tatiana Santos 411889 36881
Yuvraj Holden 121877 0
Theia Nicholson 783887 591951
Raife Padilla 445511 0
Hamaad Millington 818507 276592
Maksim Whitehead 310884 0
Iosif Portillo 773233 0
Lachlan Daniels 115100 0
Evie-Grace Reese 545083 0
Ashlea Cooper 68771 0
Required Output:
Tatiana Santos 411889 52371.02
Theia Nicholson 783887 840570.42
Hamaad Millington 818507 392760.64
My Solution:
def input_data(n):
tup = []
if n>0:
tup.append(tuple(map(str,input().split(" "))))
input_data(n-1) #I know there's a problem in the recursion. I am not #doing anything with the return value. Please help
return tup
def filtertuple(* tup): # After debugged I got to know at this point only one row is passed to function
newtuple = filter(lambda i: i[2]!=0,tup)
return tuple(newtuple)
def increasedebt(newtuple):
newtuple1 = tuple(map(lambda i:(i[2])*(142/100)),newtuple)
return (newtuple1)
def output_data():
n=int(input())
return n
print(increasedebt(filtertuple(input_data(output_data()))))
Error: Traceback (most recent call last):
File "C:\Users\msi-pc\PycharmProjects\ProgramminglanguageTask3\main.py",
line 28, in <module>
print(increasedebt(filtertuple(input_data(output_data()))))
File "C:\Users\msi-pc\PycharmProjects\ProgramminglanguageTask3\main.py",
line 14, in filtertuple
return tuple(newtuple)
File "C:\Users\msi-pc\PycharmProjects\ProgramminglanguageTask3\main.py",
line 12, in <lambda>
newtuple = filter(lambda i: i[2] != 0, tup)
IndexError: list index out of range
I see two main issues with how your code passes the data from input_data to filtertuple.
The first issue is that your recursion in input_data is messed up, you never do anything with the results of the recursive calls so only the first row of input data gets included in the final return value. Recursion really isn't an ideal approach to this problem, a loop would be a lot simpler and cleaner. But you could make the recursion work, if you do something with the value returned to you, like tup.extend(intput_data(n-1)). If you stick with recursion, you'll also need to make the base case return something appropriate (or add an extra check for None), like an empty list (or tuple).
The second issue is that filtertuple is written to expect many arguments, but you're only passing it one. So tup will always be a 1-tuple containing the actual argument. If you're expecting the one argument to be a list of tuples (or tuple of tuples, I'm not sure exactly what API you're aiming for), you shouldn't use *tup in the argument list, just tup is good without the star. You could call filtertuple(*input_data(...)) which would unpack your tuple of tuples into many arguments, but that would be silly if the function is just going to pack them back up into tup again.
There may be other issues further along in the code, I was only focused on the input_data and filtertuple interactions, since that's what you were asking about.
Here's my take on solving your problem:
def gather_data(num_lines):
if num_lines == 0: # base case
return [] # returns an empty list
data = gather_data(num_lines-1) # recursive case, always gives us a list
row = tuple(map(int, input().split(" "))) # get one new row
data.append(row) # add it to the existing list
return data
def filter_zeros(data): # note, we only expect one argument (a list of tuples)
return list(filter(lambda i: i[1] != 0, data))
def adjust_debt(data): # this only returns a single column, should it return
return list(map(lambda i: (i[1]) * (142 / 100), data)) # the whole table?
# calling code:
num_lines = int(input()) # this code really didn't deserve its own function
data = gather_data(num_lines) # extra variables help debugging
filtered = filter_zeros(data) # but they could be dropped later
adjusted = adjust_debt(filtered)
print(adjusted)
I did find one extra issue, you had the parentheses wrong in the function I renamed to adjust_debt.
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.
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
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 6 years ago.
Improve this question
I am dealing with a large txt file, there are overall 8050000 lines. A short example of the lines are:
usedfor zipper fasten_coat
usedfor zipper fasten_jacket
usedfor zipper fasten_pant
usedfor your_foot walk
atlocation camera cupboard
atlocation camera drawer
atlocation camera house
relatedto more plenty
I write a python code to read the lines, and store them as a dictionary. My code is:
dicCSK = {}
for line in finCSK:
line=line.strip('\n')
try:
r, c1, c2 = line.split(" ")
except ValueError: print line
if c1 not in dicCSK.keys():
dicCSK[c1]= []
str1 = r+" "+c2
dicCSK[c1].append(str1)
However, I ran the program for over 20 hours, it is still running. So is there any better way to store them in a dictionary? My code is too slow. Thanks.
This is a mistake: it generates a list of all keys in the dictionary and then scans over it.
if c1 not in dicCSK.keys():
dicCSK[c1]= []
Instead:
if c1 not in dicCSK:
dicCSK[c1] = []
Or instead, use a defaultdict to avoid the check.
dicCSK = collections.defaultdict(list)
for line in finCSK:
line=line.strip('\n')
try:
r, c1, c2 = line.split(" ")
except ValueError:
print line
dicCSK[c1].append(r+" "+c2)
Also, probably you also want the dicCSK[c1].append(r+" "+c2) statement under an else clause of the try/except otherwise it will execute even when there's a ValueError exception.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
hello i am trying to save the printed results from this while loop and then upload them to a database
i=0
x=0
n=0
while x < len(round1):
n +=1
print 'match number',n, ':' ,round1[x],scoretop[i],'VS','team:', round1[x+1],scorebottom[i],"\n"
x=x+2
i=i+1
i am totally new to python so sorry if this is an easy question
If you're on some UNIX-like system you can run this and redirect the output to a file like this:
python your-file.py > output.txt
Then you can manually upload the output to your database.
If you want to upload the results automatically you should safe the results in a list, instead of printing them, and then upload them through the API of your database. Look at dg123's answer for details on saving you results in a list.
Make a data structure beforehand and append to it while you are in the loop:
results = [] # A list of the results that
# that we will get in the while loop
i=0
x=0
n=0
while x < len(round1):
n +=1
results.append(' '.join(map(str,
['match number',
n,
':' ,
round1[x],
scoretop[i],
'VS','team:',
round1[x+1],scorebottom[i],"\n"])))
x=x+2
i=i+1
The results will then be saved in the results list, which you can then loop over and send to the database:
for i in results:
send_to_database(i)
Or you can concatenate all the strings together and send them that way if you like:
send_to_database('\n'.join(results))
I assume you want to print to file, you can simply write to a file:
with open('log.txt', 'w') as outfile:
while x < len(round1):
# some operations
out = ' '.join(map(str, ['match number', n, ':', round1[x], scoretop[i], 'VS', 'team:', round1[x+1], scorebottom[i], "\n"]))
outfile.write(out)
If you are working on UNIX machines, just follow the suggestion of #Ich Und Nicht Du