0

I'm having trouble understanding why I am receiving repeat output when I iterate over a set of letters and remove letters that are contained within another set.

Code

text = set(input("Please enter some text: ").lower())
vowels = {"a", "e", "i", "o", "u", "y", ' '}

for t in text:
    if t in vowels:
        new_text = (text-vowels)
        print(sorted(new_text))

example:

Please enter some text: camera
['c', 'm', 'r']
['c', 'm', 'r']
Andrew Li
  • 55,805
  • 14
  • 125
  • 143
Chris
  • 387
  • 5
  • 18

2 Answers2

-1

The print happens the same number of times as the number of non-vowels in text.

Correct approach

Make a copy of the set or create the set from text separately.

To make a copy of the set

new_set = old_set.copy() #and check the id() values for both here

To create a set from text separately

input_ = input("Please enter some text: ").lower()

text = set(input_)
vowels = {"a", "e", "i", "o", "u", "y", ' '}

#To remove the vowel one-by-one by iterating
new_text = set(input_)
for t in text:
    if t in vowels:
        new_text.discard(t) # or remove

To print the non-vowels at one-go

print(sorted(new_text))

Error in previous answer

  1. Removing elements while iterating over it. Python: Removing list element while iterating over list.
  2. I was pointing both the text and new_text to the same set. We can confirm this by 'is' operator.

    text is new_text #Returns True

    print(id(text)), print(id(new_text)) #have the same value, so changing one changes the other

Previous Answer (Incorrect)

text = set(input("Please enter some text: ").lower())
vowels = {"a", "e", "i", "o", "u", "y", ' '}

#To remove the vowel one-by-one by iterating
new_text = text
for t in text:
    if t in vowels:
        new_text.discard(t) # or remove

#To print the non-vowels at one-go
print(sorted(new_text))
Sandeep
  • 119
  • 1
  • 8
-1

By altering the set, the output works as follows...

text = input("Please enter some text: ").lower()
vowels = {"a", "e", "i", "o", "u", "y", ' '}

new_text = set(text)
for t in text:
    if t in vowels:
        new_text.discard(t)

print(sorted(new_text))

output...

Please enter some text: camera
['c', 'm', 'r']
Chris
  • 387
  • 5
  • 18