how to reverse two characters in a string python - python

I was wondering how to reverse two characters in a string.
Here are some examples:
'wing' => 'iwng', 'inwg', 'ingw'
'west' => 'ewst', 'eswt', 'estw'
I was going to use any answers given and put it in a while loop so I can get all the possible combinations of a string while swapping two characters at a time.
ex.
counter = 0
while (counter <= len(str1)):
if str1 == reverse(str2):
return str2
elif str1 == str2
return str2
else:
str1 = *some code that would swap the the characters m and n*
str1 =
n += 1
m += 1
return False
This code compares two strings, str1 to str2, and checks to see if they are the same by swapping the characters around.
ALSO, is there a way i can get this to produce a list of the results instead of printing them?
THANKS!

Try this:
s = 'wing'
s = 'west'
l = [x for x in s]
for i in xrange(len(s)-1):
l[i], l[i+1] = l[i+1], l[i]
print "".join(l)

In order to generate all possibilities, we can use:
s = "yourstring"
for i in range(0,len(s)-2):
if i>0: print s[:i]+s[i+1:i-1:-1]+s[i+2:]
else: print s[1]+s[0]+s[2:]

Since you wish to actually compare two strings to see if they "are the same by swapping two characters around," you do not actually need to generate all possible combinations, instead you can iterate through each of the characters in each of the strings and ensure that no more than two of them are not equal.
This can be done as follows:
def twoCharactersDifferent(str1,str2):
if sorted(str1) != sorted(str2): #they must contain the same letters, exactly!
return False
numDifferent = 0
for i in range(len(str1)):
numDifferent += (str1[i] != str2[i])
if numDifferent >2:
return False
return True
print twoCharactersDifferent('wings','winxg')

Related

Given a string S, remove consecutive duplicates from it recursively using python

i am adding str[1] that is causing one repeated element to be left but if donot do that string does not get printed. any solutions
def removeCD(str):
l = len(str)
if l == 0 or l == 1:
return str
if(str[0]==str[1]):
return str[1] + removeCD(str[2:])
else:
return str[0] + removeCD(str[1:])
string = input().strip()
print(removeCD(string))
When characters are equal, you again adding duplicate character. This should work:
def removeCD(str):
l = len(str)
if l == 0 or l == 1:
return str
if(str[0]==str[1]):
return removeCD(str[1:])
else:
return str[0] + removeCD(str[1:])
string = input().strip()
print(removeCD(string))
Here is the case analysis we need to perform -
If string length is less than two (base case), there is nothing to compare, simply return the string
Otherwise (by induction) the string is at least two characters long. If the first matches the second, drop the first letter and return the recursive result
Otherwise (by induction) the string is at least two characters long and the first two characters do not match. Return the first char combined with the recursive result.
This encodes to a python program in a straightforward way -
def remove_adjacent_dupes (s = ""):
if len(s) < 2:
return s
elif s[0] == s[1]:
return remove_adjacent_dupes(s[1:])
else:
return s[0] + remove_adjacent_dupes(s[1:])
print(remove_adjacent_dupes("bookkeeper"))
# bokeper
When the characters are equal, you should be recursing on everything but the first character:
if(str[0]==str[1]):
return removeCD(str[1:])
def remove(string):
l = len(string)
if l==0 or l==1:
return string
if string[0] == string[1]:
s = remove(string[1:])
return s
else:
s = remove(string[1:])
return string[0]+s
string = input().strip()
print(remove(string))

How to uppercase even letter and lowercase odd letter in a string?

I am creating a function that takes in a string and returns a matching string where every even letter is uppercase and every odd letter is lowercase. The string only contains letters
I tried a for loop that loops through the length of the string with an if statement that checks if the index is even to return an upper letter of that index and if the index is odd to return a lowercase of that index.
def my_func(st):
for index in range(len(st)):
if index % 2 == 0:
return st.upper()
else:
return st.lower()
I expected to have even letters capitalize and odd letter lowercase but I only get uppercase for the whole string.
Some issues in your code:
Currently you are returning from the function on the first index itself, i.e index=0 when you do return st.lower(), so the function will stop executing after it encounters the first index and breaks out of the for loop
Doing st.lower() or st.upper() ends up uppercasing/lowercasing the whole string, instead you want to uppercase/lowercase individual characters
One approach will be to loop over the string, collect all modified characters in a list, convert that list to a string via str.join and then return the result at the end
You also want to refer to each individual characters via the index.
def my_func(st):
res = []
#Iterate over the character
for index in range(len(st)):
if index % 2 == 0:
#Refer to each character via index and append modified character to list
res.append(st[index].upper())
else:
res.append(st[index].lower())
#Join the list into a string and return
return ''.join(res)
You can also iterate over the indexes and character simultaneously using enumerate
def my_func(st):
res = []
#Iterate over the characters
for index, c in enumerate(st):
if index % 2 == 0:
#Refer to each character via index and append modified character to list
res.append(c.upper())
else:
res.append(c.lower())
#Join the list into a string and return
return ''.join(res)
print(my_func('helloworld'))
The output will be
HeLlOwOrLd
You can store your operations beforehand and use them in join with enumerate:
def my_func(st):
operations = (str.lower, str.upper)
return ''.join(operations[i%2](x) for i, x in enumerate(st))
print(my_func('austin'))
# aUsTiN
Tweaking your code a bit, You can use the 'enumerate' and keep appending to the string based on the condition evaluations( for me this was easier since I have been coding in java :))
def myfunc(st):
str=''
for index, l in enumerate(st):
if index % 2 == 0:
str+=l.upper()
else:
str+=l.lower()
return str
def myfunc(str):
rstr = ''
for i in range(len(str) ):
if i % 2 == 0 :
# str[i].upper()
rstr = rstr + str[i].upper()
else:
#str[i].lower()
rstr = rstr + str[i].lower()
return rstr
l = 'YourString'
li=[]
for index,i in enumerate(l):
if index % 2 == 0:
i=i.lower()
li.append(i)
elif index % 2 == 1:
i=i.upper()
li.append(i)
print(''.join(li))
Use this enumerate method to perform your operation
return will terminate your function, so there isn't much point of the loop
st is the whole string, so st.upper() will yield the whole string in upper case.
You can use a bitwise and (&) to check for odd positions. The enumerate function will give you both the positions and the characters so you can easily use it in a list comprehension:
def upLow(s):
return "".join(c.lower() if i&1 else c.upper() for i,c in enumerate(s))
upLow("HelloWorld") # HeLlOwOrLd
The below code should do what you are looking for.
def myfunc(name):
str=""
lc=1;
for character in name:
if(lc%2==0):
str+=character.upper()
else:
str+=character.lower()
lc+=1
return str
def myfunc(a):
newString = ''
for count, ele in enumerate(a, 0):
if count %2 == 0:
newString += (a[count].lower())
else:
newString += ((a[count].upper()))
return newString
You can deconstruct string into collection of characters, apply transformations and reconstruct string back from them
Logic:
First enumerate() over the string to generate key-value pairs of characters and their positions
Then use comprehensions to loop over them and use conditional statement to return odd position characters in lower() case and even position in upper()
Now you have the list ready. Just join() it with an empty string '' to convert the list into a string
Code:
str = 'testing'
''.join([y.upper() if x%2 ==0 else y.lower() for x,y in enumerate(str)])

Check if the letters of one string are in another string

Okey so basically I have to check if one string has the same letters of another string. Both strings are obtained via input().
I don't want to double check if a letter is in the other string, so if I already checked that letter I want to skip to the next letter.
The code I have for now is this:
str1, str2 = list(input()), list(input())
if len(str1) > len(str2):
str = str1
else:
str = str2
for x in str:
c = 0
if x in str2:
c += 1
if c != 0:
print("Both have the same letters!")
else:
print("Nope there are some letters missing..")
I don't know if I should work with the lists instead of using a counter.. please a detailled explanation of the solution or some good quality guidance would be very appreciated! <3
Converting strings to sets of individual symbols remove duplicate symbols, so we can simply compare them:
if set(str1) == set(str2):
print("Both have the same letters!")
else:
print("Nope there are some letters missing..")
Note:
As the order of elements in sets is not important, we may even compare them, e. g.
if set(str1) <= set(str2): # <= means "is subset" in this context
print("All symbols in str1 are in str2, too.")
or
if set(str1) < set(str2): # < means "is a proper subset" in this context
print("All symbols in str1 are in str2, too, "
"but str2 has at least 1 symbol not contained in str1.")
Some issues with the code are that, str2 is always used for comparison even if str2 is longer than str1
for x in str:
c = 0
if x in str2:
Next, c is set to 0 for every character in str, Instead you can have a counter to count the number of chars not in the other string
This should do the job
str1, str2 = list(input()), list(input())
if len(str1) > len(str2):
str = str1
compared_string = str2
else:
str = str2
compared_string = str1
not_in_other_string = 0
for x in str:
if x not in compared_string:
not_in_other_string += 1
if not_in_other_string == 0:
print("Both have the same letters!")
else:
print("Nope there are some letters missing..")
It sounds like you want to find if all of the characters in one string are in some larger string.
You could use unique = ''.join(set(substring)) to get a list of chars in the substring and then make a list comprehension to get all the chars in the larger string.
Here is my example:
unique = ''.join(set(substring))
not_in = [char for char in unique if char not in superstring]
Now you can check not_in to see if it is null, otherwise there was a char in the substring that was not in the superstring.
For example:
superstring = "hello"
substring = "xllo"
unique = ''.join(set(substring))
not_in = [char for char in unique if char not in superstring]
print not_in
>>>['x']
print not_in == []
>>>False
Typically, the preferred way to do things in python is using list comprehensions or use some built in function that already checks strings for you, rather than the C style where you go through a loop and check letter for letter explicitly. This is the idiomatic way of pythonic programming.
Breaking apart the list comprehension we have a loop like this:
for char in unique:
if char not in superstring:
char #char meets conditions so it is the value used in [char ...
Here would be the modification I would make
str1, str2 = input(), input()
unique = ''.join(set(str1))
not_in = [char for char in unique if char not in str2]
if not_in == []:
print("Both have the same letters!")
else:
print("Nope there are some letters missing..")
str1, str2 = input().split()
if len(str1) > len(str2):
string_to_check= str1
string_from_which_to_check = str2
else:
string_to_check = str2
string_from_which_to_check = str1
not_in_other_string = set(string_to_check) - set(string_from_which_to_check)
if len(not_in_other_string )==0:
print("character are present in string")
else:
print("{} not present in string".format(str(not_in_other_string )))

Python: list index out of range when trying to compare two strings at index?

I have this function to check if a string contains three or more lowercase letters.
def lowerCaseValid(word):
lowCharList = ['abcdefghijklmnopqrstuvwxyz']
i = 0
flag = 0
while i <= len(word):
j = 0
while j <= len(lowCharList):
if lowCharList[j] == word[i]:
flag += 1
j = 0
else:
j += 1
i += 1
if flag >= 3:
return True
In simple terms, I pass in a string (word) and create a list of acceptable characters (lowCharList).
Then, I set up a nested while loop that checks word[i] at every index of lowCharList, until it finds a match.
Then it resets lowCharList counter and adds 1 to flag, and moves on to word[i+1].
If it doesn't find a match by the time it reaches z, then it moves onto word[i+1] anyways.
For some reason, why I try my sample input in my main function.
def main():
word = 'corRe!33'
print(lowerCaseValid(word))
I get this error:
in lowerCaseValid
if lowCharList[j] == word[i]:
IndexError: list index out of range
Why is it throwing this error? Thank you.
using python's in operator is easier...
def lowerCaseValid(word):
cnt = 0
lowCharList = ['abcdefghijklmnopqrstuvwxyz']
chars = lowCharList.pop ()
for ch in word:
if ch in chars:
cnt += 1
return cnt >= 3
or with using sets just 2 lines of code
def lowerCaseValid(word):
lowCharList = ['abcdefghijklmnopqrstuvwxyz']
return len(set(lowCharList.pop()) & set(word)) >=3
or one liner with map and lambda
def lowerCaseValid(word):
return len(list(map(lambda x: x.islower, list(word)))) >=3
Another alternative approach using a list comprehension and string.ascii_lowercase instead of redefining the lowercase letters:
from string import ascii_lowercase
def lowerCaseValid(word):
return sum[x in ascii_lowercase for x in word] >= 3
How this works is that the list comprehension goes through each letter in word. The x in ascii_lowercase will return a boolean value of either True (1) or False (0), then sum up the Trues
Change
lowCharList = ['abcdefghijklmnopqrstuvwxyz']
to
lowCharList = list('abcdefghijklmnopqrstuvwxyz')
I believe this should help, since you have a list containing only 1 item, whereas this way, you create a list with 24 items (all different letters).
As heemayl pointed out in the comments, lowCharList is 1 element long! Now you have 2 options: make lowCharList an actual list (lowCharList = list ("abcd...")), or keep lowCharList a string, which will work just fine (remove the brackets in the definition.
Might I suggest another method: checking if str.islower count adds up to >=3. So:
lower_count = 0
for letter in word:
if letter.islower(): lower_count += 1
if lower_count >= 3: return True
Also, as suggested in the comments:
return len ([letter for letter in word if letter.islower()]) >= 3
would work (better than my answer, which is just the expanded form of it)

How to calculate the number of integers in a python string

I want to calculate the number of integers in the string "abajaao1grg100rgegege".
I tried using isnumeric() but it considers '100' as three different integers and shows the output 4. I want my program to consider 100 as a single integer.
Here is my attempt:
T = int(input())
for x in range(T):
S = input()
m = 0
for k in S:
if (k.isnumeric()):
m += 1
print(m)
I'd use a very basic regex (\d+) then count the number of matches:
import re
string = 'abajaao1grg100rgegege'
print(len(re.findall(r'(\d+)', string)))
# 2
Regex is the go-to tool for this sort of problem, as the other answers have noted. However, here is a solution that uses looping constructs and no regex:
result = sum(y.isdigit() and not x.isdigit() for x,y in zip(myString[1:], myString))
In addition, here is an easy to understand, iterative solution, that also doesn't use regex and is much more clear than the other one, but also more verbose:
def getNumbers(string):
result = 0
for i in range(len(string)):
if string[i].isdigit() and (i==0 or not string[i-1].isdigit()):
result += 1
return result
You can use the regex library to solve this issue.
import re
st = "abajaao1grg100rgegege"
res = re.findall(r'\d+', st)
>>> ['1', '100']
You can check how many numbers you have on that list that the findall returned.
print (len(res))
>>> 2
In order to read more on python regex and the patterns, enter here
Not very Pythonic but for beginners more understandable:
Loop over characters in string and in every iteration remember in the was_digit (logical variable) if the current character is digit - for the next iteration.
Increase the counter only if the previous character was not a digit:
string = 'abajaao1grg100rgegege'
counter = 0 # Reset the counter
was_digit = False # Was previous character a digit?
for ch in string:
if ch.isdigit():
if not was_digit: # previous character was not a digit ...
counter += 1 # ... so it is start of the new number - count it!
was_digit = True # for the next iteration
else:
was_digit = False # for the next iteration
print(counter) # Will print 2
random="1qq11q1qq121a21ws1ssq1";
counter=0
i=0
length=len(random)
while(i<length):
if (random[i].isnumeric()):
z=i+1
counter+=1
while(z<length):
if (random[z].isnumeric()):
z=z+1
continue
else:
break
i=z
else:
i+=1
print ("No of integers",counter)

Categories