Question

Python recursive design question: Background: The class vote creates vote objects. A vote is either a...

Python recursive design question:
Background
:

The class vote creates vote objects. A vote is either a blue vote, a red vote, or a purple. This information is stored in the "value" attribute.

The function Poll returns a list of random votes. In the code below, some_poll is a list of 32 random votes.

some_poll = Poll(32)


# -----------------------------------------------------
import random
# -----------------------------------------------------
#
# Return a list of n random votes
#
# -----------------------------------------------------
def Poll(n=16):
    #
    # A random vote, if value is not specified.  Value can be either 'red', 'blue', or 'purple'
    #
    class Vote:
        def __init__(self, value=None):
            if value is None:
                r = random.random()
                if 0 <= r < 0.45:
                    self.value = 'red'
                elif 0.45 <= r < 0.9:
                    self.value = 'blue'
                else:
                    self.value = 'purple'
            else:
                if value not in ('red', 'blue', 'purple'):
                    raise Exception('Invalid vote: ' + value)
                self.value = value

        def __eq__(self, b):
            return self.value == b.value

        def __str__(self):
            return self.value

    return [Vote() for i in range(n)]


# -----------------------------------------------------

Your task is to write a recursive designed function find_winner_fast so that it can correctly find a winner (if there is one) in time Θ(? log ?).

  • A winner of a poll is a color that occurs more than 50%.
  • If all colors occur less than 50%, there's no winner, and find_winner_fast returns None.
  • find_winner should run in Θ(? log ?), where ? is the number of votes in a_poll.

Hint: suppose that w1 is the winner of half of the votes, and w2 is the winner of the other half of the votes. Will knowing w1 and w2 help you determine the winner of all the votes?

  • If w1 is equal to w2, who would be the winner of all votes?
  • If w1 is not equal to w2, how would you find the winner? Is the winner w1 or w2? Can it be someone else?

Note

  • You can store votes, but cannot directly create a vote.
  • You can compare two votes using equality. See the example of usage.

Thinking about the recursive design

  • a_poll = [ left. ][ right ] 100 votes (n votes) 50 50
  • blue is the winner on left. This means blue must have at least 25 votes on left.
  • blue is the winner on right. This means blue must also have at least 25 votes on the right.
  • Altogether, blue must have at least 50 votes on both left and right. This means blue is the winner overall.


def find_winner_fast(a_poll):
pass

Homework Answers

Answer #1

Rasw_code: (my be added to your code):

# find_winner_fast recursive function
def find_winner_fast(a_poll):
# temporary vote_type tuple for comparing the value of Vote object
vote_type = ("red", "blue", "purple", None)
# list for counting votes
vote_count = [0, 0, 0, 0]
# winner variable for storing winner
winner = None
# condition for breaking recusursion
if len(a_poll) == 1:
# finding the corresponding vote count of Vote object and incrementing vote count by 1
vote_count[vote_type.index(a_poll[0].value)] += 1
winner = a_poll[0].value
# returning vote_count and winner
return vote_count, winner
else:
# calling find_winner_fast by slicing the a_poll: second element to last element
(vote_count, winner) = find_winner_fast(a_poll[1:])
# finding the corresponding vote count of first Vote object and incrementing vote count by 1
vote_count[vote_type.index(a_poll[0].value)] += 1

# for loop for finding the winner by iterating over vote_count
for index in range(len(vote_count)):
# checking if any votes count is greater than half of total votes
if vote_count[index] > len(a_poll)/2:
# checking if votes count is greater than votes count of current winner
if vote_count[index] > vote_count[vote_type.index(winner)]:
winner = vote_type[index]

# checking if final votes count is less than half of total votes   
if vote_count[vote_type.index(winner)] < len(a_poll)//2:
winner = None
# returing votes count and winner
return (vote_count, winner)

(votes_count, winner) = find_winner_fast(some_poll)
print("winner: ", winner)
print("red: ", votes_count[0], ", blue: ", votes_count[1], ", purple: ", votes_count[2], sep = "")

if you want to return a winner , even it's votes are not greater than half of votes, then just remove last if statement (lines 67 and 68)

Know the answer?
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for?
Ask your own homework help question
Similar Questions
Create an add method for the BST (Binary Search Tree) class. add(self, new_value: object) -> None:...
Create an add method for the BST (Binary Search Tree) class. add(self, new_value: object) -> None: """This method adds new value to the tree, maintaining BST property. Duplicates must be allowed and placed in the right subtree.""" Example #1: tree = BST() print(tree) tree.add(10) tree.add(15) tree.add(5) print(tree) tree.add(15) tree.add(15) print(tree) tree.add(5) print(tree) Output: TREE in order { } TREE in order { 5, 10, 15 } TREE in order { 5, 10, 15, 15, 15 } TREE in order {...
convert to python 3 from python 2 from Tkinter import * # the blueprint for a...
convert to python 3 from python 2 from Tkinter import * # the blueprint for a room class Room(object): # the constructor def __init__(self,name,image): # rooms have a name, exits (e.g., south), exit locations (e.g., to the south is room n), # items (e.g., table), item descriptions (for each item), and grabbables (things that can # be taken and put into the inventory) self.name = name self.image = image self.exits = {} self.items = {} self.grabbables = [] # getters...
I NEED TASK 3 ONLY TASK 1 country.py class Country:     def __init__(self, name, pop, area, continent):...
I NEED TASK 3 ONLY TASK 1 country.py class Country:     def __init__(self, name, pop, area, continent):         self.name = name         self.pop = pop         self.area = area         self.continent = continent     def getName(self):         return self.name     def getPopulation(self):         return self.pop     def getArea(self):         return self.area     def getContinent(self):         return self.continent     def setPopulation(self, pop):         self.pop = pop     def setArea(self, area):         self.area = area     def setContinent(self, continent):         self.continent = continent     def __repr__(self):         return (f'{self.name} (pop:{self.pop}, size: {self.area}) in {self.continent} ') TASK 2 Python Program: File: catalogue.py from Country...
0. Introduction. In this laboratory assignment, you will write a Python class called Zillion. The class...
0. Introduction. In this laboratory assignment, you will write a Python class called Zillion. The class Zillion implements a decimal counter that allows numbers with an effectively infinite number of digits. Of course the number of digits isn’t really infinite, since it is bounded by the amount of memory in your computer, but it can be very large. 1. Examples. Here are some examples of how your class Zillion must work. I’ll first create an instance of Zillion. The string...
Write a program in python that reads in the file quiztext (txt) and creates a list...
Write a program in python that reads in the file quiztext (txt) and creates a list of each unique word used in the file, then prints the list. Generate a report that lists each individual word followed by the number of times it appears in the text, for example: Frequency_list = [('was', 3), ('bird',5), ('it', 27)….] and so on. Note: Notice the structure: a list of tuples. If you're really feeling daring, Google how to sort this new list based...
Homework Draw class diagrams for your HW4 - the Tetris Game shown below: Part 1: UML...
Homework Draw class diagrams for your HW4 - the Tetris Game shown below: Part 1: UML As a review, Here are some links to some explanations of UML diagrams if you need them. • https://courses.cs.washington.edu/courses/cse403/11sp/lectures/lecture08-uml1.pdf (Links to an external site.) • http://creately.com/blog/diagrams/class-diagram-relationships/ (Links to an external site.) • http://www.cs.bsu.edu/homepages/pvg/misc/uml/ (Links to an external site.) However you ended up creating the UML from HW4, your class diagram probably had some or all of these features: • Class variables: names, types, and...