Give random list objects attributes, python 3 - list

I am very new to programming. I have an assignment to design a game similar to minesweeper. So here's what I'm thinking right now on how to make the gameplan with hidden mines. First of all, I create a list which will be printed for the user to see (createPlan is the function which creates the plan, and showPlan is the function who shows the plan). Second, I'm thinking of creating another list which is identical to skapaPlan. However using methods to apply different attributes to the list object. For example,I want to apply a mine to list object nr x. How do I do that and still keep them "connected"? Thanks!
class Square:
def __init__(mine = False, empty = 0):
self.mina = mine
....
def createPlan(size, sign):
spelplan = []
for i in range(size):
gameplan.append([sign]*size)
return gameplan
def square_attribut(gameplan):
gomdplan = spelplan
(help)
def showPlan(gameplan):
i = 0
bracket = list(range(0,len(gameplan)))
rownr = [" "] + bracket
for row in [bracket]+gameplan:
print(rownr[i],end = " ")
i += 1
for square in row:
print(square,end = " ")
print()

Related

Groovy groupby List generated from Map values

This is the List that I have
List a = ["Sep->Day02->FY21;Inter01","Sep->Day02->FY21;Inter02","Sep->Day02->FY21;Inter03","Sep->Day01->FY21;Inter18","Sep->Day01->FY21;Inter19"]
I am trying to group this and generate a new string
Expected result
"Sep->Day02->FY21",Inter01:Inter03
"Sep->Day01->FY21",Inter18:Inter19
Tried to do this
List a = ["Sep->Day02->FY21;Inter01","Sep->Day02->FY21;Inter02","Sep->Day02->FY21;Inter03","Sep->Day01->FY21;Inter18","Sep->Day01->FY21;Inter19"]
List b = []
a.each{
b.add(it.split(";"))
}
def c = b.groupBy{it[0]}
println c
c.each{
k, v -> println "${v}"
}
I cant find a way to get the range of Inter01:Inter03 in the string. Please advice.
EDIT
The solution provided by Marmite works in the groovy console as expected. The list I am generating is from values in a map.
a.add(map[z]) Where z is the key.
When I am trying to use it, it gives me max and min method not found errors.
Tried using map[z].toString(). Still the same. Is the fact that the values are from a map affecting the same?
Code Snippet
Below is how I generate the map
def map = [:]
itr.each{
def Per = it.getMemberName("Period") //getMemberName is a product specific function . Sample output May
def Day = it.getMemberName("Day") //Day01 sample output
def Hour = it.getMemberName("Hour") //Interval01 sample output
def HourInt = it.getMemberName("Hour").reverse().take(2).reverse()
def Year = it.getMemberName("Years")
map.put(it.DataAsDate.format("dd/MM/yyyy")+"-"+Hour,Year+"->"+Per+"->"+Day+";"+HourInt)
}
Below is where I generate the List
def OSTinterval = OST.reverse().take(2).reverse() as Integer //This creates 01 out of Interval01
def OETinterval = OET.reverse().take(2).reverse() as Integer //This creates 03 out of Interval03
D1 = new Date(OSDDay)
D2 = new Date(OEDDay)
if (D1 == D2)
{
(OSTinterval..OETinterval).each
{inter ->
z = OSDDay+"-"+"Interval"+inter.toString().padLeft(2,'0')
coll.add(map[z].toString())
}
}
else
{
(D1..D2).each {
if (it == D1){
(OSTinterval..48).each
{inter ->
z = OSDDay+"-"+"Interval"+inter.toString().padLeft(2,'0')
coll.add(map[z].toString())
}
Basically you are looking for min and max after grouping.
I'm using a bit simplified data to focus on the processing:
def a = ['D02;I01','D02;I02','D02;I03','D01;I18','D01;I18']
println a.collect{it.split(";")}
.groupBy{it[0]}
.collect{k,v -> [k,v.collect {it[1]}]}
.collect{[it[0],"${it[1].min()}:${it[1].max()}"]}
.collect{it.join(',')}
returns a list of the keys with the min and max of the values
[D02,I01:I03, D01,I18:I18]
result after groupBy
[D02:[[D02, I01], [D02, I02], [D02, I03]], D01:[[D01, I18], [D01, I18]]]
The next collect removes the duplicated keys
[[D02, [I01, I02, I03]], [D01, [I18, I18]]]
Finally you find the min and max of the lists
[[D02, I01:I03], [D01, I18:I18]]

How to calculate all possibilities of very large string matrixes timely?

OK so let's say I have a situation where I have a bunch of objects in different classifications and I need to know the total possible combinations of these objects so I end up with an input that looks like this
{'raw':[{'AH':['P','C','R','Q','L']},
{'BG':['M','A','S','B','F']},
{'KH':['E','V','G','N','Y']},
{'KH':['E','V','G','N','Y']},
{'NM':['1','2','3','4','5']}]}
Where the keys AH, BG, KH, NM constitute groups, the values are list that hold individual objects and a finished group would constitute one member of each list, in this example KH is listed twice so each finished group would have 2 members of KH in it. I build something that handles this, it looks like this.
class Builder():
def __init__(self, data):
self.raw = data['raw']
node = []
for item in self.raw:
for k in item.keys():
node.append({k:0})
logger.debug('node: %s' % node)
#Parse out groups#
self.groups = []
increment = -2
while True:
try:
assert self.raw[increment].values()[0][node[increment][node[increment].keys()[0]]]
increment = -2
for x in self.raw[-1].values()[0]:
group = []
for k in range(0,len(node[:-1])):
position = node[k].keys()[0]
player = self.raw[k].values()[0][node[k][node[k].keys()[0]]]
group.append({position:player})
group.append({self.raw[-1].keys()[0]:x})
if self.repeatRemovals(group):
self.groups.append(group)
node[increment][node[increment].keys()[0]]+=1
except IndexError:
node[increment][node[increment].keys()[0]] = 0
increment-=1
try:
node[increment][node[increment].keys()[0]]+=1
except IndexError:
break
for group in self.groups:
logger.debug(group)
def repeatRemovals(self, group):
for x in range(0, len(group)):
for y in range(0, len(group)):
if group[x].values()[0] == group[y].values()[0] and x != y:
return False
return True
if __name__ == '__main__':
groups = Builder({'raw':[{'AH':['P','C','R','Q','L']},
{'BG':['M','A','S','B','F']},
{'KH':['E','V','G','N','Y']},
{'KH':['E','V','G','N','Y']},
{'NM':['1','2','3','4','5']}]})
logger.debug("Total groups: %d" % len(groups.groups))
The output of running this should clearly state my intended goal, if I have failed to do so in text. My concern is the time it takes to handle large classification of objects, when a classification has some 40 something objects in it, it is in the matrix three times and there are 7 other classifications with comparable object sizes. I think the numpy library could help me, but I am new to scientific programming and am not sure how to go about it, or if it would be worth it, could anyone provide some insight? Thank you.
Try this:
Remove duplicated values
Calculate all possibilities using permutation and factorial
Like that:
https://www.youtube.com/watch?v=Oc50d2GqXx0

Python: How to add tuple to an empty list?

I've looked around at other posts on here for a solution to my problem but none of them seems to work for me. I want to append a tuple to (what starts out as) an empty list. I've checked my code and it looks like whenever I try to just append my tuple it turns the list into a NoneType object. Here's what I've got:
list_of_pairs = []
for player in standings:
opponent = standings[standings.index(player) + 1]
matchup = (player[0:2] + opponent[0:2])
list_of_pairs = list_of_pairs.append(matchup)
print "ADDED TO LIST: " + str(list_of_pairs)
Each player in the standings list contains a tuple with four elements. I've tried using index and re-assigning list_of_pairs = [list_of_pairs, matchup], but nothing seems to be returning the right thing (i.e. [(player),(next player), (another player), (etc.)]. Every time I print "added to list" I just get ADDED TO LIST: None. I've checked matchup as well and it's definitely storing the first two values of the respective players fine. Any ideas?
This is because appending an element to a list returns None, which you are then printing when you do:
list_of_pairs = list_of_pairs.append(matchup)
print "ADDED TO LIST: " + str(list_of_pairs)
For example:
>>> a = []
>>> b = a.append('hello')
>>> print a
['hello']
>>> print b
None

i don't understand why list in object is shared with other objects

I make test python 2.7 code like below.
class test(object):
#initial 5*5 array with 1
value = [[1 for col in range(5)] for row in range(5)]
def __init__(self, name) :
self.name = name
test_list = [test("TEST"), test("test")]
test_list[0].value[0][0] = 0
print test_list[0].value[0][0]
print test_list[1].value[0][0]
What I expect is result like this
0
1
But Actual result is like
0 0
So it look like object "TEST" and "test" are sharing list.
If I change that code as below, then this problem doesn't appear.
class test(object):
def __init__(self, name) :
self.value = [[1 for col in range(5)] for row in range(5)]
self.name = name
test_list = [test("TEST"), test("test")]
test_list[0].value[0][0] = 0
print test_list[0].value[0][0]
print test_list[1].value[0][0]
I want to know why this two codes work different.
In the first example, you've made value a class variable, so it belongs to the actual class and is shared among all instances of the class. In the second example, value belongs to instances of the class, and a separate copy of value is made for each instance.

Creating a list of sums

I'm newbie in Python and I'm struggling in create a list of sums generated by a for loop.
I got an school assignment where my program have to simulate the scores of a class of blind students in a multiple choice test.
def blindwalk(): # Generates the blind answers in a test with 21 questions
import random
resp = []
gab = ["a","b","c","d"]
for n in range(0,21):
resp.append(random.choice(gab))
return(resp)
def gabarite(): # Generates the official answer key of the tests
import random
answ_gab = []
gab = ["a","b","c","d"]
for n in range(0,21):
answ_gab.append(random.choice(gab))
return(answ_gab)
def class_tests(A): # A is the number of students
alumni = []
A = int(A)
for a in range(0,A):
alumni.append(blindwalk())
return alumni
def class_total(A): # A is the number of students
A = int(A)
official_gab = gabarite()
tests = class_tests(A)
total_score = []*0
for a in range(0,A):
for n in range(0,21):
if tests[a][n] == official_gab[n]:
total_score[a].add(1)
return total_score
When I run the class_total() function, I get this error:
total_score[a].add(1)
IndexError: list index out of range
Question is: How I valuate the scores of each student and create a list with them, because this is what I want to do with the class_total() function.
I also tried
if tests[a][n] == official_gab[n]:
total_score[a] += 1
But I got the same error, so I think I don't fully understand how lists work in Python yet.
Thanks!
(Also, I'm not a English native-speaker, so please tell me if I couldn't be clear enough)
This line:
total_score = []*0
And in fact, any of the following lines:
total_score = []*30
total_score = []*3000
total_score = []*300000000
Cause total_score to be instantiated as an empty list. It doesn't even have a 0th index, in this case! If you'd like to initiate every value to x in a list of length l , the syntax would look more like:
my_list = [x]*l
Alternatively, instead of thinking about the size before-hand, you can use .append instead of trying to access a particular index, as in:
my_list = []
my_list.append(200)
# my_list is now [200], my_list[0] is now 200
my_list.append(300)
# my_list is now [200,300], my_list[0] is still 200 and my_list[1] is now 300