Standard output is empty in python3 - python-3.x

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)

Related

Write a program to check the overlapping of one string's suffix with the prefix of another string

a = input()
b = input()
def longestSubstringFinder(string1, string2):
answer = ""
len1, len2 = len(string1), len(string2)
for i in range(len1):
match = ""
for j in range(len2):
if (i + j < len1 and string1[i + j] == string2[j]):
match += string2[j]
else:
if (len(match) > len(answer)): answer = match
match = ""
if answer == '':
return 'No overlapping'
else:
return answer
print(longestSubstringFinder(a, b))
in the above code, not getting the expected outcome for the input
correct
wrong
My output: e
expected output: No overlapping
Some issues:
the else block should not allow the inner loop to continue: when you have a mismatch, you should not try matches with higher values of j, but you should exit that loop and try with the next value for i. So there needs to be a break in the else block
the condition len(match) > len(answer) is not enough to identify a solution. The reason for getting into the else block might have been that the characters didn't match, so in that case you should never update answer.
On the other hand, the update of answer is not happening now when the inner loop ends normally, i.e. when all compared characters were equal and i + j < len1 was always true. This case happens when the second input string is a suffix of the first. So you must make the update to answer somewhere else, so you also catch this case.
Here is the correction to your code, dealing with these issues:
def longestSubstringFinder(string1, string2):
answer = ""
len1, len2 = len(string1), len(string2)
for i in range(len1):
match = ""
for j in range(len2):
if (i + j < len1 and string1[i + j] == string2[j]):
match += string2[j]
# Move the assignment to answer here, and add condition that
# this was the last character of string1:
if i + j == len1 - 1 and len(match) > len(answer): answer = match
else:
break # Necessary!
if answer == '':
return 'No overlapping'
else:
return answer
With the use of string slicing, and comparing those slices instead of individual characters, you can make your code shorter and run faster.
Using RegEX, you can do it with lesser lines of code. I'm assuming you're a beginner in Python. If you are, then please learn RegEx and List Comprehension for this type of code.
import re
str1, str2 = input(), input()
def longestSubstringFinder(string1, string2):
list_of_subsets = [str1.replace(str1[:i], '') for i in range(len(str1))]
intersect = [re.search('^'+slc, str2).group() for slc in list_of_subsets if re.search('^'+slc, str2)]
if len(intersect) == 0:
return 'No overlapping'
else:
return intersect[0]
print(longestSubstringFinder(str1, str2))
a = str(input())
b = str(input())
g=len(a)-1
prefix = "No overlapping"
for i in range(len(a)):
if a[(g-i):] == b[:i+1]:
prefix = b[:i+1]
print(prefix)

While loop or If code? Stuck with this function

I'm asked to write a function generate_palindrome() that takes a given positive integer number n and applies the following procedure to it:
(i) Check if the number is palindrome. If it is, then return it otherwise continue with the next step.
(ii) Reverse the number and calculate the sum of the original number with the reversed number.
(iii) Repeat from (i) (until a palindrome is found.)
I wrote this function:
def generate_palindrome(n):
numbers = list(str(n))
for i in range(len(numbers)):
if numbers[i] == numbers[-i-1]:
return n
else:
while numbers[i] != numbers[-i-1]:
rev = list(reversed(numbers))
rev_num = int(''.join(rev))
n = n + rev_num
return n
I don't know for what reason when I try a random number that is not already palindrome, the code doesn't respond, it's still running until an indefinite amount of time. I tried changing it with an if code but it doesn't iterate my function, so I think my only chance is with the while code, but maybe I'm the one who's wrong. What do you think?
I think that you should've added a broken functionality to your while loop so that when a specific condition is achieved it breaks. And I think that the indentation of the last return statement is wrong. :)
Here you go:
#!/usr/bin/env python3
def generate_palindrome(num: int):
if str(num) == str(num)[::-1]:
return num
else:
while str(num) != str(num)[::-1]:
rev = int(str(num)[::-1])
num += rev
return num
if __name__ == '__main__':
print(generate_palindrome(212)) # prints 212
print(generate_palindrome(12)) # prints 33
print(generate_palindrome(43)) # prints 77
This is the best solution:
def generate_palindrome(n):
while True:
number = list(str(n))
num = ''
if number[::-1] == number:
for i in number:
num = num + i
print(num)
break
print(a)
else:
for i in number:
num = num + i
n = int(num) + int(num[::-1])
generate_palindrome()

Run length encoding python; String index out of range error

I'm trying to implement run length encoding into python with this code.
When I run it I get string index out of range error, not sure what is causing the error though
text="aaabbbcc"
def encode(text):
prev = text[0]
lentext = len(text)
i = 1
while prev == text[i] and i < lentext:
i += 1
return prev + str(i) + encode(text[i:])
print(encode(text))
Before you can check if i is less than the text length, you already try to access the ith element of text, which causes the exception. Instead, write your while loop as:
while i < lentext and prev == text[i]:
This will make sure i is in range before trying to access that index of text.
Also note that if you are going to use a recursive algorithm, you need a base case to exit the chain of recursive calls from. Probably something like the following at the top of your function:
if not text:
return ""
So all together:
text="aaabbbcc"
def encode(text):
if not text:
return ""
prev = text[0]
lentext = len(text)
i = 1
while i < lentext and prev == text[i]:
i += 1
return prev + str(i)+ encode(text[i:])
print(encode(text))

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)

Reverse loop for palindrome

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

Resources