hey everyone, i am newbie to python, i was trying to write a script for the following problem statement(no it doesn't work..:( ).. here, is the code.. i have a few general querries about python also, plz help me out... thanks!

Problem D - Australian Voting
Australian ballots require that the voter rank the candidates in order of choice. Initially only the first choices are counted and if one candidate receives more than 50% of the vote, that candidate is elected. If no candidate receives more than 50%, all candidates tied for the lowest number of votes are eliminated. Ballots ranking these candidates first are recounted in favour of their highest ranked candidate who has not been eliminated. This process continues [that is, the lowest candidate is eliminated and each ballot is counted in favour of its ranked non-eliminated candidate] until one candidate receives more than 50% of the vote or until all candidates are tied.
Input
The input begins with a single positive integer on a line by itself indicating the number of the cases following, each of them as described below. This line is followed by a blank line, and there is also a blank line between two consecutive inputs.

The first line of input is an integer n <= 20 indicating the number of candidates. The next n lines consist of the names of the candidates in order. Names may be up to 80 characters in length and may contain any printable characters. Up to 1000 lines follow; each contains the contents of a ballot. That is, each contains the numbers from 1 to n in some order. The first number indicates the candidate of first choice; the second number indicates candidate of second choice, and so on.
Output
For each test case, the output must follow the description below. The outputs of two consecutive cases will be separated by a blank line.

The Output consists of either a single line containing the name of the winner or several lines containing the names of the candidates who tied.
Sample Input

1

3
John Doe
Jane Smith
Sirhan Sirhan
1 2 3
2 1 3
2 3 1
1 2 3
3 1 2

Output for Sample Input

John Doe

here's what i have till now:

``````#!/usr/bin/python

#Australian Voting
#start reading from line 76;sry for the long program;)
def process():
candidates=[]
voters=[]

#creating list of all candidates(each is an instance of Candidate class,
#with the name passed on to the __init__ function)
for l in range(no_of_candidates):
candidates.append(Candidate(line[:-1]))

#getting a list of all voters(i.e each item in voters is an instance of Voter class,
#with the rank_list passed on to the __init__function)
while True:
voters.append(Voter(line))

total=len(voters)

while True:
for i in candidates: #check if any of the candidates have got above 50%(forget the tie case for now.. ill do that later)
if (i.count/total>.5):
print i.name;break;break#is this correct?? i want to finish the program here..
#is there a goto syntax in pythonlike c++?

c=[]# will contain the 'count' values of each candidate, so to help in finding the least of them all.
for i in candidates:
c.append(i.count)

for i in candidates:
if i.count==lowest(c):# lowest fn is defined at line 42
eliminate(i)#line 71

def lowest(n):
lowest=n[0]
for i in n:
if i<lowest:
lowest=i
return lowest

class Candidate:
def __init__(self,name):
self.name=name
self.count=0

class Voter:
def __init__(self,rank_list):
self.rank_list=[]
for i in rank_list.split():
self.rank_list.append(int(i))
#self.top_candidate=self.rank_list[0]

for i in candidates:# all count values are initialized to 0
i.count=0
for i in voters:
candidates[(i.rank_list[0])-1].count+=1
#This was the kikarse line:)
#i.rank_list[0] is the first number in the ranking order, i.e the number for the first choice candidate.
#since the candidates are already stored in the 'candidates' list in that order, the count value for that particular
#candidate is thus incremented.

def eliminate(loser):
for j in voters:
if j.rank_list[0]==(candidates.index(loser)+1):
del j.rank_list[0]#this automatically makes the next person in the rank list the top candidate

f=file("input.txt")
for n in range(cases):
process()# line 5``````

my questions:
1.How do i declare multiple instances of a class in a single line?In lines 12-21, i want to create a list of all Candidates and Voter instances.. is there an easier way to do this? in c++ we can just write classname instance[20], and an array of 20 instances gets initialized, something similar in python?

2.How do i decide which functions should be a part of a class(i.e methods) and which ones should be normal functions? from what i know, i should define a function inside the class if it manipulates the attributes of the instances of that class... is this correct?for example, in the above code, should i have included the lower() function in the Candidate class? any pointer from you guys will be really helpful..

3.is it necessary to declare arrays(lists), as i have done in line 7 and 8?

4.in reference to line 29... if there are nested loops, say inner loop and outer loop. The inner loop has an if clause saying if condn is satisfied, it should break out of the full thing, like the inner and the outer loop. do i use break;break as i have done? any simpler way?

5.omg.. readline() function has given me nightmares.. can sum1 plz explain what it is all about.. like when it changes its value?
it seems when 'something is done' to readline(), that something gets done to the next line, but if we are comparing it to something, it doesn't increment..(does that make sense? sry i dnt know the right terminology)

for eg

``````while True:
print d``````

and

``````while True:
f.readline()# not doing anything.. just display what it contains,``````

whats the dif between above 2 codes?

also, if i replace lines 13 and 14 with:

``candidates.append(Candidate(f.readline()))``

will f.readline still provide the next lines as the loop goes on?

6.How do i divide properly? I know that 6/5 will return 1 and 6/5.0 will return 1.2 but what if i don't know the actual numbers? what if i want to divide two variables like in line 28.. i want it to do proper decimal division.. not just return the quotient.. how do i do it?

7. In almost all the loops, i have used 'i' as the iterator.. like
for i in blah blah: etc but if i have two loops in the same block, should use i and j (two dif iterators?

phew!! i hope all that makes sense.. if i can get the answers to these questions i can clear up a lot of things, then i will rewrite the script. Though if you guys want, plz give suggestions to how to improve the program..

I can tell you've come from C++. You're making things much harder than they need be. Python has such a simple syntax, yet you're clogging it up by doing things similar to how you would in C++.

For #1, in C++ you couldn't just write Candidate[20] anyways because that doesn't store the names for each instance like you're trying to here by reading it from a file. However, you can simplify that whole process considerably:

``````# read the whole file as a list of lines
# we use this list comprehension to trim leading and trailing whitespace
everything = [line.strip() for line in f.readlines()]

# everything up to the no_of_candidates index, again,
# using a list comprehension to make the instances
candidates = [Candidate(name) for name in everything[:no_of_candidates]]

# and the same for the voters
voters = [Voter(name) for name in everything[no_of_candidates:]]``````

#2
I don't get your question. I see no lower function in your code. If you're referring to the lowest function, then I'd say it's best how it is. It shouldn't be a method of the Candidate class as it needs to handle count values from all the other Candidate instances too. Best to keep it the way it is. If it was something that performed operations on only that specific instance's values, then I'd make it a method, but that's not the case.

#3
Of course you must initialize the lists. You're appending stuff to them, and you can't do so if the list you're appending to hasn't been initialized yet. However, my above code makes lines 7 - 21 obsolete.

#4
There is no goto (luckily). Seeing as you're trying to exit the whole function, you could just go ahead and say `return` . You don't need to pass it anything to return - it just automatically terminates that function. If given nothing, it technically returns None, but seeing as you're not trying to capture the return value, that doesn't make any difference. The other (and at most times), cleaner, solution for exiting the program is to `import sys` at the top of your code and then later call `sys.exit(0)` to terminate the Python script at an arbitrary point (return value zero, like in C++).

#5
What's the difference? Well one stores the value returned from `f.readline()` into the variable d and the other doesn't store it... I don't get what you don't understand about it. Calling readline on a file object without a parameter just reads until it encounters the next newline character, then returns that along with the \n ...

#6
That was already answered in another thread you made. In Python 2.x and below, dividing integers returns an integer result. Likewise with floats. Etc...

#7
If you're referring to something like:

``````def count_votes():
for i in candidates:# all count values are initialized to 0
i.count=0
for i in voters:
candidates[(i.rank_list[0])-1].count+=1``````

Then it doesn't matter. i will be reset for iterating in the second for loop. If they're nested though, then you'll need to use different variable names, like:

``````for i in range(10):
for k in range(5):
print i, k``````

I hope that answered some stuff for you!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge.