Getting elements from a table and counting total - python

I have a table as such representing the result of a game.
GameTab = [['TRE','ARD','1','1'],['PRK','GEA','2','3'],['ARD','PRK','1','0'],['TRE','GEA','2','1']]
I appended the result from a text file into table form so here's the text format: To put it easier, it's interpreted in such that for example, TRE scored 1 and ARD scored 1. PRK scored 2 and GEA score 3.
TRE:ARD:1:1
PRK:GEA:2:3
ARD:PRK:1:0
TRE:GEA:2:1
Instead of obtaining the result for the player, i want to obtain the result of the opponent instead. I have done my code in a way where it obtains the result of the player but i couldn't think of a way to obtain the opponents result.
For example, in the match of PRK:GEA and TRE:GEA:
The opponent of GEA scored a total of: 4
My code:
gameTab =[['TRE','ARD','1','1'],['PRK','GEA','2','3'],['ARD','PRK','1','0'],
['TRE','GEA','2','1']]
dictionary = {}
for i in gameTab:
for c in range(len(i[:2])):
if i[:2][c] not in dictionary.keys():
dictionary[i[:2][c]] = int(i[2:][c])
else:
dictionary[i[:2][c]] += int(i[2:][c])
print(dictionary)

In order to obtain the result of the opponent against a team, The below code satisfied the condition:
gameTab =[['TRE','ARD','1','1'],['PRK','GEA','2','3'],['ARD','PRK','1','0'],['TRE','GEA','2','1']]
dictionary = {}
for i in gameTab:
if i[0] in dictionary:
dictionary[i[0]] += int(i[3])
else:
dictionary[i[0]] = int(i[2])
if i[1] in dictionary:
dictionary[i[1]] += int(i[2])
else:
dictionary[i[1]] = int(i[2])
print(dictionary)
it prints out: {'ARD': 1, 'GEA': 4, 'TRE': 2, 'PRK': 3}
Basically traverse the list of lists, and for every team check if it exists in dictionary then increment its value as the opponents value. And finally you would get all point scored against a team by the opposition.

gametab = [['TRE','ARD','1','1'],['PRK','GEA','2','3'],['ARD','PRK','1','0'],['TRE','GEA','2','1']]
dicta = {}
for i in range(len(gametab)):
for j in range(2):
if gametab[i][j] in dicta:
dicta[gametab[i][j]] += int(gametab[i][j+2])
else:
dicta[gametab[i][j]] = int(gametab[i][j+2])
print dicta

Related

Finding the highest sum of a string in a list

In this task, we creating a function called highsum. It looks at a list of strings and sums up all the numerical characters. We then return the location of the element of the list with the highest value.
For example given list highestSum([“jx72i9r”, “9ch37#r2”, “8rgku3op8”]).
We then must find [17, 21,19] which is all the numerical values added up. Because 21 is the highest value we need the function to return 1 because that is the location of 9ch37#r2 in the list.
This is what I have so far:-
def highestSum(stringList):
number= 0
for xinlist in stringList:
print(xinlist)
for yoflist in xinlist:
print (yoflist)
if yoflist in "1234567890":
number+=int(yoflist)
print(number)
The first for loop cycles through each element while the second for loop cycles through each character in the elements. My accumulator variable work but the problem is I don't know how to let it know when it moves on to a new element.
Another example highestSum([“90gw1xy3”, “12432”, “hfkvbd2”, “*&hdj!4”])
this would return 0 as it as the highest sum of digit characters.
Homemade version
Basically, we gather turn each element in the given list to there digits sum. So like [18,21,19]. Then pair this with original list using zip(). Then use .index() in order to get the corresponding index.
hilarious one-liner
def highestSum(stringList):
return stringList.index({k:v for k,v in zip([sum(list(map(int,[character for character in stringEx if character.isdigit()]))) for stringEx in stringList],stringList)}[max(summed)])
List comprehension & dict comprehension
def highestSum(stringList):
summed = [sum(list(map(int,[character for character in stringEx if character.isdigit()]))) for stringEx in stringList]
highest = max(summed)
pair = {k:v for k,v in zip(summed,stringList)}
return stringList.index(pair[highest])
print(highestSum(["jx72i9r", "9ch37#r2", "8rgku3op8"]))
Easier to understand for the human eye.
def highestSum(stringList):
summed = []
for stringEx in stringList:
gathered = []
for character in stringEx:
if character.isdigit():
gathered.append(character)
gathered = sum(list(map(int,gathered)))
summed.append(gathered)
highest = max(summed)
pair = {}
for k,v in zip(summed,stringList):
pair[k] = v
return stringList.index(pair[highest])
print(highestSum(["jx72i9r", "9ch37#r2", "8rgku3op8"]))
output
1
I have modified your code. Look at this solution. You need a condition to for the highest number in the list and a variable to keep track of its index. See solution below:
def highestSum(stringList):
index = 0
highestValue = 0
for xinlist in stringList:
number= 0
for yoflist in xinlist:
if yoflist in "1234567890":
number+=int(yoflist)
if number > highestValue:
index = stringList.index(xinlist)
highestValue = number
print(index)
stringList = ['jx72i9r', '9ch37#r2', '8rgku3op8']
highestSum(stringList)
def highestSum(stringList):
res = list()
for xinlist in stringList:
number = 0
for yoflist in xinlist:
if yoflist in "1234567890":
number += int(yoflist)
res.append(number)
# find the max position form the accumulator
maxNumPos = 0
for i in range(len(res)):
if res[i] > res[maxNumPos]:
maxNumPos = i
print(maxNumPos)
highestSum(['90gw1xy3', '12432', 'hfkvbd2', '*&hdj!4'])
I'll use list comprehension, maybe it's difficult to read.
code:
x = ["jx72i9r", "9ch37#r2", "8rgku3op8"]
x_to_int = [sum([int(char) for char in s if char.isdigit()]) for s in x]
print(x_to_int.index(max(x_to_int)))
result:
1

Issues with KeyError: 0

Im having issued where my code keeps saying KeyError: 0, I have searched all over and couldn't find a way to fix this
student_scores = {'0':65.0, '1':54.7}
average_score = 66.0
i = 0
for v in student_scores:
if student_scores[i] >= average_score:
above_avg_check = "{} {}".format(student_names[i], student_scores[i])
above_avg.append(above_avg_check)
print(above_avg_check)
i += 1
I am not sure on what to do, i is both a counter and the key of student_scores, so I can use it in a while loop.
You're checking an integer index while your 0 index is actually a string.
This code compiles for me on repl, just convert your index values to strings before trying to find them
student_scores = {'0':65.0, '1':54.7}
average_score = 66.0
i = 0
for v in student_scores:
if student_scores[str(i)] >= average_score:
above_avg_check = "{} {}".format(student_names[str(i)], student_scores[str(i)])
above_avg.append(above_avg_check)
print(above_avg_check)
i += 1
You can use the .items() method and get the scores in a much more simple way. The you can format your string based on the student and their score within your for loop.
student_scores = {'0': 65.0, '1': 54.7}
average_score = 65.0
i = 0
above_avg = []
for student, score in student_scores.items():
if score >= average_score:
above_average_check = '{}: {}'.format(student, score)
above_avg.append(above_average_check)
print(above_average_check)
i += 1
And here is your output:
0: 65.0
This will get you the output that you are looking for as you iterate through each key and its corresponding value.

Comparing an unlimited number of values taken from a 2D array to see which element has the largest sum

I'm trying to produce a program that will check the highest sum value of a 2D array.Then it needs to compare each value against each other to output which is the largest of all the sums for each position in the array.
I'm able to do this for a set number of elements but i would like to do this for an unlimited number of elements depending on how many elements the user inputs.
Person = [123,321,213]
TotalMorn =[[3,5,6,4,5,3,7],
[2,1,1,2,3,4,5],
[3,4,5,6,7,6,5]]
TotalAft =[[8,7,6,2,6,7,5],
[4,3,2,3,4,3,2],
[1,1,1,1,2,3,1]]
def WeeklyTotal(K):
Total = 0
for j in range(7):
TotalM = TotalMorn[K][j]
TotslA = TotalAft[K][j]
Total = TotalM + TotalA + Total
return Total
Total1 = WeeklyTotal(0)
Total2 = WeeklyTotal(1)
Total3 = WeeklyTotal(2)
if Total1 > Total2 and Total1 > Total3:
print 'Person', (Person[0]), 'Has produced the most profit with ', Total1
elif Total2 > Total1 and Total2 > Total3:
print 'Peron', (Person[1]), 'Has produced the most profit with ', Total2
elif Total3 > Total1 and Total3 > Total2:
print 'Person', (Person[2]), 'Has produced the most profit with ', Total3
I assume what you want to do is find the max value in the array WeeklyTotal?
maxIndex, maxValue = 0,0
for i in range(0,len(WeeklyTotal)-1):
if WeeklyTotal[i] > maxValue :
maxValue = WeeklyTotal[i]
maxIndex = i
print 'Person ',Person[maxIndex],' Has produced the most profit with ',WeeklyTotal[maxIndex]
In your case, you either need to bind person to his totalScore. You would then look for the maximum score value, and so you would have the person with the maximum score affiliated with this value, such as...
arr = [('John', 15), ('Sue', 13), ('Jack', 20), ('Tom', 5)]
print max(arr, key = lambda x:x[1])
# outputs : ('Jack', 20)
Here, you have bound the score to the person into a list of tuples. You asking max function to look for the highest value using the second element of each tuple (that's what key = lambda x:x[1] means).
In your example, where data would be formatted such as...
people = ['John', 'Sue', 'Jack', 'Tom']
scores = [15, 13, 20, 5]
... you might want to use a function to determine the index of the highest value, doing :
# We set the highest score at the beginning as the first value, and save the index.
curr_score = scores[0]
saved_index = 0
# We then iterate through scores, not looping through the first item, as its index
# is already saved. We set the start of the index to `1`.
for index, score in enumerate(scores[1:], start=1):
if score > curr_score:
# We save the new highest score.
curr_score = score
# And keep its index.
saved_index = index
# At the end of the loop, we saved the maximum value index, and can use it
# on `people` array.
print people[saved_index]
# It will output the person with the highest score.
Here is a short solution using some python idioms:
(Thanks to IMCoins for reminding me about max(a, key = lambda...)
people = [123,321,213]
morning =[[3,5,6,4,5,3,7],
[2,1,1,2,3,4,5],
[3,4,5,6,7,6,5]]
afternoon =[[8,7,6,2,6,7,5],
[4,3,2,3,4,3,2],
[1,1,1,1,2,3,1]]
def makeTotals(people, morning, afternoon):
return [(p,sum(m+a)) for (p,m,a) in zip(people, morning, afternoon)]
allTotals = makeTotals(people, morning, afternoon)
print(max(allTotals, key = lambda x:x[1]))
Output:
(123, 74)
The makeTotals function zips up the arrays to align each person with their morning and afternoon scores and (p,sum(m+a)) creates a tuple of the person and their total.
The call to max uses the key = lambda x:x[1] parameter (thanks #IMCoins) to pull out the tuple with the largest sum of morning and afternoon scores.
how about a 'one-liner' (with line breaks and added whitespace for readability)
Person = [123,321,213]
TotalMorn =[[3,5,6,4,5,3,7],
[2,1,1,2,3,4,5],
[3,4,5,6,7,6,5]]
TotalAft =[[8,7,6,2,6,7,5],
[4,3,2,3,4,3,2],
[1,1,1,1,2,3,1]]
print('Person %s Has produced the most profit with %s'
% max(zip(map(sum,
zip(map(sum, TotalMorn),
map(sum, TotalAft))),
Person))[::-1])
Person 123 Has produced the most profit with 74

Assigning salespersons to different cities program

I was working on a problem of assigning 8 salespersons to 8 different cities, which are represented in below format.
The column represents Sales person and row represent cities.
1) The condition for assigning are :
1) Only one city per person
2) Once a city is assigned a salesperson , the rows and columns and diagonal cities cannot be assigned to another person
I am not able to recreate an example from memory , sorry for that , but the representation of cities and salesperson is correct.
I thought to avoid rows or columns for similar salesperson , I could use permutations from python which will give me distinct set of cities without overlapping and from there on I could check for diagonal values.
Here is my attempt.
import collections
import itertools
def display (l):
list_count = 0
k = ''
for i in l:
print i
list_count = list_count + 1
if list_count != len(l):
k = k + ','
cities = [1,2,3,4,5,6,7,8]
sales = [1,2,3,4,5,6,7,8]
print_list = []
count = 0
for i in itertools.permutations([1,2,3,4,5,6,7,8],8):
print_list.append(i)
if count == 2:
display(print_list)
#print print_list
#print '\n'
for j in range(8):
print_list.pop()
count = 0
count = count + 1
I am stuck on how to check if a salesperson is in diagonal position to another Salesperson, If someone can extend my approach that would be great , would like any other explanation , would be helpful, I would like python as I am practising in it.

Python, append within a loop

So I need to save the results of a loop and I'm having some difficulty. I want to record my results to a new list, but I get "string index out of range" and other errors. The end goal is to record the products of digits 1-5, 2-6, 3-7 etc, eventually keeping the highest product.
def product_of_digits(number):
d= str(number)
for integer in d:
s = 0
k = []
while s < (len(d)):
j = (int(d[s])*int(d[s+1])*int(d[s+2])*int(d[s+3])*int(d[s+4]))
s += 1
k.append(j)
print(k)
product_of_digits(n)
Similar question some time ago. Hi Chauxvive
This is because you are checking until the last index of d as s and then doing d[s+4] and so on... Instead, you should change your while loop to:
while s < (len(d)-4):

Categories

Resources