Advice on python program - python

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 surrounded 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("]", "}")

Related

joining sequences together using the + operator

Does anyone know how to write this out in code using the + operator?
I've been trying for a while but I don't know how to get the output to be in the format:
Data: [1, 2, 3, 4]
This is my first time answering so I apologize in advance if my answer is unnecessarily complicated. First question I have is, do you have to use the '+' operator? If not, you could just append the numbers into a list (we can call the list 'ls') and then if you do print(ls) python should automatically print out the list like you want.
If you do have to use the '+' operator, you could have a string with an opening bracket, so just '[' and then every number they type in, you could add each number to the string using a loop.
Try this, not sure why do need + operator here, unless you want to write result += [int(value)]:
def main():
result = []
while True:
value = input("Enter an integer number (blank to exit): ")
if value == "":
return f'Data: {result}'
result.append(int(value))
print(main())

How would I execute this? Python

I am pretty new to python and would like to know how to write a program that asks the user to enter a string that contains the letter "a". Then, on the first line, the program should print the part of the string up to and including the certain letter, and on the second line should be the rest of the string.
For example...
Enter a word: Buffalo
Buffa
lo
This is what I have so far :
text = raw_input("Type something: ")
left_text = text.partition("a")[0]
print left_text
So, I have figured out the first part of printing the string all the way up to the certain letter but then don't know how to print the remaining part of the string.
Any help would be appreciated
If what you want is the first occurrence of a certain character, you can use str.find for that. Then, just cur the string into two pieces based on that index!
In python 3:
split_char = 'a'
text = input()
index = text.find(split_char)
left = text[:-index]
right = text[-index:]
print(left, '\n', right)
I don't have a python2 on hand to make sure, but I assume this should work on python 2:
split_char = 'a'
text = raw_input()
index = text.find(split_char)
left = text[:-index]
right = text[-index:]
print left + '\n' + right)
Another option that is far more concise is to use
left_text, sep, right_text = text.partition("a")
print (left_text + sep, '\n', right_text)
and then as suggested in the comments, thanks #AChampion !
You should have some knowledge about slicing and concatenating string or list. You can learn them here Slicing and Concatenating
word = raw_input('Enter word:') # raw_input in python 2.x and input in python 3.x
split_word = raw_input('Split at: ')
splitting = word.partition(split_word)
'''Here lets assume,
word = 'buffalo'
split_word = 'a'
Then, splitting variable returns list, storing three value,
['buff', 'a', 'lo']
To get your desire output you need to do some slicing and concatenate some value .
'''
output = '{}\n{}'.join(splitting[0] + splitting[1], splitting[2])
print(output)
First find the indices of the character in the given string, then print the string accordingly using the indices.
Python 3
string=input("Enter string")
def find(s, ch):
return [i for i, ltr in enumerate(s) if ltr == ch]
indices=find(string, "a")
for index in indices[::-1]:
print(string[:index+1])
print(string[indices[-1]+1:])

White space counter

Your program should ask the user to input the list, then it should call the function, and print the result. with the following condition:
It returns True if the given list has at least 2 white spaces and False otherwise.
My code:
n = ((input("Please input a list of numbers separated by space:")))
t = 0
k = n.count(' ')
for i in range(0,len(n)):
if n[i] > " ":
print("True")
else:
print("False")
print("There are",k,"space which has two length run")
My program counts all of the white spaces, but I want it to only count the 2 white spaces or more and return True or False otherwise
I see several issues with this code.
First, you do not define a function as stated in the requirements.
Second, k = n.count(' ') already counts all the spaces in the input string. You do not need to loop over each character.
Third, even if you did need to loop over the characters, n[i] > " " is definitely not the right way to do what you want.
Fourth, what is the purpose of the t variable?
Fifth, why is input() enclosed in two extra layers of parentheses?
Not clear why you think you need a loop.
Try simply
print(n.count(' ') >= 2)
Or rather
def foo(n):
return n.count(' ') >= 2
print(foo(input("Enter some numbers:")))

Cannot remove two vowels in a row

I have to enter a string, remove all spaces and print the string without vowels. I also have to print a string of all the removed vowels.
I have gotten very close to this goal, but for some reason when I try to remove all the vowels it will not remove two vowels in a row. Why is this? Please give answers for this specific block of code, as solutions have helped me solve the challenge but not my specific problem
# first define our function
def disemvowel(words):
# separate the sentence into separate letters in a list
no_v = list(words.lower().replace(" ", ""))
print no_v
# create an empty list for all vowels
v = []
# assign the number 0 to a
a = 0
for l in no_v:
# if a letter in the list is a vowel:
if l == "a" or l == "e" or l == "i" or l == "o" or l == "u":
# add it to the vowel list
v.append(l)
#print v
# delete it from the original list with a
del no_v[a]
print no_v
# increment a by 1, in order to keep a's position in the list moving
else:
a += 1
# print both lists with all spaces removed, joined together
print "".join(no_v)
print "".join(v)
disemvowel(raw_input(""))
Mistakes
So there are a lot of other, and perhaps better approaches to solve this problem. But as you mentioned I just discuss your failures or what you can do better.
1. Make a list of input word
There are a lot of thins you could do better
no_v = list(words.lower().replace(" ", ""))
You don't replaces all spaces cause of " " -> " " so just use this instead
no_v = list(words.lower().translate( None, string.whitespace))
2. Replace for loop with while loop
Because if you delete an element of the list the for l in no_v: will go to the next position. But because of the deletion you need the same position, to remove all the vowels in no_v and put them in v.
while a < len(no_v):
l = no_v[a]
3. Return the values
Cause it's a function don't print the values just return them. In this case replace the print no_v print v and just return and print them.
return (no_v,v) # returning both lists as tuple
4. Not a mistake but be prepared for python 3.x
Just try to use always print("Have a nice day") instead of print "Have a nice day"
Your Algorithm without the mistakes
Your algorithm now looks like this
import string
def disemvowel(words):
no_v = list(words.lower().translate( None, string.whitespace))
v = []
a = 0
while a < len(no_v):
l = no_v[a]
if l == "a" or l == "e" or l == "i" or l == "o" or l == "u":
v.append(l)
del no_v[a]
else:
a += 1
return ("".join(no_v),"".join(v))
print(disemvowel("Stackoverflow is cool !"))
Output
For the sentence Stackoverflow is cool !\n it outputs
('stckvrflwscl!', 'aoeoioo')
How I would do this in python
Not asked but I give you a solution I would probably use. Cause it has something to do with string replacement, or matching I would just use regex.
def myDisemvowel(words):
words = words.lower().translate( None, string.whitespace)
nv = re.sub("[aeiou]*","", words)
v = re.sub("[^a^e^i^o^u]*","", words)
return (nv, v)
print(myDisemvowel("Stackoverflow is cool !\n"))
I use just a regular expression and for the nv string I just replace all voewls with and empty string. For the vowel string I just replace the group of all non vowels with an empty string. If you write this compact, you could solve this with 2 lines of code (Just returning the replacement)
Output
For the sentence Stackoverflow is cool !\n it outputs
('stckvrflwscl!', 'aoeoioo')
You are modifying no_v while iterating through it. It'd be a lot simpler just to make two new lists, one with vowels and one without.
Another option is to convert it to a while loop:
while a < len(no_v):
l = no_v[a]
This way you have just a single variable tracking your place in no_v instead of the two you currently have.
For educational purposes, this all can be made significantly less cumbersome.
def devowel(input_str, vowels="aeiou"):
filtered_chars = [char for char in input_str
if char.lower() not in vowels and not char.isspace()]
return ''.join(filtered_chars)
assert devowel('big BOOM') == 'bgBM'
To help you learn, do the following:
Define a function that returns True if a particular character has to be removed.
Using that function, loop through the characters of the input string and only leave eligible characters.
In the above, avoid using indexes and len(), instead iterate over characters, as in for char in input_str:.
Learn about list comprehensions.
(Bonus points:) Read about the filter function.

Concatenating in for loop

it's a loop to reverse a string entered by the user, it reads letters in reverse and put them into a sentence. the problem is that, for example user's input is hello, the comma(,) in the last line of the code makes the output to be o l l e h, but if there isnt a comma there, the output will have each letter in a line. and concatenate (+) doesnt work it gives an error. What do i do so that the output would be olleh instead of o l l e h?
phrase = raw_input("Enter a phrase to reverse: ")
end = (len(phrase))-1
for index in range (end,-1,-1):
print phrase[index],
how about:
string = ''
for i in range(end, -1, -1):
string += phrase[i]
print string
However, an easier, cleaner way without the for loop is:
print phrase[::-1] # this prints the string in reverse
And also there is:
#As dougal pointed out below this is a better join
print ''.join(reversed(phrase))
#but this works too...
print ''.join(phrase[i] for i in range(end, -1, -1)) # joins letters in phrase together from back to front
To concatenate something, you have to have a string to concatenate to. In this case, you need a variable that is defined outside of the for loop so you can access it from within the for loop multiple times, like this:
phrase = raw_input("Enter a phrase to reverse: ")
end = (len(phrase))-1
mystr = ""
for index in range (end,-1,-1):
mystr += phrase[index]
print mystr
Note that you can also simply reverse a string in Python doing this:
reversedstr = mystr[::-1]
This is technically string slicing, using the third operator to reverse through the string.
Another possibility would be
reversedstr = ''.join(reversed(mystr))
reversed returns a reversed iterator of the iterator you passed it, meaning that you have to transform it back into a string using ''.join

Categories