Home > database >  Problem with dictionary exercise (Python)
Problem with dictionary exercise (Python)

Time:09-22

I made a code, but it's showing the following error: nailshable type: 'list' Question statement:

Gohan most certainly asked you to write a program to check that the distances marked by the two were equal. Attention: Realize that the stones can reach the same distance, so you must ensure that they reach a certain distance the same amount of times.

Note: It is mandatory to use dictionaries for the question. The use of the sort and count functions is prohibited.

Note: The order of distances is not relevant

The program must receive an initial integer that represents the amount of stones thrown by each one.

If the two lists are the same, even if in different order, print:

“Dale Gohan!”

And if not, print:

"Oh, not now, Gohan! Let's try again next week.

Input example:

5

1 2 3 3 5

5 1 3 2 3

Exit:

'Go, Gohan'.

My code:

n = int(input())

stone_gohan = input().split()

stone_picolo = input().split()

dictionary_gohan = {stone_gohan}

dictionary_picolo = {stone_picolo}

if dictionary_gohan == dictionary_picolo:
  print("Go, gohan")
else:
   print("Oh, not now, Gohan! Let's try again next week.")

CodePudding user response:

You probably could utilize duplicate lists for testing and as items are compared between the lists, you would remove the list items that are being compared. Following is a snippet of code to illustrate that method. Neither sorting nor counting is used.

found = True

n = int(input("Enter number: "))

stone_gohan = input("Enter Gohan: ").split()
st_gohan = stone_gohan

stone_picolo = input("Enter Picolo: ").split()
st_picolo = stone_picolo

for item in stone_gohan:
    if item not in st_picolo:
        found = False
        break
    else:
        st_picolo.remove(item)
        
for item in stone_picolo:
    if item not in st_gohan:
        found = False
        break
    else:
        st_gohan.remove(item)

if found:
  print("Go, gohan")
else:
   print("Oh, not now, Gohan! Let's try again next week.")

The key item here is that if an item is found in the other list (the work list duplication), then that item is removed from the work list to ensure that the proper count of items are found.

Following are a couple of tests. One where the lists have the same values but in different orders and then another where each value is found in the other list but not the same number for each value.

@Una:~/Python_Programs/Gohan$ python3 Gohan.py 
Enter number: 5
Enter Gohan: 1 2 3 3 5
Enter Picolo: 5 3 2 3 1
Go, gohan
@Una:~/Python_Programs/Gohan$ python3 Gohan.py 
Enter number: 5
Enter Gohan: 1 2 3 3 5
Enter Picolo: 1 2 2 3 5
Oh, not now, Gohan! Let's try again next week.

Give that a try.

  • Related