2017-12-10 9 views
1

목록에 3 명이 대기열에 추가되어 각 사람의 이름이 맨 위에 표시되지만 이름없이 결과 하나만 얻을 수있었습니다 :대기열 데이터 구조 목록 (Python)에서 항목 호출하기

Contacting the following 
Phone answered: Yes 
Booked an appointment: No 
Reshedule an appointment again. 

내가 그들의 이름과 3 개 출력, 'names' 내부에 저장된 정보에서 각 사람 하나를 표시하는 출력을 만들고 싶어하고, 각각의 이름이 두 번 나타나지 않습니다.

대기열을 사용하여 목록에 따라 우선 순위를 정하고 싶습니다. 그래서 순서대로 나열하려고합니다. if와 elif는 임의의 생성자에 따라 두 범주 중 하나에 속하는 조건입니다. 이제는 내부에 이름을 포함시키는 방법이 정의되지 않은 것입니다.

코드

import random 

class Queue: 
    def __init__(self): 
     self.container = [] 

    def isEmpty(self): 
     return self.size() == 0 

    def enqueue(self, item): 
     self.container.append(item) 

    def dequeue(self): 
     self.container.pop(0) 

    def size(self): 
     return len(self.container) 

    def peek(self) : 
     return self.container[0] 

names = ["Alvin", "James", "Peter"] 

# Enqueuing 

q = Queue() 
q.enqueue(random.choice(names)) 

# Dequeuing and Printing 
print("Contacting the following:\n" + "\n".join(q.container)) # unsure about this 




for i in range(q.size()): 

    answered = random.randint(0,1) 
    booked = random.randint(0, 1) 

    if(answered == 1 and booked == 1): 
     print("Now Calling -" + (q.names)) # unsure about this 
     print("Phone answered: Yes") 
     print("Booked an appointment: Yes") 
     print("Booking successful.") 

    elif(answered==1 and booked==0): 
     print("Now Calling -" + (q.names)) # unsure about this 
     print("Phone answered: Yes") 
     print("Booked an appointment: No") 
     print("Reshedule an appointment again.") 

    elif(answered == 0): 
     print("Now Calling -" + (q.names)) # unsure about this 
     print("Phone answered: No") 
     print("Reshedule a callback.") 

    q.dequeue() 

예 원하는 출력 :

Contacting the following 
Alvin 
James 
Peter 

Now Calling - James 
Phone answered: No 
Reshedule a callback. 
+0

했다 https://stackoverflow.com/questions/47736687/showing-names-in-the-queue-data-structure # 47736687) 삭제했을 때 ... –

+0

죄송합니다. 나는 내 자신을 알아 내려고 노력할 것이라고 생각했다. 출력에 – John

답변

1

나는 당신의 큐 class에 변화의 몇했다. 주로 .dequeue 메서드는 팝하는 항목을 반환하지 않으므로 None의 기본값을 반환합니다.

는 또한 그래서 당신은 내장 len 기능 Queue 인스턴스를 전달할 수 __len__.size 방법을 변경했습니다. 그리고 for 루프에서 쉽게 사용할 수있는 iter 메서드를 사용하거나 .join으로 전달하십시오. 또한 .isEmpty.is_empty으로 변경하여 Python의 PEP-0008 스타일 가이드를 준수했습니다.

반복하지 않고 각 이름을 임의로 대기열에 추가하려면 random.choice을 원하지 않으므로 여기에 입력하십시오. 대신 random.shuffle을 사용할 수 있습니다. 다른 옵션은 random.sample을 사용하는 것이지만 목록에서 부분 선택을 할 때 더 적합합니다.

from random import seed, shuffle, randrange 

# Seed the randomizer so we can reproduce results while testing 
seed(9) 

class Queue: 
    def __init__(self): 
     self.container = [] 

    def __len__(self): 
     return len(self.container) 

    def is_empty(self): 
     return len(self) == 0 

    def enqueue(self, item): 
     self.container.append(item) 

    def dequeue(self): 
     return self.container.pop(0) 

    def peek(self) : 
     return self.container[0] 

    def __iter__(self): 
     return iter(self.container) 

names = ["Alvin", "James", "Peter"] 

# Enqueuing 
q = Queue() 

# Make a temporary copy of the names that we can 
# shuffle without affecting the original list 
temp = names.copy() 
shuffle(temp) 

# Put the shuffled names onto the queue 
for name in temp: 
    q.enqueue(name) 

# Dequeuing and Printing 
print("Contacting the following") 
print('\n'.join(q)) 
#for name in q: 
    #print(name) 

while not q.is_empty(): 
    name = q.dequeue() 
    print('\nNow Calling -', name) 

    answered = randrange(2) 
    booked = randrange(2) 

    if answered: 
     print("Phone answered: Yes") 
     if booked: 
      print("Booked an appointment: Yes") 
      print("Booking successful.") 
     else: 
      print("Booked an appointment: No") 
      print("Reshedule an appointment again.") 
    else: 
     print("Phone answered: No") 
     print("Reshedule a callback.") 

위의 코드에서 출력

Contacting the following 
Alvin 
Peter 
James 

Now Calling - Alvin 
Phone answered: Yes 
Booked an appointment: No 
Reshedule an appointment again. 

Now Calling - Peter 
Phone answered: No 
Reshedule a callback. 

Now Calling - James 
Phone answered: Yes 
Booked an appointment: Yes 
Booking successful. 

나는 당신이 당신의 코드에서 그 목적을 위해 .join을 사용하기 때문에, 모든 이름을 인쇄 할 수

print('\n'.join(q)) 

을 사용했다. 그러나 나는 또한 간단한 for 루프를 사용하여 다른 방법을 보여,하지만 난 그것을 주석 : (나는 당신의 [이전 질문]에 대한 답변을 작성하는 중간에

for name in q: 
    print(name) 
+0

이 있으면 목록에서'names = [ "Alvin", "James", "Peter"] 대신 Alvin, Peter, James를 표시합니다. 내가 정리할 수있는 방법이 있니? – John

+0

또한 동일한 결과가 계속 발생하며 자체가 뒤섞이는 것처럼 보입니다. – John

+0

@ 존 여러분의 코드는'random.choice'를 사용합니다. 그래서 임의의 순서로 이름을 큐에 추가하고 싶다고 생각했습니다.이름을 원래의 순서대로 대기열에 넣고 싶으면'names'를 대기열에 넣고'temp' 물건을 제거하십시오. 내 코드는 임의의 이름이 반복되지 않도록'random.shuffle'을 사용합니다. 'seed (9)'로 랜덤 숫자를 파종하기 때문에 각 런에서 동일한 랜덤 순서를 선택합니다. 그 라인을 주석 처리하면 매번 다른 임의 순서가 선택됩니다. –