I have created files using python, which I need to compare. How can I compare the two files using python?
def td():
choice = input("which trainning event would you like to access?
\n1.swimming
\n2.cycling
\n3.running\nplease type in the number before the event of which you want to choose\n")
if choice == "1":
Swimming_file= open("Swimming_file.txt", "w")
totaldistance = input("what was the total distance you swam in meters?")
totaltime = input("how long did you swim for in minutes?")
speed = totaldistance/totaltime
print ("on average you where running at a speed of", speed, "mps")
total = (totaldistance, totaltime, speed)
Swimming_file.write(str(total))
Swimming_file.close()
elif choice == "3":
Running_file= open("Running_file.txt", "w")
totaldistanceR = int(input("what was the total distance you ran in KM?"))
totaltimeR = int(input("how long did you run for in minutes?"))
totaltimeR1 = 60/totaltimeR
speedR1 = totaldistanceR/totaltimeR1
print ("The records have been saved")
print ("on average you where running at a speed of", speedR1, "KMph")
totalR = (totaldistanceR, totaltimeR, speedR1)
Running_file.write(str(totalR))
Running_file.close()
elif choice == "2":
Cycling_file= open("Cycling_file.txt", "w")
totaldistancec = int(input("what was the total distance you ran in KM?"))
totaltimec = int(input("how long did you run for in minutes?"))
speedc = totaldistancec/totaltimec
print ("on average you where running at a speed of", speedc, "KMph")
totalc = (totaldistancec, totaltimec, speedc)
Cycling_file.write(str(totalc))
Cycling_file.close()
The created files contain running times named after the username. I need to compare files so the user can see how fast other users are.
I have been looking on the internet for this solution but none are relevant to my problem.
I think you first need to update your question. if you would like to compare two files you can do it this way:
from __future__ import with_statement
with open(filename1) as f1:
with open(filename2) as f2:
if f1.read() == f2.read():
...
Or This way
import filecmp
if filecmp.cmp(filename1, filename2, shallow=False):
...
But you do not say what you would like clearly, what exactly are you comparing, are you comparing information inside the files with different username and times? How is the files structured. Do you need to select one user first and then find at what place sorted by time that user is compared to other?
We will help you just as long as you write an excellent description.
EDIT after OP updated post: You still need to give information about your data. and are you sure your code runs like you have written,
speed = totaldistance/totaltime
You should maybe not do math on a string. and you are not saving username in the file, how should you compare data without information about whom has what time in a certain event?
could you maybe write what you are trying to do so we can help you better?
i'm not sure about your question but i think this is your answer:
U1 = open('file1.txt', 'r')
U2 = open('file2.txt', 'r')
username1 = U1.readline()
username2 = U2.readline()
if U1.readline() >= U2.readline():
#do something
else:
#do something else...
Related
I'm a beginner in Python and I'm trying to solve this problem.
I'm trying to write a code where you can put your name and the amount that you want to donate.
The thing is, deppending on the amount of the donation you can have more chances to be the winner.
Eg. If you donate $10 (1 chance), $20(2 chances), $30(3 chances).
My biggest problem is because I can't figure out how to solve this problem when the person insert $30 its name goes to the list 3 times and so on. I tried to use "for..inrange():" but without any sucess. Can someone explain me how to do this?
from random import shuffle
from random import choice
list = []
while True:
name = str(input('Write your name: '))
donation = float(input('Enter the amount you want to donate.: $ '))
list.append(name)
print('You donated $ {}. Thank you {} for you donation!'.format(donation, name))
print('=-'*25)
print('[1] YES')
print('[2] NO')
answer = int(input('Would you like to make another donation? '))
if answer == 1:
continue
else:
shuffle(list)
winner = choice(list)
break
print('The winner was: {}' .format(winner))
First do not use the name of a built-in type as a (meaningless) variable name. Change list to entry_list.
For the particular problem
compute the quantity of chances;
make a list of the person's name that many times;
extend the entry list with that list of repeated name.
Code:
entry_list = []
while ...
...
chances = int(donation) // 10
entry_list.extend( [name] * chances )
An alternative to adding another loop with additional control flow, you can use list.extend() with a list expression:
num_chances = donation // 10
chances = [name] * num_chances
all_chances.extend(chances)
Note that list is a built-in python identifier, and it's not a good idea to overwrite it. I've used all_chances instead.
Rather than adding extra names to the list to represent the higher chance, you could use the donations as weights in the random.choices function:
from random import choices
names, donations = [], []
while True:
names.append(input('Write your name: '))
donations.append(float(input('Enter the amount you want to donate.: $')))
print(f'You donated ${donations[-1]}. Thank you {names[-1]} for your donation!')
print('=-'*25)
print('[1] YES')
print('[2] NO')
if input('Would you like to make another donation? ') != '1':
break
winner = choices(names, donations)[0]
print(f'The winner was: {winner}')
This allows for non-integer donations to be counted fairly -- e.g. if Bob donates $0.25 and Fred donates $0.50, the drawing will still work in a reasonable way. It also allows very large donations to be handled without tanking the performance of the program -- if you have one list entry per dollar donated, what happens if Elon donates $20B and Jeff donates $30B? (The answer is that your fan spins really fast for a while and then the program crashes because you can't create a list with 50 billion elements -- but this is not a problem if you simply have a list of two elements with large int values.)
Note that shuffle is not necessary if you're using random.choices (or random.choice for that matter) because those functions will already make a random selection from the list.
You can use a for loop to append the name to the list more than one time :
for i in range(donation//10):
list.append(name)
This code should do the job. Please follow good naming conventions as pointed out by others. I have changed the list variable to donations as it is forbidden to use keywords as variables.
I have included the name in donations int(name) // 10 times using the extend function as pointed out by others. You may change the number of times as you wish.
from random import shuffle
from random import choice
donations = []
makeDonation = True
winner = "Unknown"
while makeDonation:
name = str(input('Write your name: '))
donation = float(input('Enter the amount you want to donate.: $ '))
donations.extend([name for i in range ( int(donation) // 10)])
print('You donated $ {}. Thank you {} for you donation!'.format(donation, name))
print('=-'*25)
print('[1] YES')
print('[2] NO')
answer = int(input('Would you like to make another donation? '))
if answer == 2:
makeDonation = False
shuffle(donations)
winner = choice(donations)
print('The winner was: {}' .format(winner))
This thing is hard to post code and context inside of.
#This is a menu driven multiplication game. i am attemtping to save the high
#score in a file named multiplication_game.txt...
def single_player():
in_file = open('multiplication_game.txt', 'r')
highest_times_selection = int(in_file.readline())
print('\n____now lets see how u do on the times tables____')
correct = 0
missed = 0
times_selection = int(input(
'\nPlease enter a times time table integer to practice: '))
#This simple generates the multiplation questions and checks for right or
#wrong.
for number in range(0,11):
print(times_selection, 'x' , number, '=')
user_answer=int(input('answer: '))
correct_answer = times_selection * number
if user_answer == correct_answer:
correct+=1
else:
missed+=1
#This is where if its a perfect score and a high times table than the
#previous saved score it should be opened and the new score saved in the
#text document.
if missed == 0 and times_selection > highest_times_selection :
output_file = open('multiplication_game.txt', 'w')
name = input('You have the highest Score!!\n enter your name: ')
output_file.write(str(times_selection)+ '\n')
output_file.write(name + '\n')
else:
print('you missed ', missed, 'and got', correct,'correct\n')
output_file.close()
Try to define output_file = None before any assignment of it.
Tip: before your last if-else condition.
This looks like homework, so I don't want to give you the answer but rather lead you to it.
Take a look at your if/else for your high score table, and walk through your code twice, taking a different branch (different part of the if/else) each time you reach this spot. Write down the variable names on paper as you define them, starting over with a new sheet of paper each time you walk through. If you access a variable, check it off on your list. If you try to access a variable that's not on your list, it's the same as python saying local variable referenced before assignment -- you're trying to access it before you've defined it.
Hope this helps, both in figuring out your problem and learning how to debug in the future.
So I am making a simple randomized number game, and I want to save the players High Score even after the program is shut down and ran again. I want the computer to be able to ask the player their name, search through the database of names in a text file, and pull up their high score. Then if their name is not there, create a name in the database. I am unsure on how to do that. I am a noob programmer and this is my second program. Any help would be appreciated.
Here is the Code for the random number game:
import random
import time
def getscore():
score = 0
return score
print(score)
def main(score):
number = random.randrange(1,5+1)
print("Your score is %s") %(score)
print("Please enter a number between 1 and 5")
user_number = int(raw_input(""))
if user_number == number:
print("Congrats!")
time.sleep(1)
print("Your number was %d, the computers number was also %d!") %(user_number,number)
score = score + 10
main(score)
elif user_number != number:
print("Sorry")
time.sleep(1)
print("Your number was %d, but the computers was %d.") %(user_number, number)
time.sleep(2)
print("Your total score was %d") %(score)
time.sleep(2)
getscore()
score = getscore()
main(score)
main(score)
EDIT:
I am trying this and it seems to be working, except, when I try to replace the string with a variable, it gives an error:
def writehs():
name = raw_input("Please enter your name")
a = open('scores.txt', 'w')
a.write(name: 05)
a.close()
def readhs():
f = open("test.txt", "r")
writehs()
readhs()
with open('out.txt', 'w') as output:
output.write(getscore())
Using with like this is the preferred way to work with files because it automatically handles file closure, even through exceptions.
Also, remember to fix your getscore() method so it doesn't always return 0. If you want it to print the score as well, put the print statement before the return.
In order to write a file using python do the following:
file2write=open("filename",'w')
file2write.write("here goes the data")
file2write.close()
If you want to read or append the file just change 'w' for 'r' or 'a' respectively
First of all you should ask your question clearly enough for others to understand.To add a text into text file you could always use the open built-in function.Do it like this.
>>> a = open('test.txt', 'w')
>>> a.write('theunixdisaster\t 05')
>>> a.close()
Thats all.If need further help try this website.
http://www.afterhoursprogramming.com/tutorial/Python/Writing-to-Files/
You could also use a for loop for the game to print all the scores.
Try this one on your own.It would rather be fun.
THE RECOMENDED WAY
Well as if the recommended way use it like this:
>>> with open('test.txt', 'w') as a:
a.write('theunixdisaster\t 05')
With this its certain that the file would close.
With variables
>>> name = sempron
>>> with open('test.txt', 'w') as a:
a.write('%s: 05' % name)
Now try calling it.Well I use python 3.4.2.So, if you get into errors, try to check if there is any difference in the string formatting with the python version that you use.
I'm looking to create a Python based vocabulary checker for my little cousin to use for studying. The purpose of the program will be to display a word and then she will need to type in the definition and have it checked. I was wondering if the best way to do this is with array lists:
vocab = ['Python','OSX']
definition = ['programming language','operating system']
Is this the best way to go about this? And if so how do I have the program randomly display a vocab and then check the definition. Any help would be greatly appreciated. Thank you guys.
Ok. So this is what I have so far....
#Russian Translation Program
import os
import random
#Asks users if they want to add more vocabulary
word_adder=raw_input("Add more words? If yes, press 1: ")
with open("Russian_study.txt","a") as f:
while word_adder=="1":
word=raw_input("Enter word: ")
translation=raw_input("Word translation: ")
f.write("'{0}':{1},".format(word,translation))
word_adder=raw_input("Add another word? If yes, press 1: ")
#Checks to see if file exists, if not one is created
with open("Russian_study.txt","a") as f:
pass
os.system('clear')
print("Begin Quiz")
#Begin testing user
with open("Russian_study.txt","r") as f:
from random import choice
question = choice(list(f))
result = raw_input('{0} is '.format(question))
print('Correct' if result==f[question] else ':(')
However, my output is
Begin Quiz
'Один':'One', is
How do I make it only display Один and check the user input against one?
use a dictionary:
d={'Python':'programming language', 'OSX':'operating system'}
from random import choice
q = choice(list(d))
res = input('{0} is:'.format(q))
print('yay!' if res == d[q] else ':(')
[if you are using python < 3.0, use raw_input() instead of input()]
the simplest (and not safe!) way to write/read from a file:
with open('questions.txt', 'w') as f:
f.write(repr(d))
'questions.txt' will have this line:
`{'Python':'programming language', 'OSX':'operating system'}`
so for reading it you can do
with open('questions.txt') as f:
q=eval(f.read())
and now q and d are equal. don't use this method for "real" code, as 'questions.txt' may contain malicious code.
1) You can use random.choice() to randomly pick an element from your vocab list (or the keys() of a dictionary).
2) Deciding when an answer is close enough to the definition is trickier. You could simply search the answer string for certain key words. Or if you want to get more complex, you can calculate something like the Levenshtein distance between two strings. You can read about the L distance here: http://en.wikipedia.org/wiki/Levenshtein%5Fdistance. And there are python recipes online for calculating the L distance.
I am very new to python, and I am hoping I didnt miss a fix for this somewhere else. I have a simple program that was one of the practice excercises in a book I purchased and I am running into an issue. I have a program that opens a file and writes it to a list. Then a user can update the list with input, and when a user exits it updates the list with the latest content. Everything works fine except the sort option. It shows the scores from the file with a single quote infront of them, and the scores updated while the program was running without. It also doesn't sort them at all. I have tried many different way to do this without fail. I am sure this is not that important in the long run, but I wanted to figure it out.
Here is the code
# High Scores
# Demonstrates list methods
scores = []
try:
text_file = open("scores.txt", "r")
for line in text_file:
scores.append(line.rstrip("\n"))
text_file.close()
except:
raw_input("Please verify that scores.txt is placed in the correct location and run again")
choice = None
while choice != "0":
print \
"""
High Scores Keeper
0 - Exit
1 - Show Scores
2 - Add a Score
3 - Delete a Score
4 - Sort Scores
"""
choice = raw_input("Choice: ")
print
# exit
if choice == "0":
try:
output_file = open("scores.txt" , "w")
for i in scores:
output_file.write(str(i))
output_file.write("\n")
output_file.close()
print "Good-bye"
except:
print "Good-bye.error"
# list high-score table
elif choice == "1":
print "High Scores"
for score in scores:
print score
# add a score
elif choice == "2":
score = int(raw_input("What score did you get?: "))
scores.append(score)
# delete a score
elif choice == "3":
score = int(raw_input("Delete which score?: "))
if score in scores:
scores.remove(score)
else:
print score, "isn't in the high scores list."
# sort scores
elif choice == "4":
scores.sort()
scores.reverse()
print scores
# some unknown choice
else:
print "Sorry, but", choice, "isn't a valid choice."
raw_input("\n\nPress the enter key to exit.")
When you add scores from the file, you're adding them as strings: scores.append(line.rstrip("\n")). But when you add scores during the program, you're adding them as integers: int(raw_input("What score did you get?: ")).
When Python sorts a list containing both strings and integers, it'll sort the strings according to character order (so '1' < '12' < '3'), and sort the integers separately, putting the integers before the strings:
>>> sorted([1, 8, '11', '3', '8'])
[1, 8, '11', '3', '8']
Presumably it's printing out a single quote after the characters as well as before, as it does here (indicating that it's a string).
So, when you're reading the file at the start, turn them into an integer just like you do when you read user input.
Some other tips:
scores.sort(reverse=True) will sort in reverse order without having to go through the list twice.
It's generally a bad idea to do except:: that'll catch absolutely any problem with the program, including the user hitting ^C to try to quit, the system running out of memory, etc. You should do except Exception: as a catch-all to get exceptions that it's possible to recover from but not those kinds of system errors, or a more specific exception when you want to handle only certain types.
If in your text file you have only one score per line, the best way is to change the scores into integers while taking inputs like this.
scores = []
try:
text_file = open("scores.txt", "r")
for line in text_file:
scores.append(int(line.strip()))
except:
text_file.close()
Actually the way you are taking inputs is leaving some of your numbers as strings. The best way to deal with these types of problems is to print the array before sorting and look into it. All the best.