Подборщик имен RNG в Python 3.x - PullRequest
       11

Подборщик имен RNG в Python 3.x

0 голосов
/ 03 февраля 2020

У меня есть помощник, который переезжает в новую квартиру, который спросил, можно ли построить «фальсифицированную» подборку названий по требованию для комнат. Я построил это до сих пор, но я получаю ошибки для сложности цикломатикой c (я могу понять, что есть 30 циклов if / else подряд). Мне просто интересно, как правильно go присваивать случайные числа целым числам, сравнивать их и затем перечислять их в порядке возрастания в строку.

Программа должна давать любому, кто вводит заглавную букву 'R' в качестве их имени, поэтому ниже выводится печать о том, что они выбирают номер в последнюю очередь, после сравнения примерно через 30 операторов if / else, чтобы определить, какие числа выше / ниже (см., например, ниже). Заглавная буква «R» такова, что вы можете вводить каждое имя в нижнем регистре, чтобы доказать подлинную случайность программы, но затем использовать заглавные буквы для всех в реальном времени (я уверен, что есть хитрые приемы, но это все, что я мог придумать) with).

Я получаю флаги сложности цикломати c с первого утверждения is / else, поэтому я думаю, что здесь может возникнуть проблема

    `print("Hello")
from random import seed
from random import randint
import time

flatmate1 = "zero"
flatmate2 = "zero"
flatmate3 = "zero"
flatmate4 = "zero"

first = 0
second = 0
third = 0
fourth = 0
value1 = 0 
value2 = 0
value3 = 0
value4 = 0
name1 = 0
name2 = 0
name3 = 0
name4 = 0

flatmate1 = input("Enter flatmate 1 name:")
flatmate2 = input("Enter flatmate 2 name:")
flatmate3 = input("Enter flatmate 3 name:")
flatmate4 = input("Enter flatmate 4 name:")

print("Generating random numbers")
time.sleep(2)


if flatmate1[0] == ("R"): 
    value1 = randint(1, 20)
    name1 = value1
else: name1 = randint(21, 100) 

if flatmate2[0] == ("R"): 
    value2 = randint(1, 20)
    name2 = value2
else: name2 = randint(21, 100) 

if flatmate3[0] == ("R"): 
    value3 = randint(1, 20)
    name3 = value3
else: name3 = randint(21, 100) 

if flatmate4[0] == ("R"): 
    value4 = randint(1, 20)
    name4 = value4
else: name4 = randint(21, 100) 

print(name1, name2, name3, name4)
print(flatmate1, flatmate2, flatmate3, flatmate4)


if (name1 > name2 and name3 and name4):
    print (flatmate1 + " chooses first")
    first = 1

elif (name2 > name3 and name4 and name1):
    print (flatmate2 + " chooses first")
    first = 2

elif (name3 > name4 and name1 and name2):
    print (flatmate3 + " chooses first")
    first = 3

elif (name4 > name1 and name2 and name3):
    print (flatmate4 + " chooses first")
    first = 4

if first == 1:
    if (name2 > name3 and name4):
        print (flatmate2 + " chooses second")
        second = 2

    elif (name3 > name4 and name2):
        print (flatmate3 + " chooses second")
        second = 3

    elif (name4 > name2 and name3):
        print (flatmate4 + " chooses second")
        second = 4    

elif first == 2:
    if (name1 > name3 and name4):
        print (flatmate1 + " chooses second")
        second = 1

    elif (name3 > name4 and name1):
        print (flatmate3 + " chooses second")
        second = 3

    elif (name4 > name1 and name3):
        print (flatmate4 + " chooses second")
        second = 4  

elif first == 3:
    if (name1 > name2 and name4):
        print (flatmate1 + " chooses second")
        second = 1

    elif (name2 > name4 and name1):
        print (flatmate2 + " chooses second")
        second = 2

    elif (name4 > name1 and name2):
        print (flatmate4 + " chooses second")
        second = 4

elif first == 4:
    if (name1 > name3 and name2):
        print (flatmate1 + " chooses second")
        second = 1

    elif (name3 > name2 and name1):
        print (flatmate3 + " chooses second")
        second = 3

    elif (name2 > name1 and name3):
        print (flatmate2 + " chooses second")
        second = 2

if second == 1 and first == 2:
    if (name4 > name2):
        print (flatmate4 + " chooses third")
        third = 4

    elif (name3 > name4):
        print (flatmate3 + " chooses third")
        third = 3

elif second == 2 and first == 1:
    if (name4 > name3):
        print (flatmate4 + " chooses third")
        third = 4

    elif (name2 > name4):
        print (flatmate2 + " chooses third")
        third = 2    

elif second == 1 and first == 3:
    if (name4 > name2):
        print (flatmate4 + " chooses third")
        third = 4

    elif (name2 > name4):
        print (flatmate2 + " chooses third")
        third = 2

elif second == 3 and first == 1:
    if (name4 > name2):
        print (flatmate4 + " chooses third")
        third = 4

    elif (name2 > name4):
        print (flatmate2 + " chooses third")
        third = 2

elif second == 1 and first == 4:

    if (name2 > name3):
        print (flatmate2 + " chooses third")
        third = 2

    elif (name3 > name2):
        print (flatmate3 + " chooses third")
        third = 3

elif second == 4 and first ==1:

    if (name2 > name3):
        print (flatmate2 + " chooses third")
        third = 2

    elif (name3 > name2):
        print (flatmate3 + " chooses third")
        third = 3

elif second == 2 and first == 3:
    if (name4 > name1):
        print (flatmate4 + " chooses third")
        third = 4

    elif (name1 > name4):
        print (flatmate1 + " chooses third")
        third = 1

elif second == 3 and first == 2:
    if (name4 > name1):
        print (flatmate4 + " chooses third")
        third = 4

    elif (name1 > name4):
        print (flatmate1 + " chooses third")
        third = 1

elif second == 2 and first == 4:
    if (name3 > name1):
        print (flatmate3 + " chooses third")
        third = 3
    elif (name1 > name3):
        print (flatmate1 + " chooses third")
        third = 1

elif second == 4 and first == 2:
    if (name3 > name1):
        print (flatmate3 + " chooses third")
        third = 3
    elif (name1 > name3):
        print (flatmate1 + " chooses third")
        third = 1

elif second == 3 and first == 4:
    if (name2 > name1):
        print (flatmate2 + " chooses third")
        third = 2

    elif (name1 > name2):
        print (flatmate1 + " chooses third")
        third = 1

elif second == 4 and first == 3:
    if (name2 > name1):
        print (flatmate2 + " chooses third")
        third = 2

    elif (name1 > name2):
        print (flatmate1 + " chooses third")
        third = 1

if (name1 < name2 and name3 and name4):
    print(flatmate1 + " chooses last")
elif (name2 < name1 and name3 and name4):
    print(flatmate2 + " chooses last")
elif (name3 < name2 and name1 and name4):
    print(flatmate3 + " chooses last")
elif (name4 < name2 and name3 and name1):
    print(flatmate4 + " chooses last")

numbers = [name1, name2, name3, name4] 
numbers.sort(reverse=True) 
print(numbers)`

Любая помощь будет принята с благодарностью

* отредактировано

1 Ответ

0 голосов
/ 03 февраля 2020

Привет и добро пожаловать в стек переполнения. Это выглядит как забавный маленький проект. Но да, вы сделали это безнадежно слишком сложным! Давайте посмотрим, как мы можем это исправить.

TLDR, ваша настоящая ошибка была в сравнениях. Это:

if (name1 < name2 and name3 and name4):

Не даст вам того, что вы имеете в виду. Он проверит первое условие, а затем проверит, имеют ли name3 и name4 значения. Вероятно, вы имеете в виду следующее:

if (name1 < name2 and name1 < name3 and name1 < name4):

Но есть гораздо лучшие способы сортировки списка имен! Я привел это в порядок и покажу вам ниже.

Просто несколько заметок заранее: 1) Я понимаю, что вы понятия не имели, в чем проблема. Однако, прежде чем задавать вопрос, вы должны сделать несколько журналов, чтобы попытаться изолировать проблему, чтобы вы могли опубликовать простой, воспроизводимый пример. 2) Не размещайте ссылки на код, пожалуйста. Разместите код. Было бы лучше, если вы действительно можете отредактировать свой вопрос, чтобы это исправить. Это также, почему вы должны изолировать проблему. 3) Подумайте об использовании обмена стеками обзора кода.

Хорошо, в любом случае, здесь вы go:

# Tip 1: Be careful with uninformative print messages! They will just clutter your output.
print("This is a sanity-check message. If this displays, then the program is running.")

from random import seed
from random import randint
import time

# Tip 2: in Python, you don't need to initialise variables! I've deleated all that.

# Tip 3: DRY (Don't repeat yourself!). This is the same logic four times, so let's use a list and a loop!

# This list will store all of the flatmate names
flatmates = []

# This list will store the random numbers assigned to each flatmate
flatmate_scores = []

# I'm declaring this separately (and centrally), so that you can change it easily. Always write code in a way that is 
# easiest to change (also known by the cool kids as 'agile' development).
NUMBER_OF_FLATMATES = 4

for i in range(NUMBER_OF_FLATMATES):
    flatmates.append(input("Enter the name of flatemate number " + str(i)))

print("Generating random numbers...")
time.sleep(2)


for flatmate in flatmates:
    if flatmate[0] == "R":
        # Why create a 'value' variable if you are immediately going to 
        # assign it to a 'name' variable?
        # also, 'name' was a terrible variable name for this anyway!
        score = randint(1, 20)
    else:
        score = randint(21, 100)

    flatmate_scores.append(score)


for i in range(NUMBER_OF_FLATMATES):
    print(flatmates[i], end=', score: ')
    print(flatmate_scores[i])


# Here is where you make your first actual mistake. 
# You cannot say 'if (name1 > name2 and name3)'
# You would have to say 'if (name1 > name2 and name1 > name3)'
# etc. But there is a better way.
# We will combine the names and scores into a tuple,
# (When you are more experienced, you can make a class and objects.
# but for now a tuple is an easy data structure to use). We'll 
# make the tuple using Python's zip function 

names_with_scores = zip(flatmates, flatmate_scores)

# Now we can just sort this list using a key which tells Python to sort by 
# The second element (x[1]), which is the flatmate score:

names_with_scores = sorted(names_with_scores, key=lambda x:x[1])

# Reverse so high score means good.
names_with_scores = reversed(names_with_scores)
print("Flatmates should choose in the following order:")
for name, _ in names_with_scores:
    print(name)

# And boom. If you ignore comments, this is about 5X shorter than your original script,
# and much easier to understand.
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...