I'm an absolute amateur when it comes to any coding but I have been attempting to create a top trumps type program using Python. In the below code I have created player cards that are added to a list using a class. I am now attempting to randomly split the list (fullCardList) into two separate lists but having a lot of issues.
Once the list has been split, I am aiming to compare a stat from each player but cannot seem to figure how to show the card's name/caps/goals. I hope this makes sense. Can anyone give me any advice?
class Player:
def __init__(self, name, caps, goals, trophies):
self.name = name
self.caps = caps
self.goals = goals
self.trophies = trophies
CardListOne = Player("Lionel Messi",102, 46, 26)
CardListTwo = Player("Ronaldo", 124, 55, 17)
CardListThree = Player("Mats Hummels", 39, 4, 8)
CardListFour = Player("Angel Di Maria", 65, 15, 10)
CardListFive = Player("Jason", 101,44,12)
CardsListSix = Player("Peter", 45,10,1)
fullCardList = [CardListOne.name, CardListOne.caps,CardListOne.goals,CardListOne.trophies],[CardListTwo.name,CardListTwo.caps,CardListTwo.goals,CardListTwo.trophies],[CardListThree.name, CardListThree.caps, CardListThree.goals, CardListThree.trophies], [CardListFour.name,CardListFour.caps,CardListFour.goals,CardListFour.trophies], [CardListFive.name,CardListFive.caps,CardListFive.goals,CardListFive.trophies]
global playersRandomSelection, computersRandomSelection
playersRandomSelection = []
playersRandomSelection = random.sample(fullCardList,3)
computersRandomSelection = []
computersRandomSelection = random.sample(fullCardList,3)
print("Players name selection: " + str(playersRandomSelection))
print("Computers random selection: " + str(computersRandomSelection))
Hhow to show the card's name/caps/goals/(trophies):
You can use the method, vars():
lst = [CardListOne,CardListTwo,CardListThree,CardListFour,CardListFive,CardsListSix]
for n in lst:
a = vars(n)
print('\n'.join(f"{k}: {v}" for k,v in a.items()))
print()
Output:
name: Lionel Messi
caps: 102
goals: 46
trophies: 26
name: Ronaldo
caps: 124
goals: 55
trophies: 17
name: Mats Hummels
caps: 39
goals: 4
trophies: 8
name: Angel Di Maria
caps: 65
goals: 15
trophies: 10
name: Jason
caps: 101
goals: 44
trophies: 12
name: Peter
caps: 45
goals: 10
trophies: 1
Related
I'm creating a smart home system in domoticz and I'm having some issues. So basically I have 32 relays for connections (ON, OFF) and each of one is displayed as a switch (In domoticz). Every switch has his own idx number for API control (turn on/off the switch with requests). My task is to get the status of my relays, for example I can only get 1,0 these are on/off. 1 is equal to on, 0 is equal to off. So I built a little logic to get the relay status, but then I realized that the idx numbers are unique to every device I have, and they are mixed. So I built some type of define, but I don't know how to work with it.
These are my definitions for every relay. This is only an example, these are not my real idx's from domoticz.
# Relays
RELAY_1_IDX = 1
RELAY_2_IDX = 2
RELAY_3_IDX = 3
RELAY_4_IDX = 4
RELAY_5_IDX = 5
RELAY_6_IDX = 6
RELAY_7_IDX = 7
RELAY_8_IDX = 8
RELAY_9_IDX = 9
RELAY_10_IDX = 10
RELAY_11_IDX = 11
RELAY_12_IDX = 12
RELAY_13_IDX = 13
RELAY_14_IDX = 14
RELAY_15_IDX = 15
RELAY_16_IDX = 16
RELAY_17_IDX = 17
RELAY_18_IDX = 18
RELAY_19_IDX = 19
RELAY_20_IDX = 20
RELAY_21_IDX = 21
RELAY_22_IDX = 22
RELAY_23_IDX = 23
RELAY_24_IDX = 24
RELAY_25_IDX = 25
RELAY_26_IDX = 26
RELAY_27_IDX = 27
RELAY_28_IDX = 28
RELAY_29_IDX = 29
RELAY_30_IDX = 30
RELAY_31_IDX = 31
RELAY_32_IDX = 32
# Inputs
INPUT_1_IDX = 50
INPUT_2_IDX = 51
INPUT_3_IDX = 52
INPUT_4_IDX = 53
INPUT_5_IDX = 54
INPUT_6_IDX = 55
This is my code without any logic to give the number a definition.
# Change 32 Relays statuses to real-time in domoticz.
for relay in range(1, 32):
RELAY_INPUT = f"RELAY-READ-255,{relay}"
srvsock.sendto(RELAY_INPUT.encode(), (edsIP, edsPORT))
_relay_status_ = srvsock.recv(4096).decode('utf-8').replace(f'RELAY-READ-255,{relay},','').replace(',OK', '')
_set_ = Domoticz.set_value(relay, int(_relay_status_))
# _relay_status_ is an integer, available - 1,0 (1-on, 0-off)
# ... Logic to find idx number for the current relay which is our for bool....
if _set_ is False: print(f'* Note: Request for relay {relay} was unsuccessful.')
time.sleep(0.15)
I have problem with the for loop in Python. I want to sum these data based on time and location, without pandas. This data is in the MySQL database (mysql workbench):
Time No_of_people Location
----------------------------------------
07:00 20 Liberty City
07:15 25 Liberty City
07:30 20 Liberty City
07:45 30 Liberty City
08:00 21 Liberty City
...
07:00 10 San Andreas
07:15 15 San Andreas
07:30 20 San Andreas
07:45 25 San Andreas
08:00 30 San Andreas
Now I want it to be like:
Time No_of_people Location
----------------------------------------
07:00 116 Liberty City
08:00 120 Liberty City
...
07:00 100 San Andreas
This is currently what I have done:
views.py:
def getData(request):
api = 'http://localhost:8000/api/myData/'
response = requests.get(api)
myData = response.json()
time = []
no_of_people = []
location = []
for hourly in myData:
time.append(hourly['time'])
no_of_people.append(hourly['no_of_people'])
location.append(hourly['location'])
hour = []
for x in range(7,24):
hour.append(x)
uniqueLocation=[]
for x in location:
if x not in uniqueLocation:
uniqueLocation.append(x)
for uniqueIndex in uniqueLocation:
for x in hour:
sum =0
for index, t in enumerate(time):
x_time = t.split(":")[0]
if int(x_time) == x and uniqueIndex == location[index]:
sum += no_of_people[index]
print(str(sum))
json_obj = {
"time": time,
"no_of_people": no_of_people,
"location": location
}
return JsonResponse(data=json_obj)
You want to group by the location, therefore I suggest you aim for this format, which is easier to visualize, and then try to build the table output from there (for each city, for each time, print hour and people/hr)
[
{'location' : 'Liberty City', 'times': [{'hour' : '7:00', 'people' : 116}, ...]},
...
]
When working with almost any database, try to create a class per object (row, table, bucket, relationship, (insert database term here), etc). You can then isolate logic here rather than clutter the main function
class Location:
def __init__(self, name):
self.name = name
self.times = list()
def __str__(self):
s = ['{}\t{}\t{}'.format(k, t[k], self.name) for t in self.times for k in t.keys()]
return '\n'.join(s)
def add_time(self, hour, people):
existing_people_for_hour = None
for t in self.times: # loop existing times, looking for the hour
existing_people_for_hour = t.get(hour)
if existing_people_for_hour is not None:
t[hour] += people
break # found the hour to update, so break the loop
if existing_people_for_hour is None: # if the hour was never found, add to the times list
self.times.append({hour : people})
With that in place, use a dictionary to group on the location value and you should be able to print them in the end
locations = dict()
for d in myData:
# parse each value out
hour = d['time'][:2] + ':00'
p = int(d['no_of_people'])
loc = d['location']
# get the location from the map, if exists, else create new one
l = locations.get(loc, Location(loc))
l.add_time(hour, p) # add the people for the time
locations[loc] = l # upsert the new location
for l in locations.values():
print(l)
Output
07:00 95 Liberty City
08:00 21 Liberty City
07:00 70 San Andreas
08:00 30 San Andreas
Over the past few days, I have been attempting to code a solution to Task 3 of the A453 Computing section. Essentially, I am aiming to produce a program that takes data from members of a class that have participated in a maths quiz (that is situated over three text files, as the exam specification states that participants in the hypothetical quiz must be from a "Class 1" "Class 2", or "Class 3")and then sorts it, according to the user's input, in one of the two following ways:
In alphabetical order with each student's (in the appropriate class) highest score for the tests.
By the highest score achieved by each student in that class, from highest to lowest.
Here is the code that I have written up so far:
def highest_score_first():
names_with_scores_list = []
ScoresFirstList = []
AlreadySeenList = []
for line in file:
names_with_scores_list.append(line.strip())
for row in names_with_scores_list:
nameString = row[0: row.index(', ') ]
scoreString = row[row.index(', ')+2 : len(row)]
scoresFirstString = scoreString+","+nameString
#print(scoresFirstString)
ScoresFirstList.append(scoresFirstString)
ScoresFirstList.sort(reverse = True)
for row in ScoresFirstList:
nameString = row[row.index(',') : len(row)]
if nameString not in AlreadySeenList:
print(row)
AlreadySeenList.append(nameString)
def alphabetical():
names_with_scores_list = []
NamesFirstList = []
AlreadySeenList = []
for line in file:
names_with_scores_list.append(line.strip())
for row in names_with_scores_list:
nameString = row[0: row.index(', ') ]
scoreString = row[row.index(', ')+2 : len(row)]
NamesFirstString = nameString+","+scoreString
NamesFirstList.append(NamesFirstString)
NamesFirstList.sort()
for row in NamesFirstList:
nameString = row[0: row.index(',') ]
if nameString not in AlreadySeenList:
print (row)
AlreadySeenList.append(nameString)
# main code here
chosen_class = input("Which class would you like to view - one, two or three?")
if chosen_class == "one":
file = open("classonescore.txt","r")
elif chosen_class == "two":
file = open("classtwoscore.txt","r")
elif chosen_class == "three":
file = open("classthreescore.txt","r")
else:
print("Unfortunately, you have entered an invalid class name. ")
function = input("How would you like to sort the data - alphabetically or by highest score? Choose A or H")
if function.upper() == "H":
highest_score_first()
elif function.upper() == "A":
alphabetical()
Essentially, the problem with the code is that, when the user wants the data for a class to be sorted alphabetically (in terms of highest score), only the lowest score for each student, as well as his name, is generated.
For instance, whilst data from Class 1 is written into the text file as follows:
Chris, 08
Clive, 09
Will, 04
Harry, 10
Ahmed, 08
Geoff, 06
Amy, 04
Vennu, 10
Vennu, 07
Amy, 06
Ahmed, 09
Geoff, 04
Harry, 07
Will, 06
Clive, 10
Chris, 10
It is displayed upon running the program (when the user wants scores to be generated using "alphabetical") as:
Ahmed,08
Amy,04
Chris,08
Clive,09
Geoff,04
Harry,07
Vennu,07
Will,04
Ideally, it should be generated as follows:
Ahmed, 09
Amy, 06
Chris, 10
Clive, 10
Geoff, 06
Harry, 10
Vennu, 10
Will, 06
Unfortunately, I am unable to contact my teacher, so any reply would be greatly appreciated.
Many thanks,
Chris
I have 2 CSV files. One with city name, population and humidity. In second cities are mapped to states. I want to get state-wise total population and average humidity. Can someone help? Here is the example:
CSV 1:
CityName,population,humidity
Austin,1000,20
Sanjose,2200,10
Sacramento,500,5
CSV 2:
State,city name
Ca,Sanjose
Ca,Sacramento
Texas,Austin
Would like to get output(sum population and average humidity for state):
Ca,2700,7.5
Texas,1000,20
The above solution doesn't work because dictionary will contain one one key value. i gave up and finally used a loop. below code is working, mentioned input too
csv1
state_name,city_name
CA,sacramento
utah,saltlake
CA,san jose
Utah,provo
CA,sanfrancisco
TX,austin
TX,dallas
OR,portland
CSV2
city_name population humidity
sacramento 1000 1
saltlake 300 5
san jose 500 2
provo 100 7
sanfrancisco 700 3
austin 2000 4
dallas 2500 5
portland 300 6
def mapping_within_dataframe(self, file1,file2,file3):
self.csv1 = file1
self.csv2 = file2
self.outcsv = file3
one_state_data = 0
outfile = csv.writer(open('self.outcsv', 'w'), delimiter=',')
state_city = read_csv(self.csv1)
city_data = read_csv(self.csv2)
all_state = list(set(state_city.state_name))
for one_state in all_state:
one_state_cities = list(state_city.loc[state_city.state_name == one_state, "city_name"])
one_state_data = 0
for one_city in one_state_cities:
one_city_data = city_data.loc[city_data.city_name == one_city, "population"].sum()
one_state_data = one_state_data + one_city_data
print one_state, one_state_data
outfile.writerows(whatever)
def output(file1, file2):
f = lambda x: x.strip() #strips newline and white space characters
with open(file1) as cities:
with open(file2) as states:
states_dict = {}
cities_dict = {}
for line in states:
line = line.split(',')
states_dict[f(line[0])] = f(line[1])
for line in cities:
line = line.split(',')
cities_dict[f(line[0])] = (int(f(line[1])) , int(f(line[2])))
for state , city in states_dict.iteritems():
try:
print state, cities_dict[city]
except KeyError:
pass
output(CSV1,CSV2) #these are the names of the files
This gives the output you wanted. Just make sure the names of cities in both files are the same in terms of capitalization.
I wrote the following class:
class Average(object):
def __init__(self,invoer):
self.regel = invoer
self.persons = []
def parse_input(self):
lengte = self.regel.split('\t')[2]
gewicht = self.regel.split('\t')[3]
self.lengte = float(lengte)
self.gewicht = float(gewicht)
return self.lengte, self.gewicht
def add_person(self):
self.persons += [self.lengte, self.gewicht]
def get_average_bmi(self):
total_bmi = 0
for i in self.persons:
total_bmi += i[0]/i[1]
average_bmi = total_bmi/len(self.persons)
self.average = average_bmi
return self.average
And the program looks as follows:
from BodyMassIndex import Average
from ipy_lib import file_input
bestand = file_input().splitlines()
for i in bestand:
bmi = Average(i)
bmi.parse_input()
bmi.add_person()
average_bmi = bmi.get_average_bmi()
The input, that comes in the bestand variable looks like this:
Barbara Lerner V 1.54 67 No
Danny Coronado M 1.84 89 No
Diana Knox V 1.69 58 Yes
Penney Rose V 1.56 102 No
Jessica Richman V 1.58 63 Yes
The parse_input() method takes the length en heigth of each person, add_person adds it to a list and get_average_bmi should calculate the bmi of every list within that list and calculate the average of that.
However, i get this error:
total_bmi += i[0]/i[1]
TypeError: 'float' object has no attribute 'getitem'
What is going wrong in this code?
You will want to fix add_person():
def add_person(self):
self.persons.append([self.lengte, self.gewicht])