Advice on python program
So i had to write a program that asks for a user input (which should be a 3 letter string) and it outputs the six permutations of the variations of the placements of the letters inside the string. However, my professor wants the output to be surrounde开发者_开发百科d by curly brackets whereas mine is a list (so it is square brackets). How do i fix this? Also, how do I check if none of the letters in the input repeat so that the main program keeps asking the user to enter input and check it for error?
Thank you
The only datatype im aware of that 'natively' outputs with { }
is a dictionary, which doesnt seem to apply here. I would just write a small function to output your lists in the desired fashion
>>> def curlyBracketOutput(l):
x = ''
for i in l: x += i
return '{' + x + '}'
>>> curlyBracketOutput(['a','b','c'])
'{abc}'
ok, for one thing, as everyone here has said, print '{'. other than that, you can use the following code in your script to check for repeated words,
letterlist = []
def takeInput(string):
for x in string:
if x not in letterlist:
letterlist.append(x)
else:
return 0
return 1
then as for your asking for input and checking for errors, you can do that by,
while(True): #or any other condition
string = input("Enter 3 letter string")
if len(string)!=3:
print("String size inadequate")
continue
if takeInput(string):
arraylist = permutation(string) #--call permutation method here
#then iterate the permutations and print them in {}
for x in arraylist: print("{" + x + "}")
else:
print("At least one of the letters already used")
The answer to both question is to use a loop.
Print the "{" and then loop through all the elements printing them.
But the input inside a loop and keep looping until you get what you want.
Curly brackets refers to a dict?
I think a
list(set(the_input))
should give you a list of unique letters. to check if they occur more than once and
theinput.count(one_letter) > 1
should tell you if there is mor than one.
>>> chars = ['a','b','c']
>>> def Output(chars):
... return "{%s}" % ''.join(chars)
...
>>> print Output(chars)
{abc}
>>>
Or just do something tremendously kludgy:
print repr(YourExistingOutput).replace("[", "{").replace("]", "}")
精彩评论