When execute code below I receive the message error str concatenate - python-3.x

Hy guys! I started learn programming. And when execute code below I receive the message error str concatenate.
import random
word_list = ["ababababababab", "baloon", "banana"]
chosen_word = random.choice(word_list)
print(chosen_word)
guess = input("Guess the word, type one letter: \n").lower()
i = 0
while (i < len(chosen_word)):
for i in chosen_word:
if i == guess:
print(guess)
i += 1
The message error:
TypeError: can only concatenate str (not "int") to str

j = ""
for j in chosen_word:
if j == guess:
print(guess)
Use one loop.

Try this way, put input in a while loop (why did you do while condition in parenthesis?). Another thing that I've changes is to use if statement insted for loop.
import random
word_list = ["ababababababab", "baloon", "banana"]
chosen_word = random.choice(word_list)
print(chosen_word)
i = 0
while i < len(chosen_word):
guess = input("Guess the word, type one letter: \n").lower()
if guess in chosen_word:
print(f'Yep {guess} is in a word')
i += 1

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)

How to get through the whole list with if statement even if the first conditin was met?

The code below is for a hangman game. When the if statement finds the first letter it stops and doesn't go further through the list, so it doesn't add the duplicates. For example, if a word contains two a letters, then it will only add the first one.
words = ["harry potter", "i love you forever", "neverland", "pockahontas"]
lives = 3
hangman = list(random.choice(words))
copy_of_hangman = hangman.copy()
print(copy_of_hangman)
for i in range(-6, 6, 2):
copy_of_hangman[i] = "_"
print(copy_of_hangman)
while lives != 0:
guess = input("Make your guess: ")
for letter in hangman:
if letter == guess:
copy_of_hangman[hangman.index(letter)] = guess
print(" ".join(copy_of_hangman))
You need to use a while loop.
So instead of copy_of_hangman[hangman.index(letter)] = guess
you can use something like (untested):
pos = hangman.index(letter)
while pos != None:
copy_of_hangman[pos] = guess
pos = hangman.index(letter)

Where is issue with final display in this code?

The code requires the user to provide an input of strings and convert the uppercase to lower and vice-versa.Input: Rohit Tapadia , Expected Output: rOHIT tAPADIA , Actual Output: rOHIt TAPADIA . It should do exactly what the swapcase() does.
inp = input("Enter ")
for i in inp:
inp_lst.append(i)
print(inp_lst)
for j in inp_lst:
if j.isupper()==True:
x=inp_lst.index(j)
#print(x)
#print(j)
k = j.lower()
#print(k)
inp_lst[x]=k
print(inp_lst[x])
elif j.islower()==True:
y=inp_lst.index(j)
#print(y)
#print(j)
l = j.upper()
inp_lst[y]=l
print(inp_lst[y])
else:
z=inp_lst.index(j)
#print(z)
#print(j)
inp_lst[z]=j
print(inp_lst[z])
print(''.join(inp_lst))```
You can achieve exactly the same thing in 2 lines with the built-in swapcase() method:
inp = input("Enter ")
print(inp.swapcase())
Example input:
heLLo StackOverflow
Output:
HEllO sTACKoVERFLOW
Demo: https://repl.it/#glhr/55548482
Edit: here's a working and simplified implementation of your code. Note that inp_lst is not needed since you can directly iterate over characters in a string. You can simply add each character to the output string using string concatenation (not that outputString += j is equivalent to outputString = outputString + j - it simply adds j at the end of the string).
inp = input("Enter ")
outputString = ""
for j in inp:
if j.isupper():
outputString += j.lower()
elif j.islower():
outputString += j.upper()
else:
outputString += j
print(outputString)
Edit 2: The problem in your code is this inp_lst.index(j), because index() searches for the first occurrence of the character j. So if j='t', it will select the first occurrence of t in the list, and turn it uppercase/lowercase, even if the loop is at the second occurrence of t. That's why the first t in "Rohit Tapadia" is turned to lowercase in the output.
you can try this one too
inp = input("Enter ")
output="".join([char.lower() if char.isupper() else char.upper() for char in inp ])
inp = "Rohit Tapadia"
output will be
rOHIT tAPADIA

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)

pig latin issues with output code for python

I am having trouble with the code only producing the first two letters of the first word and then attaching the 'AY' to the end while it runs. I can't seem to figure out how to correct this error.
def main():
strin = input('Enter a sentence (English): ')
strlist = strin.split()
i = 0
pigsen = ''
while i < len(strlist):
word = strlist[i]
j = 1
fc = word[0].upper()
pigword =''
while j < len(word):
pigword += word[j].upper()
j += 1
pigword += fc + 'AY'
pigsen += pigword + ' '
i +=1
print('Pig Latin: ' +str(pigsen))
main()
First, I'll assume this is just the start of a pig Latin generator and you'll add the other rules (at least a couple more) once you get this much working. Second, let's simplify the code as a way of fixing it:
def main():
sentence = input('Enter a sentence (English): ')
words = sentence.upper().split()
latin_words = []
for word in words:
first, rest = word[0], word[1:]
latin_word = rest + first + 'AY'
latin_words.append(latin_word)
print('Pig Latin:', *latin_words)
main()
USAGE
> python3 test.py
Enter a sentence (English): He complimented me on my English
Pig Latin: EHAY OMPLIMENTEDCAY EMAY NOAY YMAY NGLISHEAY
>
I would say the problem with your code is you made it too complicated.

Resources