Split strings from integers from a text file - python-3.x

This is the code part of viewing a text file with a list of highscores and putting them into a list. i need to then split the string and integers.
OutList = input("Which class score would you like to view? ").upper()
if OutList == 'A':
List = open("classA.txt").readlines()
print (List)
elif OutList == 'B':
List = open("classB.txt").readlines()
print (List)
elif OutList == 'C':
List = open("classC.txt").readlines()
print (List)
This code currently prints this:
['Bobby 6\n', 'Thomas 4\n']
I need to know how to separate these and get rid of the '\n' to just have the name and score printed out.

Use rstrip()
Here is your modified program:
OutList = input("Which class score would you like to view? ").upper()
if OutList == 'A':
List = open("classA.txt").readlines()
print (List)
elif OutList == 'B':
List = open("classB.txt").readlines()
print (List)
elif OutList == 'C':
List = open("classC.txt").readlines()
for item in List:
print(item.rstrip())
Output:
Which class score would you like to view? A
['Bobby 6\n', 'Thomas 4\n']
Bobby 6
Thomas 4
You can read more on rstrip function here.

Related

List of Starters in dictionaries

in the given method called solve which takes as parameter a list of strings called items.
You have to print the list of items for each alphabet. Print in sorted order of alphabets.
Example Input:
noodles, rice, banan, sweets, ramen, souffle, apricot, apple, bread
Output:
a : apple apricot
b : banana bread
n : noodles
r : ramen rice
s : souffle sweets
import collections
def solve(items):
result = {}
for word in items:
char = word[0]
if char in result:
result[char].append(word)
else:
result[char] = [word]
od = collections.OrderedDict(sorted(result.items()))
for key, value in od.items():
print ("%s : %s"%(key,value))
but, im getting it in brakets...! not like a desired output...
Alternatively you can try to leverage Python collections.defaultdict as this will simply the code logic:
You could convert this easily to the function - maybe as an exercise? If you have any questions, please ask.
from collections import defaultdict
inputs = "noodles, rice, banan, sweets, ramen, souffle, apricot, apple, bread"
groups = defaultdict(list)
lst = inputs.split(', ')
#print(lst)
for item in lst:
groups[item[0]].append(item)
for k, val in sorted(groups.items()):
print(k, ": ", *val) # *val to expand the list content
Output:
a : apricot apple
b : banan bread
n : noodles
r : rice ramen
s : sweets souffle
You are not performing any comparisons to find the maxEnglish or the maxTotalMarks. The reason print('Max Marks:',d['name']) is printing the correct result is because Dwight is the last entry in the Ordered Dictionary and you are printing the last item's name.
One of the ways you could tackle this question is by keeping variables that keep track of the maximum scores and as you iterate through the dictionary, you can compare against these stored value to determine if the current value
that you are iterating is greater or lesser than all the values that you have seen so far. Something like this:
def solve(stats):
maxEnglishMarks = -1
maxTotalMarks = -1
maxEnglishStudentName = maxTotalStudentName = None
for stat in stats:
totalMarks = sum([i for i in stat.values() if str(i).isnumeric() == True])
if totalMarks > maxTotalMarks:
maxTotalStudentName = stat['name']
maxTotalMarks = totalMarks
if stat['English'] > maxEnglishMarks:
maxEnglishStudentName = stat['name']
maxEnglishMarks = stat['English']
print('Max English:', maxEnglishStudentName)
print('Max Marks:', maxTotalStudentName)
stats = [
{'name': 'Jim', 'English': 92, 'Math': 80, 'Physics': 70},
{'name': 'Pam', 'French': 72, 'English': 80, 'Biology': 65},
{'name': 'Dwight', 'Farming': 95, 'English': 85, 'Chemistry': 97}
]
solve(stats)

Can't figure out how to print out all the integers in my dictionary value list

Curious if there is any way to do something similar to this.
Dictionary = {"item":1,"item2":[1,2,3,4]}
for keys,values in Dictionary.items():
if values == list():
print(values[0:3])
With the resulting outcome of
1
2
3
4
Sure, there is:
Dictionary = {"item": 1, "item2": [1,2,3,4]}
for values in Dictionary.values():
if type(values) == list:
for item in values:
print(item, end=' ')

How do i add a list and an argument?

I am new to python and couldn't work out a solution:
I have a empty list and a command generated from processing user input. i want to merge them so it works as normal command.
lst = []
cmd = insert(0,5)
i want it to work like
lst.insert(0,5)
so that output is
[5]
but with every loop the value of cmd will change.
concatenate, .join or print format doesn't apply here
shall i try class or is there any other easier method to do so?
This will write 5 to the 0th index of the list
lst = []
lst[0] = 5
# lst is [5] now
This will add 5 to the end of the list.
lst = []
lst.append(5)
# lst is [5] now
This will remove the last values from the list.
lst = [5]
lst.pop()
# lst is empty now []
You can also use pop() at a certain index.
lst = [5, 4, 3, 2, 1]
lst.pop(2)
# lst is changed to [5, 4, 2, 1]
If the user defines the index and the value, you could try something like this:
# The index the user provides has to be <= to the length of the list
lst = []
cmd = input("Give a command:\n").split(" ") # input must be space-separated
if cmd[0] == "append":
lst.append(cmd[1])
elif cmd[0] == "insert":
lst[cmd[1]] = cmd[2]
elif cmd[0] == "pop" and len(cmd) == 1:
lst.pop()
elif cmd[0] == "pop" and len(cmd) == 2:
lst.pop(cmd[1])
There are some problems in it, like error handling, but it should work if you know what the inputs will be beforehand.

Define function that reads from Lists of lists

Heres a quick example:-
setup = [['dog','red','big','ears'],
['cat','blue','small','tail']]
def do_it(dummy_parameter):
if do_it [0][0] == 'dog':
print 'dog'
elif do_it [0][0] == 'cat'
print 'cat'
do_it(setup)
Basically looking to go through a list of up to four lists, make an action depending on each of the list contents.. It a bit vague but any assistance would be appreciated! :)
Getting the error
TypeError: 'function' object has no attribute '__getitem__'
Here is an example how to get all the values from a list and list of list :)
with recursion :)
test = [['a', 'b', 'c'],['d', 'e'], 'f']
def separate(item):
try:
for i in item:
if type(i) == list:
separate(i)
else:
print(i)
except IndexError:
pass
separate(test)

Getting index of duplicate letters in a string

from graphics import *
import random
def hangman(word):
returnStuff = {'again':0, '1st':1}
alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o',
'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
win = GraphWin("Hangman", 800, 550)
win.setBackground("yellow")
titleText = Text(Point(400,50), 'HANGMAN')
titleText.setSize(24)
titleText.setStyle('bold')
titleText.draw(win)
#Building the hangman base
base = Line(Point(120,350),Point(230,350))
base.draw(win)
stand = Line(Point(175,350),Point(175,150))
stand.draw(win)
stand2 = Line(Point(175,150),Point(250,150))
stand2.draw(win)
stand3 = Line(Point(250,150),Point(250,180))
stand3.draw(win)
#drawing the empty lines for the word
x1 = 150
x2 = 180
l = 0
print(word)
while l< len(word):
wordLine = Line(Point(x1, 420),Point(x2,420))
wordLine.draw(win)
l+=1
x1+=40
x2+=40
guessCounter = 0
textCheck = 0
invalidText = Text(Point(600,100), 'You did not enter a valid letter.')
invalidText.setTextColor('red')
indexes = []
while guessCounter < 6:
#text entry box
textEntry = Entry(Point(600,180),10)
textEntry.draw(win)
guessText = Text(Point(600,150), 'Guess a letter:')
guessText.draw(win)
#user has to click this box to confirm the letter
enterBox = Rectangle(Point(580,200), Point(620,220))
enterBox.setFill('white')
enterBox.draw(win)
clickText = Text(Point(600,210), 'Enter')
clickText.draw(win)
click = win.getMouse()
x = click.getX()
y = click.getY()
if 580 < x < 620 and 200 < y < 220:
guess = textEntry.getText().lower().strip()
if guess not in alphabet:
if textCheck == 0:
invalidText.draw(win)
textCheck = 1
else:
if textCheck == 1:
invalidText.undraw()
textCheck = 0
for letter in word:
if letter == guess:
indexes.append(word.index(guess))
print(indexes)
win.getMouse()
win.close()
return returnStuff
#list with various words pertaining to nanotechnology
words = ['nanotechnology', 'science', 'nanometre' , 'strength', 'chemistry',
'small', 'molecule', 'light' , 'weight', 'technology', 'materials',
'property', 'physics', 'engineering', 'matter', 'waterloo', 'nanobot',
'reaction', 'structure', 'cells']
#picks a random word from the list
word = random.choice(words)
#this variable ensures it opens the game the first time
initialCall = 1
#stores the returnValue for the first call
returnValue = hangman(word)
#sets the initialCall to 0 after first call
if returnValue['1st']==1:
initialCall=0
#Calls the game function again if user wishes
while initialCall == 1 or returnStuff['again'] == 1:
returnValue = hangman(word)
I am making Hangman in Python graphics. I apologize for the huge block of code, it all works fine, I just thought it must be useful. The part of the code that I'm concerned about is this:
else:
if textCheck == 1:
invalidText.undraw()
textCheck = 0
for letter in word:
if letter == guess:
indexes.append(word.index(guess))
print(indexes)
This block of code will be executed when the user's letter guess is in the alphabet, I then run through each letter in the chosen word, and if at any point a letter in the word is the same as the guess letter, I store the index of that letter in a empty list so I can use that to tell the computer where to draw the letters on the empty lines.
It works fine, with the exception of when there is a duplicate letter in the word. For example, engineering has 3 es. Unfortunately, .index() only records the index for when the letter appears the first time, and it disregards the other letters. What is the work around for this so I can get the indexes of all 3 es in that word, instead of 3 indexes of just the first e. For testing purposes, I have printed the chosen word and the index list on the console so I can see what's going on and so I don't actually have to guess a letter.
you can do something like this
def indexes(word,letter):
for i,x in enumerate(word):
if x == letter:
yield i
test
>>> list( indexes("engineering","e") )
[0, 5, 6]
>>>
this function is a generator, that is a lazy function that only give result when asked for then, to get a individual result you use next, the functions is execute until the first yield then return the result and stop its execution and remember where it was, until another call to next is executed in witch point resume execution from the previous point until the next yield, if the is no more raise StopIteration, for example:
>>> word="engineering"
>>> index_e = indexes(word,"e")
>>> next(index_e)
0
>>> print(word)
engineering
>>> next(index_e)
5
>>> next(index_e)
6
>>> next(index_e)
Traceback (most recent call last):
File "<pyshell#13>", line 1, in <module>
next(index_e)
StopIteration
>>>
to update a list with the result of this function, you can use the extend method
>>> my_list=list()
>>> index_e = indexes(word,"e")
>>> my_list.extend( index_e )
>>> my_list
[0, 5, 6]
>>>
generator are used in cases where their result is only a intermediary step to something else because they use a minimum amount of memory, but in this case maybe you want the whole thing so use it as the first example or remake the function to return a list in the first place like this
def indexes(word,letter):
result = list()
for i,x in enumerate(word):
if x == letter:
result.append(i)
return result
sorry if I confuse you with the yield thing.

Resources