In what format does this variable need to be? - python

This is one of the programs I need to make on finals. The assignment is to write a name of racer and his three throws after that. For example: Adam 150 60 70. Then i need to find his max and min throw. I also need to write this data in txt file. I stripped this var of all text, only numbers remained. But I have problem with basic math functions. It takes e.g. number 150 as separate digits 1 5 0. I assume I have this variable in wrong format. I tried to convert it to almost everything, but nothing worked. I know this is silly problem, but if you know how to fix or rewrite this program I would appreciate it.
from fileinput import close
from string import ascii_letters
alp = ascii_letters
n = int(input('Number of racers: '))
subor = open('hod_ostepom_tx.txt','r+')
with open('hod_ostepom_tx.txt','r+') as f:
f.truncate(0)
for i in range (n):
name = input('Name of racer and his three throws: ')
subor.write(name + '\n')
for ele in alp:
name = name.replace(ele,'')
name = name.replace(' ','')
print('Maximum is: ',max(name))
print('Minimum is: ',min(name))
subor = close()
Name of racer and his three throws: Adam 150 60 70
Maximum is: 7
Minimum is: 0
In this case I would expect outcome of Maximum is : 150 Minimum is : 60

You can use a useful function str.split() to split the string by spaces, thus by doing this:
user_input = input('Name of racer and his three throws: ').split()
user_input will be ['Adam', '150', '60', '70']. You'll only need to get the name and convert string numbers to integer numbers. To remove first element form a list you can use .pop() function:
name = user_input.pop(0)
Now there's no 'Adam' in the list, only throws. To convert the ist of string to a list of numbers, you can use functional style:
throws = list(map(int, user_input))

name is a string. After you apply your replacements, name is still a string which contains only numbers. For your example name = "1506070". When you call max and min on a string it returns the character with the highest and lowest character code, 7 and 0 respectively. You can achieve what you want using the split function on the string. name_list = name.split(" ") will give a list name_list = ["Adam", "150", "60", "70"]. You can then use a list comprehension to convert the strings to integers:
name_list = name_list[1:] # Includes items at index 1 and after to get rid of name
name_list = [int(x) for x in name_list]
Then you can do max(name_list) or min(name_list) as the elements are integers and should give you what you want.

Related

Turn each word into a variable with python

I have a text which I need to delete the first two words and store the numbers into a variable.
I am trying to split the words and then create a loop to store each word in a variable.
My text is: "ABA BLLO 70000000 12-2022"
So I am trying to store the numbers, which can alternate depending on the data set and create a variable for each of them.
text = "ABA BLLO 70000000 12-2022"
a = text.strip().strip("")
for a in text:
print(a)
So I would have three variables:
number = 70000000
month = 12
year = 2022
You can use the split function to split the string on white-spaces and convert all the splitted strings into a list. Then you can slice the array to remove the first two elements and destructure the remaining array into variables.
text = "ABA BLLO 70000000 12-2022"
x,y = text.split()[2:]
print(x,y)
NOTE : This would work only if there's a fixed format for the input string.
If i get your point right, then try to check this code:
text = "ABA BLLO 70000000 12-2022"
counter = 0
word = []
number = []
for a in text.split(" "):
if counter <= 1:
word.append(a)
else:
number.append(a)
counter += 1
print(word)
print(number)
The output will be
['ABA', 'BLLO']
['70000000', '12-2022']
I don't know if I'm catching your drift but here's my answer:
new_text = text.split(" ")
for i in range(2, len(new_text)):
if i == 2:
number = new_text[i]
else:
month = new_text[i].split("-")[0]
year = new_text[i].split("-")[1]
print(f"Number: {number}\nMonth: {month}\nYear: {year}")
After using something like
tempSplit = text.split()
You're going to get a list class.
result = [s for s in tempSplit if s.isdigit()]
And with that you can get int objects but problem with this last fourth element is a Date object you have to use another function for that.
As #roganjosh suggested with the comment you should check other tutorials to find out about different functions. Like for this instance maybe you can try split function then learn how to get only numbers from a list.
To get dates
month = tempSplit[3].split("-")[0]
year = tempSplit[3].split("-")[1]

How to add same number to same string in python?

I want to give same number to the same string name and save it to text file.
For example if there are multiple strings name "Ball" from filename, then I will give this string number 0. Another example, if I have multiple strings name "Square" from filename, then I will give this string number 1. And so on.
I tried using os.path.walk and splitting the text but still have no idea how to add the number and save it to text file
with open("check.txt", "w") as a:
for path, subdirs, files in os.walk(path):
for i, filename in enumerate(files):
#the filename have underscore to separate the space
#for example Ball_red_move
mylist = filename.split("_")
#I tried to take the first string name only after splitting, here
#for example "Ball"
k = mylist[0]
#After this I don't have idea to add number when the string name
#is same and also save it to txt file with the directory name
This is my expected result:
Check/Ball_red_move_01 0
Check/Ball_red_move_02 0
Check/Ball_red_move_03 0
Check/Square_jump_forward_01 1
Check/Square_jump_forward_02 1
Check/Square_jump_forward_03 1
You might like to do something like this:
Prepare a dictionary to map the string to some labeling numbers and check if the string is present.
object_map = {'Ball': 0, 'Square': 1}
def get_num_from_string(x):
for i in object_map:
if i in x:
return object_map[i]
A = ['Check/Ball_red_move_01', 'Check/Square_jump_forward_01']
for i in A:
print(i + ' '+str(get_num_from_string(i)))
This produces
Check/Ball_red_move_01 0
Check/Square_jump_forward_01 1
A few thing for you to consider, what do you want to do none of the string appears and also what do you want to do if multiple strings appear.

python add data to existing excel cell Win32com

Assume I have A1 as the only cell in a workbook, and it's blank.
I want my code to add "1" "2" and "3" to it so it says "1 2 3"
As of now I have:
NUMBERS = [1, 2, 3, 4, 5]
ThisSheet.Cells(1,1).Value = NUMBERS
this just writes the first value to the cell. I tried
ThisSheet.Cells(1,1).Value = Numbers[0-2]
but that just puts the LAST value in there. Is there a way for me to just add all of the data in there? This information will always be in String format, and I need to use Win32Com.
update:
I did
stringVar = ', '.join(str(v) for v in LIST)
UPDATE:this .join works perfectly for the NUMBERS list. Now I tried attributing it to another list that looks like this
LIST=[Description Good\nBad, Description Valid\nInvalid]
If I print LIST[0] The outcome is
Description Good
Bad
Which is what I want. But if I use .join on this one, it prints
('Description Good\nBad, Description Valid\nInvalid')
so for this one I need it to print as though I did LIST[0] and LIST[1]
So if you want to put each number in a different cell, you would do something like:
it = 1
for num in NUMBERS:
ThisSheet.Cells(1,it).Value = num
it += 1
Or if you want the first 3 numbers in the same cell:
ThisSheet.Cells(1,it).Value = ' '.join([str(num) for num in NUMBERS[:3]])
Or all of the elements in NUMBERS:
ThisSheet.Cells(1,1).Value = ' '.join([str(num) for num in NUMBERS])
EDIT
Based on your question edit, for string types containing \n and assuming every time you find a newline character, you want to jump to the next row:
# Split the LIST[0] by the \n character
splitted_lst0 = LIST[0].split('\n')
# Iterate through the LIST[0] splitted by newlines
it = 1
for line in splitted_lst0:
ThisSheet.Cells(1,it).Value = line
it += 1
If you want to do this for the whole LIST and not only for LIST[0], first merge it with the join method and split it just after it:
joined_list = (''.join(LIST)).split('\n')
And then, iterate through it the same way as we did before.

How can I create an average from a text file in Python 3.5.2?

I've been struggling with this for two days now and I can't seem to find any help. I need to search the file for a student ID (1001 is my test ID being used) and then add the numbers in each line that takes place below each occurrence of the student ID together in order to get an average.
filename = input("Enter file name: \n"
"Example: Grade Data.txt \n")
myFile = open(filename, "r")
selectSID = input("Enter SID: \n")
gradesNum = myFile.read().count(selectSID)
grades = myFile.read()
gradetotal = sum()
average = (gradetotal/gradesNum)
print(average)
The text file that is being opened looks like this:
1001
95
1002
99
1001
96
1002
0
1001
84
1002
25
1001
65
1002
19
This looks like homework so I don't want to write the code for you but here is a pseudo code (there are multiple ways to achieve what you want, this is just a simple beginner level code):
Open file to read
get two lines from the file
is the line1 interesting to me?
yes -> store value from line2 in an array
no -> ignore line2
close file
get average
Some useful references:
Python I/O
Powerful things in python to help with I/O
Built-in functions to help with basic operations like sum
from collections import defaultdict
# with open('filename') as f:
# file = [for i in f]
# in this case, it's the list below
file = [1001,95,1002,99,1001,96,1002,0,1001,84,1002,25,1001,65,1002,19]
infos = defaultdict(list)
sids = file[::2] # select sid info
grades = file[1::2] # select grade info
for sid,grade in zip(sids,grades):
infos[sid].append(grade)
print(infos[1001])
print(infos[1002])
out:
[95, 96, 84, 65]
[99, 0, 25, 19]
in this point, you can sum, average, max or min whatever you want.
Please don't use this code for your homework (use #Aditya's method); you need to learn the basics before using fancy libraries. However, I just learned about collections.defaultdict and I wanted to use it. Watch this video for a great demo on defaultdict.
import collections
import statistics
# This little guy will hold all of our grades
# https://youtu.be/lyDLAutA88s is a great video using it
grades = collections.defaultdict(list)
def get_next_num(file):
"""get the next line of a file,
remove any whitespace surrounding it,
and turn it into an integer"""
return int(next(file).strip())
with open('tmp.txt') as myfile:
while True:
try:
# seriously, watch the video
grades[get_next_num(myfile)].append(get_next_num(myfile))
except StopIteration: # end of file
break
student_id = int(input('Enter student ID. Choices: {} : '.format(list(grades.keys()))))
print(statistics.mean(grades[student_id]))
Updated Answer:
Okay, so I think I understand your question now... Same thing, except I suggest using a list, and as long as the file stays in the same format (SID, Score, so on...), this should work, and requires minimal understanding of Python (i.e No weird libraries like glob):
filename = input("Enter file name: \n"
"Example: Grade Data.txt \n")
myFile = open(filename, "r")
selectSID = input("Enter SID: \n")
raw = myFile.read() ## Raw contents of file.
val = raw.count( selectSID ) ## Returns number of occurences
print( "Occurrences: ", val ) ## Or do something else...
lines = raw.split("\n") ## Create a list containing each new line
scores = [] ## A list that will contain all your scores
while selectSID in lines:
val = lines.index( selectSID ) ## Returns where it is in the list,
score = lines[ val+1 ] ## Gets the item at that position (index) Because the score is one line after the SID
scores.append( int(score) ) ## Adds the score to the list. --Suggest you look into how to safely capturing "int"s (try, except, etc) so the program doesn't crash if the score isn't a number (Advance)
lines.remove( selectSID ) ## automatically removes first occurrence of the SID (cause that's the one we just used)
avg = sum(scores) / len(scores) ## sum() function is self explanatory (takes a list or tuple [a sequence] and adds all values (must be all numbers), THEN len() is just length.
This will return an integer, or with your file, will print:
Occurrences: 4
Regardless if this answered your question, my tip for learning basics is understanding file types and what they can do.
In your case, you will mainly need to focus on strings (text) and integers (whole numbers). Using Pythons IDLE, declare a variable, and type the name and a dot, and use tab to scroll through each functions available.
Example:
>>> myString = "Hello World"
>>> myString.[TAB] #--> [Context Menu Here]
Once you pick one form the list, enter an opening parenthesis "(", and it will give a brief description of what it does.
Hope that helps, and sorry for the lengthy reply (I was trying to explain and give pointers (tips) since you said you were a noob)

Remove comma and change string to float

I want to find "money" in a file and change the string to float , for example, I use regular expression to find "$33,326" and would like to change to [33326.0, "$"] (i.e., remove comma, $ sign and change to float). I wrote the following function but it gives me an error
import locale,re
def currencyToFloat(x):
empty = []
reNum = re.compile(r"""(?P<prefix>\$)?(?P<number>[.,0-9]+)(?P<suffix>\s+[a-zA-Z]+)?""")
new = reNum.findall(x)
for i in new:
i[1].replace(",", "")
float(i[1])
empty.append(i[1])
empty.append(i[0])
return empty
print currencyToFloat("$33,326")
Can you help me debug my code?
money = "$33,326"
money_list = [float("".join(money[1:].split(","))), "$"]
print(money_list)
OUTPUT
[33326.0, '$']
When you do
float(i[1])
you are not modifying anything. You should store the result in some variable, like:
temp = ...
But to cast to float your number have to have a dot, not a comma, so you can do:
temp = i[1].replace(",", ".")
and then cast it to float and append to the list:
empty.append(float(temp))
Note:
Something important you should know is that when you loop through a list, like
for i in new:
i is a copy of each element, so if you modify it, no changes will be done in the list new. To modify the list you can iterate over the indices:
for i in range(len(new)):
new[i] = ...
You can use str.translate()
>>>money= "$333,26"
>>>float(money.translate(None, ",$"))
33326.0
With Python 3 you can use str.maketrans with str.translate:
money = "$33,326"
print('money: {}'.format(float(money.translate(str.maketrans('', '', ",$")))))
Output: money: 33326.0

Categories