How do you sort integers in a string [duplicate] - python

This question already has answers here:
Split a string with unknown number of spaces as separator in Python [duplicate]
(6 answers)
Closed 4 years ago.
This function takes one string parameter. Assume the string will be a series of integers separated by spaces. Ignore any extra whitespace. The empty string or a whitespace string return the empty string. Otherwise, the function returns a string with the argument’s integers
separated by spaces but now in sorted order. Do not check for invalid strings. For instance, if the argument is 43 -1 17, the function returns -1 17 43.`
it does not work in a situation where the input is \t42 4 -17 \n
def sort_int_string(string):
strlist = string.split(' ')
new = []
for value in strlist:
value2 = int(value)
new.append(value2)
new = sorted(new)
strlist2 = []
for number in new:
number = str(number)
strlist2.append(number)
final = ' '.join(strlist2)
return final

based on your comment, change the line:
strlist = string.split(' ')
to
strlist = string.split()
That should work because when sep is not specified, it defaults to white space. [ \t\n\r\f\v] are all white spaces.

#VanTan has explained the problem with your code. But you can also use:
x = '43 -1 17'
res = ' '.join(map(str, sorted(map(int, x.split()))))
# '-1 17 43'

This list comprehension should handle the whitespace you are encountering:
s = "\t42 4 -17 \n"
sorted([int(x) for x in " ".join(s.split()).split()])
[-17, 4, 42]

Related

How to get the first letter index of a string after spaces in Python? [duplicate]

This question already has answers here:
What is the pythonic way to count the leading spaces in a string?
(7 answers)
Closed last year.
Is there a way to get the first letter index of a string after an n number of spaces?
I know it is easily made with a for loop, but for sake of simplicity, is there a cleaner way?
string_1 = " Hello" # Return 4
string_2 = " Bye" # Return 8
Method strip() cuts spaces before the first and after the last charactes (and multiple inside like x y.
So:
x = ' abc'
x = x.strip()
print(x) # result -> 'abc'
You can use filter, enumerate, and next to stop whevener the condition is met:
string_1 = " Hello"
next(filter(lambda x: x[1]!=' ', enumerate(string_1)))[0]
# 4

Remove first word from string if length is 1 [duplicate]

This question already has answers here:
Removing any single letter on a string in python
(6 answers)
Closed 2 years ago.
I want to remove the first character in a string, and the white space after it, only if the first word is one character.
Like this:
input = "A fish"
output = "fish"
Is there a way to do this without turning it into a list first?
You can do this with indexing:
def remove_first(s):
if len(s) < 2:
return s
# if string is letter then a space then trim the first 2 chars
if s[0].isalpha() and s[1].isspace():
return s[2:]
return s
remove_first("A fish") # "fish"
remove_first("fish") # "fish"
Here is how:
text = "A fish"
if text[1] == ' ':
text = text[2:]
print(text)
Output:
fish

Check whether characters in a string are delimited by a space [Python]

Let's say I have a string a = 31 4 5 + + and a string b = 31 4 5 ++. I need to check that all numbers and operators in the string are delimited by at least one white space. Therefore, string a is correct, string b incorrect. c = 31 4 5+ + is also incorrect. Is there a way how to check for this? I could not come up with anything reasonable.
You can check it through following steps -
Break string into list using .split()
Check whether items in list whose length is more than 1 is numeric or not.
Code snippet:
def is_valid_string(st, delimiter = ' '):
lst = st.split(delimiter) # create list of chars separated by space
for item in lst:
if len(item) > 1 and not item.isdigit():
return False
return True
In case if you are considering float numbers you can use item.replace('.','',1).isdigit()
First thing to do would be splitting the strings by the whitespaces into "words", so something like words = a.split() (split's delimitor is a whitespace by default so no need for arguments)
I'm guessing you're only gonna use integers or floats and a set of operators like adding, substraction, multiplication and division, so one thing that you could do is check if you can cast the words into numbers with int or float and if you can't, check if the word is in your operators set, so something like:
a = "31 4 5 + +"
operators = ["+", "-", "*", "/"]
# Every string is valid by default
valid = True
words = a.split() # ["31", "4", "5", "+", "+"]
for word in words:
# try to cast word into a number
try:
float(word)
except:
# if you can't, check if it's an operator
if word not in operators:
valid = False #if it's not, the string isn't valid
if valid:
print("String is valid")
else:
print("String is not valid")
More complex stuff like equations and variables is obviously more difficult to code.
EDIT: python's isdigit() checks if a string is a number and it is more simple than a try block for casting the string, but it doesn't check for floats, which won't be valid. (you could still replace decimal points by numbers)
Try use regex ^((\d+|[+*/-])(\s+|$))+$. It matches more or more items, each of which is either a number (\d+) or an operator ([+*/-]), followed by either one or more spaces (\s+) or the end of string ($). The ^ at the beginning and ($) at the end force the regex match the whole string. Example:
>>> import re
>>> a = '31 4 5 + +'
>>> b = '31 4 5 ++'
>>> c = '31 4 5+ +'
>>> print(re.match(r'^((\d+|[+*/-])(\s+|$))+$', a))
<re.Match object; span=(0, 10), match='31 4 5 + +'>
>>> print(re.match(r'^((\d+|[+*/-])(\s+|$))+$', b))
None
>>> print(re.match(r'^((\d+|[+*/-])(\s+|$))+$', c))
None

How to print array in single_line? [duplicate]

This question already has answers here:
How can I suppress the newline after a print statement? [duplicate]
(5 answers)
Closed 3 years ago.
I am attempting to print a reversed array (list) of integers as a single line of space-separated numbers.
I've tried to use a for loop and printed each integer separately with a sep = ", " to remove the commas from the list. Should I use the remove() method as one alternative?
n = int(input())
arr = list(map(int, input().rstrip().split()))
for i in arr[::-1]:
print(i, sep = ", ")
Output
2
3
4
1
Should be:
2 3 4 1
Suppose I inputted 4. The expected results should be the exact sequence in the output but in a single line.
IIUC, this is what you look for:
print(*reversed(arr))
If a comma separator is needed, you can write
print(*reversed(arr), sep=", ")
for i in arr[::-1]:
print(i, end = ", ")

Comparing two strings and returning the difference. Python 3 [duplicate]

This question already has answers here:
How to merge lists into a list of tuples?
(10 answers)
Closed 7 years ago.
My goal is to write a program which compares two strings and displays the difference between the first two non-matching characters.
example:
str1 = 'dog'
str2 = 'doc'
should return 'gc'
I know that the code which I have tried to use is bad but I am hoping to receive some tips. Here is my poor attempt to solve the exercise which leads me to nowhere:
# firstly I had tried to split the strings into separate letters
str1 = input("Enter first string:").split()
str2 = input("Enter second string:").split()
# then creating a new variable to store the result after comparing the strings
result = ''
# after that trying to compare the strings using a for loop
for letter in str1:
for letter in str2:
if letter(str1) != letter(str2):
result = result + letter
print (result)
def first_difference(str1, str2):
for a, b in zip(str1, str2):
if a != b:
return a+b
Usage:
>>> first_difference('dog','doc')
'gc'
But as #ZdaR pointed out in a comment, result is undefined (in this case None) if one string is a prefix of the other and has different length.
I changed the solution by using a single loop.
How about this:
# First, I removed the split... it is already an array
str1 = input("Enter first string:")
str2 = input("Enter second string:")
#then creating a new variable to store the result after
#comparing the strings. You note that I added result2 because
#if string 2 is longer than string 1 then you have extra characters
#in result 2, if string 1 is longer then the result you want to take
#a look at is result 2
result1 = ''
result2 = ''
#handle the case where one string is longer than the other
maxlen=len(str2) if len(str1)<len(str2) else len(str1)
#loop through the characters
for i in range(maxlen):
#use a slice rather than index in case one string longer than other
letter1=str1[i:i+1]
letter2=str2[i:i+1]
#create string with differences
if letter1 != letter2:
result1+=letter1
result2+=letter2
#print out result
print ("Letters different in string 1:",result1)
print ("Letters different in string 2:",result2)

Categories