Reverse loop for palindrome - python-3.x

My teacher wants me to use a reverse loop instead of the reverse function I am using right now. I can't seem to get one that works.
def palindrome():
myInput = input("Enter a Word: ")
word = myInput[::-1]
if myInput == word:
print("That is a palindrome")
return True
else:
print("That is not a palindrome")
return False
palindrome()

def palindrome():
string = input("Enter a Word: ")
for i,char in enumerate(string):
if char != string[-i-1]:
return False
return True
Edited for below comment:
the enumerate() function adds a counter to an iterable.
>>> string = "PARAM"
>>> for count, elem in enumerate(string):
... print count, elem
...
0 P
1 A
2 R
3 A
4 M
so line if char != string[-i-1] will try to match one character from front and one character from end.

You could try the code below, but I really recommend you to try it yourself first. (Because, if you're able to write a recursive call, you should be able to write an iterative one yourself too.)
def reverse(text):
rev = ""
final = ""
for a in range(0,len(text)):
rev = text[len(text)-a-1]
final = final + rev
return final

Related

I need a help in writing a function that counts the digits and letters separately then returns the result in a dictionary format

I have been working on the python challenge question and I have been stuck it on for a while. Below is the question.
Write a function that takes a string and calculates the number of letters and digits within it. Return the result in a dictionary.
Examples:
count_all("Hello World") ➞ { "LETTERS": 10, "DIGITS": 0 }
count_all("H3ll0 Wor1d") ➞ { "LETTERS": 7, "DIGITS": 3 }
count_all("149990") ➞ { "LETTERS": 0, "DIGITS": 6 }
Notes:
Tests contain only alphanumeric characters.
Spaces are not letters.
All tests contain valid strings.
The function should return dictionary
I have written a code to solve it but I have been getting a 'Too many positional arguments for function call.
def count_all(string):
d = 0
l = 0
for c in string:
if c.isdigit():
d=d+1
elif c.isalpha():
l=l+1
else:
pass
print(count_all("string", "l"))
print(count_all("string", "d"))
what have I done wrong exactly?
Pretty much all you need to do is make it so that you're passing just 1 string to your function, like so: print(count_all("letters and numbers 12345")). And second, you need to change the output so that it should return a dict, like so: return {"letters": l, "digits": d}.
Try this out
def countStuff(argString = None):
resultDict = {"Letters" : 0, "Numbers" : 0}
if argString is None:
print("-_-")
for i in argString:
if i.isdigit():
resultDict["Numbers"] += 1
elif i.lower().islower():
resultDict["Letters"] += 1
else:
pass
print(resultDict)
alphacount = 0
numcount = 0
str1 = input("Enter a sentence: ")
for x in str1:
if x.isalpha(): # Check the Albhabets in String
alphacount+=1
elif x.isdigit(): # Check the digits in String
numcount+=1
else:
continue
print('LETTERS '+ str(alphacount))
print('DIGITS '+ str(numcount))

Concatenating string outputs of a for loop in Python 3

I have a code which, after a nested for loop, provides me with a unique string in each iteration. I want to find a way to concatenate those outputs so that my final line is a single string of those unique strings. Ignoring how ugly and inefficient this code is, what steps can I take to achieve the desired result?
VOWELS = ('a','e','i','o','u','A','E','I','O','U')
ad = "Desirable unfurnished flat in quiet residential area"
# remove all vowels, unless the word starts with a vowel
def is_vowel(c):
return c in VOWELS
def mod3(ad):
testAd =ad.split()
for word in testAd:
modAd = ""
i = 0
for char in word:
if i == 0:
modAd += char
elif not is_vowel(char):
modAd += char
i+=1
print(modAd)
mod3(ad)
my output for this code:
Otherwise, when I modify my code to look like this:
But my output is:
I don't believe a .join() would work here as it's not a list type. And I can't figure out where to put a string concat + anywhere without my for loop going bonkers. Any advice?
You can create a string result where you can concatenate your each iteration result and print that. You need to add spaces after each addition of words. So, append + " " to your result variable as well.
def mod3(ad):
result = ""
testAd =ad.split()
for word in testAd:
modAd = ""
i = 0
for char in word:
if i == 0:
modAd += char
elif not is_vowel(char):
modAd += char
i+=1
result += modAd + " "
print(result)
Second option: This is my take on it:
def mod4(ad):
result = ""
testAd =ad.split()
for word in testAd:
for i, char in enumerate(word):
if i == 0:
result += char
if i > 0 and char not in VOWELS:
result += char
result += " "
print(result)

How can I find a string in sequence (with Booleans)?

I receive a String. For example in here I have :
Mystring= ‘alohrefllluqoo’
I can see all the letter of 'Hello' word, in the correct sequence, in Mystring string
is it possible to use Booleans?
in that string the final output would be 'YES', cause when I remove extra letter I can see the 'Hello' word (in correct sequence) in string.
and if the sequence is not correct and the word can not be found, the output will be 'NO'
This is one approach.
Ex:
Mystring= 'alohrefllluqoo'
to_find = "hello"
def check_string(Mystring, to_find):
c = 0
for i in Mystring:
if i == to_find[c]:
c += 1
if c == len(to_find):
return "YES"
return "NO"
print(check_string(Mystring, to_find))
You can use something like this:
mystring = 'alohreflllouq'
wordtofind = "hello"
i=0
word=''
for char in mystring:
if char == wordtofind[i]:
word = word + char
i+= 1
if word == wordtofind:
break
result = "YES" if word == wordtofind else "NO"
print(result)
making a function, and passing your string, and the thing you search for:
def IsItHere(some_string, sub_string)
try:
some_string.index(sub_string)
return 'YES'
except:
return 'NO'

Standard output is empty in python3

This is a program of finding a string is palindrome or not. But When I run this code I got error "standard output is error".
class Palindrome:
#staticmethod
def is_palindrome(word):
flag = word;
lengths = len(word);
j=lengths;
lengths = lengths/2;
lengths = int(lengths);
for i in lengths:
if (word[i] == word[j]):
count = count+1;
j = j-1;
if (count == lengths):
r = "yes";
else:
r = "no";
return r
word = input();
print(Palindrome.is_palindrome(word));
There are some mistakes in the code,
First of all, you are trying to iterate a int like for i in lengths which will throw you an error. You must be using it like for i in range(lengths).
Also, you are trying to do count = count+1 even before count is initialized, which will be throwing an error. To solve this you can initialize the variable count before the loop to 0.
Another issue with the code is that, you are tying to compare word[i] and word[j] where j is length which is not possible because for a string of length n, index runs from 0 to n-1. Therefore you must be using length-1 as j.
Also, there is no need for semicolon in Python.
Correcting all the things that I have mentioned above you can re-write the code like this
class Palindrome:
#staticmethod
def is_palindrome(word):
flag = word
lengths = len(word)
j=lengths-1
lengths = lengths/2
lengths = int(lengths)
count = 0
for i in range(lengths):
if (word[i] == word[j]):
count = count+1
j = j-1
if (count == lengths):
r = "yes"
else:
r = "no"
return r
word = input()
print(Palindrome.is_palindrome(word))
If you can use ~ operator you can tidy up the code to a great extend. It can be done like this.
class Palindrome:
#staticmethod
def is_palindrome(word):
if all(word[i] == word[~i] for i in range(len(word) // 2)):
return "yes"
else:
return "no"
word = input()
print(Palindrome.is_palindrome(word)
If you want to know how the ~ operator works take a look at this post.
You can improve it further if you can use indexing to reverse the string. If you can reverse the string and then check with the original one.
class Palindrome:
#staticmethod
def is_palindrome(word):
if word == word[::-1]:
return "yes"
else:
return "no"
word = input()
print(Palindrome.is_palindrome(word)

String index out of range, Python

code for a function which increments a string, to create a new string. If the string already ends with a number, the number should be incremented by 1. If the string does not end with a number the number 1 should be appended to the new string.
The output is correct but it is showing a String index out of range error. Can someone help me on where and how the string index is out of range?
test cases,expected output:
(increment_string("foo"), "foo1"),(increment_string("foobar001"), "foobar002"),(increment_string("foobar1"), "foobar2"),(increment_string("foobar00"), "foobar01"),("foobar99"), "foobar100"),("foobar099"), "foobar100"),(increment_string(""), "1")
def increment_string(strng):
if strng[-1].isdigit():
exp_strng=strng[::-1]
new_strng=""
new_strng1=""
for i in exp_strng:
if i.isdigit():
new_strng+=i
else:
break
new_strng=new_strng[::-1]
new_strng1=int(new_strng)+1
new_strng1='{num:{fill}{width}}'.format(num=new_strng1, fill='0', width=len(new_strng))
return(strng[:-len(new_strng)]+new_strng1)
else:
strng+="1"
return(strng)
Since you gave us more information on the test cases given, you can bypass the edge case of an empty string by modifying the if statement:
def increment_string(strng):
# Add it here #
if strng == "":
return "1"
elif strng[-1].isdigit():
exp_strng = strng[::-1]
new_strng = ""
new_strng1 = ""
for i in exp_strng:
if i.isdigit():
new_strng += i
else:
break
new_strng = new_strng[::-1]
new_strng1 = int(new_strng) + 1
new_strng1 = '{num:{fill}{width}}'.format(num=new_strng1, fill='0', width=len(new_strng))
return strng[:-len(new_strng)] + new_strng1
else:
strng += "1"
return strng
If think this would be a better solution to your problem:
from re import search
def increment_string(s):
number = search('\d+$', s)
if number != None:
number = number.group()
first_part = s.split(number)[0]
return first_part + str(int(number)+1)
else:
return s + '1'
I don't know what you want when the number is 9 though: 0 or 10. This code produces 10.
the error was caused when empty string is passed. and I resolved it by adding one more if else:(thanks to Skam)
def increment_string(strng):
if len(strng)>0:
if strng[-1].isdigit():
exp_strng=strng[::-1]
new_strng=""
new_strng=""
for i in exp_strng:
if i.isdigit():
new_strng+=i
else:
break
new_strng=new_strng[::-1]
new_strng1=int(new_strng)+1
new_strng1=str(new_strng1)
new_strng1=new_strng1.zfill(len(new_strng))
return(strng[:-len(new_strng)]+new_strng1)
else:
strng+="1"
return(strng)
else:
strng+="1"
return(strng)

Resources