Write a function called remove_duplicates which will take one argument called string. This string input will only have characters between a-z.
The function should remove all repeated characters in the string and return a tuple with two values:
A new string with only unique, sorted characters.
The total number of duplicates dropped.
For example:
remove_duplicates('aaabbbac') => ('abc', 5)
remove_duplicates('a') => ('a', 0)
remove_duplicates('thelexash') => ('aehlstx', 2)
Here's my solution, and I'm new to python:
string = raw_input("Please enter a string...")
def remove_duplicates(string):
string = set(string)
if only_letters(string):
return (string, string.length)
else:
print "Please provide only alphabets"
remove_duplicates(string)
What might I be doing wrongly? This is the error I get below
THERE IS AN ERROR/BUG IN YOUR CODE
Results:
/bin/sh: 1: python/nose2/bin/nose2: not found
Thanks.
This works just fine. The output should be sorted.
def remove_duplicates(string):
new_string = "".join(sorted(set(string)))
if new_string:
return (new_string, len(string)-len(new_string))
else:
print "Please provide only alphabets"
No need to include this:
string = raw_input("Please enter a string...")
remove_duplicates(string)
As the order is not important, you can use
string = raw_input("Please enter a string...")
def remove_duplicates(string):
new_string = "".join(set(string))
if new_string:
return (new_string, len(string)-len(new_string))
else:
print "Please provide only alphabets"
remove_duplicates(string)
Please enter a string...aaabbbac
Out[27]: ('acb', 5)
set() will create a set of unique letters in the string, and "".join() will join the letters back to a string in arbitrary order.
was receiving the same error from a test I am working on, I feel the error is not from your end but the tester's end
Related
I want to check if a set of numbers is present in a string or not
Here is my code:
def check_no(string):
string = string.lower()
no = set(c)
s = set()
for i in string:
if i in no:
s.add(i)
else:
pass
if len(s) == len(no):
return("Valid")
else:
return("Not Valid")
c = input()
print(check_no(c))
if the given set of numbers is present in the string then it prints Valid and if not present it prints Not valid
the program works fine when the input is given as 123 and the string is like I have 12 car and 3 bikes then the output is valid
but when i give input as 254 and string as i hav25555number the output comes as valid but the actual output should be Not valid as 4 is not present in the string.
Can anyone help how to solve it in the provided code
I you want to check if all characters match then use all.
def check_no(text, check):
valid = all(character in text for character in check)
if valid:
return("Valid")
else:
return("Not Valid")
check = '254'
text = 'i hav25555number'
print(check_no(text, check))
The one-liner version
def check_no(text, check):
return 'Valid' if all(character in text for character in check) else 'Not Valid'
Your function is mostly correct, but probably because of your (terrible) choices of variable names, string and c variables were mixed up in the environment.
The solution is to add the parameters explicitly to the function definition (also avoid names like string or c as these could be pre-defined python keywords):
teststring = "254"
testc = "i hav25555number"
def check_no(mystring, myc):
string = mystring.lower()
no = set(c)
print("string is",string)
s = set()
for i in string:
if str(i) in no:
# print(i, " in ", no)
s.add(i)
else:
pass
# print("s is",s)
# print("no is",no)
if len(s) == len(no):
return("Valid")
else:
return("Not Valid")
print(check_no(teststring,testc))
gives:
print(check_no(teststring,testc))
string is 254
Not Valid
As mentioned before, you can use all to make your code more elegant, although there is nothing wrong with your implementation either.
The aim of my code is to take an input from the user and to check if each character could be a string or an integer. It would then put the character into different lists.
Also if you know a better way to do this please say. This is only thing I could think of.
user_inp = input("please give me an input")
def split_func():
for i in user_inp:
user_inp_split.append(i)
def check():
for i in user_inp:
try :
temp = int(i)
items2.append(temp)
del user_inp_split[i]
# the line that wont work
print (user_inp)
print (user_inp_split)
except:
print ("get to stage 2")
Welcome to StackOverflow, the problem that you have is that you do not have an organized code, i reorganized your code in order to make the task that you want:
user_inp = input("please give me an input: ")
user_inp_split = list(user_inp) #user input converted to list
items2 = [] #Character list
items1 = [] #integer list
def check():
for i in user_inp_split: #iterates over the user_input list
try :
items1.append(int(i,10)) #Convert the items to an integer with base on 10
except ValueError:
items2.append(i) #if not, append to the items2 list
print ("User input {}".format(user_inp))
print ("Characters {}".format(items2))
print ("Integers {}".format(items1))
check() #call the function, otherwise it wont work
First of all, you must declare the list to be appended to (line 3 and 4), then we must iterate, and check if they are integer, if they can be converted with the built-in function int(), they are integers, otherwise, they are not (lines 8 to 11), finally we print the user input to check that everything is OK.
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:])
import re
def check_input():
while True:
try:
sequence = raw_input("Please input:")
if sequence = [a,t,c,g]: # checking for valid input
continue
else:
print("invalid input, sequence coule only contain the "
"following letters (a,t,c,g)"):
check_input()
I basically want the script to check the user's input whether it contains only these four letters (a,t,c,g). If their input contains anything other than that four letters, it could print that second statement and prompt the user to input again. I saw there are similar questions and I already tried to change my script according to those posts but it still gives me the invalid syntax error at the if < sequence position. Anyone knows what's wrong here?
You need to iterate over every letter in the input and check if it is in the set of allowed letters, like this:
sequence = raw_input("Please input:")
for letter in sequence:
if letter not in "atcg":
print("invalid input, sequence coule only contain the following letters (a,t,c,g)")
When you discover that the sequence is invalid, you could choose to end the check by using a break statement after the print, or you could count how many invalid letters are allowed.
Your function must check and give user whether True or False:
def check_input(word):
result = True
for letter in sequene:
if letter in 'atcg':
continue
else:
result = False
break
return result
check_input('atgc')
Error Message:
if check_input('agct'):
continue
else:
print "error message"
You could also use the filter command:
def checkInp():
seq = raw_input("Please input sequence:")
if not filter(lambda m: m not in 'ATGC', seq) == '':
print 'Invalid input characters in sequence: ' + filter(lambda m: m not in 'ATGC', seq)
print 'Pleas'
check_input()
else: return seq
sequence, once input by the user will be a string, so you would need to iterate over each character in the sequence and use in to verify the existence of the character in the accepted characters string. String comparisons in Python are also case sensitive, so you need to match the case of the input to your expected string. I've used uppercase based on your sample input.
def check_input():
sequence = input("Please input:")
sequence.upper()
for letter in sequence:
if letter in 'ATCG':
continue
else:
print("invalid input, sequence could only contain the
following letters: a, t, c or g.")
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("]", "}")