Реализуйте условие в массив - PullRequest
1 голос
/ 28 апреля 2020

Я пытаюсь внедрить другое условие в мою программу, но не могу понять это.

Вот код:

print ("Welcome to the winning card program.")
year_one=[]
year_one.append(eval(input("Enter the salary individual 1 got in year 1:  ")))
year_one.append(eval(input("Enter the salary individual 2 got in year 1:  ")))
 if year_one[0]==year_one[1]:
   print("Error. The amount are the same, please reenter information.")
year_two=[]
year_two.append(eval(input("Enter the salary individual 1 got in year 2:  ")))
year_two.append(eval(input("Enter the salary individual 2 got in year 2:  ")))
 if year_two[0]==year_two[1]:
   print("Error. The amount are the same, please reenter information.")
year_three=[]
year_three.append(eval(input("Enter the salary individual 1 got in year 3:  ")))
year_three.append(eval(input("Enter the salary individual 2 got in year 3:  ")))
  if year_three[0]==year_three[1]:
   print("Error. The amount are the same, please reenter information.")
year_four=[]
year_four.append(eval(input("Enter the salary individual 1 got in year 4:  ")))
year_four.append(eval(input("Enter the salary individual 2 got in year 4:  ")))
 if year_four[0]==year_four[1]:
  print("Error. The amount are the same, please reenter information.")
year_five=[]
year_five.append(eval(input("Enter the salary individual 1 got in year 4:  ")))
year_five.append(eval(input("Enter the salary individual 2 got in year 4:  ")))
 if year_five[0]==year_five[1]:
  print("Error. The amount are the same, please reenter information.")
individual1_total=year_one[0]+year_two[0]+year_three[0]+year_four[0]+year_five[0]
individual2_total=year_one[1]+year_two[1]+year_three[1]+year_four[1]+year_five[1]
 if (individual1_total>individual2_total):
  print("Individual one has the highest salary.")
 elif (individual2_total>individual1_total):
  print("Individual two has the highest salary.")

Если зарплата для двух человек за определенный год точно такая же, вы должны напечатать ошибку и заставить пользователя ввести обе зарплаты снова на этот год. (Условие - зарплаты не должны быть одинаковыми).

Я с нетерпением жду отзывов каждого.

Заранее спасибо.

Ответы [ 2 ]

0 голосов
/ 28 апреля 2020

Хорошо, так что, опираясь на surge10, это более полная замена вашего кода. Я разбил все части на функции и сделал словарь своей базой данных в памяти.

total_years = 5
years = {}

def dict_key(year, userId):
    return '{}:{}'.format(year, userId)

def get_user_data(year, userId):
    key = dict_key(year, userId)
    years[key] = float(input("Enter the salary individual {} got in year {}:".format(userId, year)))

def get_year_salaray(year, userId):
    key = dict_key(year, userId)
    return years[key]

def any_salaries_match(year, userIds):
    for userLeft in userIds:
        salary_left = get_year_salaray(year, userLeft)
        for userRight in userIds:
            if userLeft != userRight:
                salary_right = get_year_salaray(year, userRight)
                if salary_left == salary_right:
                    return True

def get_user_totals(userId):
    total = 0
    for key, value in years.items():
        if ':{}'.format(userId) in key:
            total += value
    return total

for x in range(total_years):
    year = x + 1
    data_invalid = True
    while data_invalid:
        userOne = 1
        userTwo = 2
        get_user_data(year, userOne)
        get_user_data(year, userTwo)

        if any_salaries_match(year, [userOne, userTwo]):
            print("Error. The amount are the same, please reenter information.")
        else:
            data_invalid = False

userOneTotal = get_user_totals(1)
userTwoTotal = get_user_totals(2)

if (userOneTotal>userTwoTotal):
  print("Individual one has the highest salary.")
elif (userTwoTotal>userOneTotal):
  print("Individual two has the highest salary.")
0 голосов
/ 28 апреля 2020

Поскольку мы проверяли в течение пяти разных лет, я использовал все oop в течение этих пяти лет. Позже мы можем вернуть его в отдельные годы.

print ("Welcome to the winning card program.")
years=[]

for x in range(5):

    # range starts at zero so add one all the time
    # to start it at one
    y = str(x + 1)

    errors = True
    while errors:

        salary_one = input("Enter the salary individual 1 got in year " + y + ":  ")
        salary_two = input("Enter the salary individual 2 got in year " + y + ":  ")

        if salary_one == salary_two:
            print("Error. The amount are the same, please reenter information.")
            errors = True
        else:
            years.append([salary_one, salary_two])
            errors = False

year_one = years[0]
year_two = years[1]

...
print(year_one)
print(year_two)
...
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...