Я создал калькулятор голосования, но кажется, что одна строка кода портит другой раздел. Это мои переменные? - PullRequest
0 голосов
/ 01 августа 2020

У меня есть довольно сложный (для меня, но, вероятно, простой для python экспертов) код из моего класса python, который анализирует местные выборы: подсчитывает голоса, а затем выводит результаты (кандидаты + голоса, округа + голоса , победитель на выборах). Результаты, которые я получил, точны ... за исключением одной части, которую я прокомментировал в коде с помощью "#! Что-то в этой строке приводит к тому, что подсчет победителей / победителей и процент побед были выброшены!" С этой предыдущей строкой кода результаты победителя выборов под ней не печатаются (в разделе печатается, а вот имя победителя и итоги голосов - нет). Если я удалю этот фрагмент кода, неправильный округ будет идентифицирован как "округ с наибольшим количеством голосов" (наибольший_county; Арапахо вместо Денвера, где Денвер является правильным округом с наибольшим количеством голосов), но тогда победителем выборов будет напечатано правильно.

Два раздела кода, которые печатают эти фрагменты информации - округ с наибольшим количеством голосов и победитель выборов - представляют собой практически один и тот же код, только с разными переменными. Мне интересно, может быть, какая-то переменная, которую я там объявил, удваивается или увеличивается дважды, но я не могу понять, что это может быть. Может, переменная "голосов"? Любая помощь приветствуется.

# snip some code

# Candidate Options list and candidate votes dictionary.
candidate_options = []
candidate_votes = {}

# 1: Create a county list and county votes dictionary.
counties = []
county_votes = {}

# Track the winning candidate, vote count and percentage
winning_candidate = ""
winning_count = 0
winning_percentage = 0

# 2: Track the largest county and county voter turnout.
largest_county = ""
largest_count = 0
largest_percentage = 0

# snip some code

        if candidate_name not in candidate_options:

            # Add the candidate name to the candidate list.
            candidate_options.append(candidate_name)

            # And begin tracking that candidate's voter count.
            candidate_votes[candidate_name] = 0

        # Add a vote to that candidate's count
        candidate_votes[candidate_name] += 1

        # 4a: Write a decision statement that checks that the county does not match any existing county in the county list.
        if county_name not in counties:

            # 4b: Add the existing county to the list of counties.
            counties.append(county_name)

            # 4c: Begin tracking the county's vote count.
            county_votes[county_name] = 0

        # 5: Add a vote to that county's vote count.
        county_votes[county_name] += 1

# snip some code

            winning_count = votes
            largest_county = county_name
            largest_percentage = vote_percentage
    
    # 7: Print the county with the largest turnout to the terminal.
    largest_county_summary = (
        f"-------------------------\n"
        f"County with largest turnout: {largest_county}\n"
        f"-------------------------\n")
    print(largest_county_summary)
    
# snip some code

        # Determine winning vote count, winning percentage, and candidate.
        if (votes > winning_count) and (vote_percentage > winning_percentage):
            winning_count = votes
            winning_candidate = candidate_name
            winning_percentage = vote_percentage

# snip some code

1 Ответ

1 голос
/ 01 августа 2020

Кажется, ошибка здесь:

if (votes > largest_count) and (vote_percentage > largest_percentage):
    winning_count = votes
    largest_county = county_name
    largest_percentage = vote_percentage

Вместо winning_count = votes следует назначить largest_count = votes

...