How to write the code to get the required output - python

I need to write the code so that I get the required output (see image). When I run the code it doesn't show anything on the screen.
word = 'Python'
print("The original string is = ",end = '')
for ch in word : # ch will take each character from name
print(ch , end = ' ')
print("\n")
length = len(word) # len is function to give no. of characters
print("The reversed string is = ",end = '')
for ch in range(-1, (-length - 1), -1) :
print(word[ch], end = ' ')![enter image description here](https://i.stack.imgur.com/kSYlP.jpg)![enter image description here](https://i.stack.imgur.com/ehkHl.jpg)

I think this is what you expect:
word = 'Python'
print("The original string is = ",end = '')
for ch in word : # ch will take each character from name
print(ch , end = ' ')
print("\n")
length = len(word) # len is function to give no. of characters
print("The reversed string is = ",end = '')
for ch in range(-1, (-length - 1), -1) :
print(word[ch], end = ' ')
Please read this to understand how to fix the indentation.
https://www.python.org/dev/peps/pep-0008/#indentation

word = "Python"
stringlength=len(word)
slicedString=word[stringlength::-1]
print ("The original string is =",word)
print ("The reversed string is =",slicedString)

Related

how to extract a sentence from string in python using simple for loop?

str1 = "srbGIE JLWokvQeR DPhyItWhYolnz"
Like I want to extract I Love Python from this string. But I am not getting how to.
I tried to loop in str1 but not successful.
i = str1 .index("I")
for letter in range(i, len(mystery11)):
if letter != " ":
letter = letter+2
else:
letter = letter+3
print(mystery11[letter], end = "")
In your for loop letter is an integer. In the the first line of the loop you need to compare mystery[11] with " ":
if mystery11[letter] != " ":
You can use a dict here, and have char->freq mapping of the sentence in it and create a hash table.
After that you can simply iterate over the string and check if the character is present in the hash or not, and if it is present then check if its count is greater than 1 or not.
Don't know if this will solve all your problems, but you're running your loop over the indices of the string, This means that your variable letter is an integer not a char. Then, letter != " " is always true. To select the current letter you need to do string[letter]. For example,
if mystery11[letter] != " ":
...
Here's how I'd go about:
Understand the pattern of the input: words are separated by blank spaces and we should get every other letter after the first uppercase one.
Convert string into a list;
Find the first uppercase letter of each element and add one so we are indexing the next one;
Get every other char from each word;
Join the list back into a string;
Print :D
Here's the code:
def first_uppercase(str):
for i in range(0, len(str)):
if word[i].istitle():
return i
return -1
def decode_every_other(str, i):
return word[i::2]
str1 = "srbGIE JLWokvQeR DPhyItWhYolnz"
# 1
sentence = str1.split()
clean_sentence = []
for word in sentence:
# 2
start = first_uppercase(word) + 1
# 3
clean_sentence.append(decode_every_other(word, start))
# 4
clean_sentence = ' '.join(clean_sentence)
print("Input: " + str1)
print("Output: " + clean_sentence)
This is what I ended up with:
Input: srbGIE JLWokvQeR DPhyItWhYolnz
Output: I Love Python
I've added some links to the steps so you can read more if you want to.
def split(word):
return [char for char in word]
a = input("Enter the original string to match:- ")
b = input("Enter the string to lookup for:- ")
c = split(a)
d = split(b)
e = []
for i in c:
if i in d:
e.append(i)
if e == c:
final_string = "".join(e)
print("Congrats!! It's there and here it is:- ", final_string)
else:
print("Sorry, the string is not present there!!")

How to find the longest word in a string without using split method

I need an algorithm that can find the longest word in a string, I can't use split(), the only predefined function I can use is find() and I don't think it's useful for this solution.
This is what I managed to do so far:
ch=input("donner: ")
def plus_long(ch):
p=ch.find(" ")
if p==-1:
return ch
maximum=""
mot=""
while p!=-1:
mot=ch[:p]
print(mot)
ch=ch[p+1:]
print(ch)
if len(mot)>len(maximum):
maximum=mot
p=ch.find(" ")
return maximum
print("maximum est: ",plus_long(ch))
But this one doesn't check the last word because there are no more spaces.
EDIT: Thank you all for the answers, i realised how to solve it this morning by putting ch in a new variable and comparing it to maximum and it worked
ch=input("donner: ")
def plus_long(ch):
p=ch.find(" ")
if p==-1:
return ch
maximum=""
mot=""
while p!=-1:
mot=ch[:p]
print(mot)
ch=ch[p+1:len(ch)]
print(ch)
if len(mot)>len(maximum):
maximum=mot
p=ch.find(" ")
f=ch
if len(f)>len(maximum):
maximum=f
return maximum
print("maximum est: ",plus_long(ch))
I've split this problem into two parts:
Use find to create the list of words.
Find the longest word in the list.
def plus_long(ch):
letters = "abcdefghijklmnopqrstuvwxyz"
words = ['']
for v in ch:
if letters.find(v.lower()) != -1: # Use find to check if the character is part of the alphabet
words[-1] += v # If so, add that character to the last string in the list
else:
words.append('') # Else, start a new string
result = "" # Check which string is the longest
for word in words:
if len(word) > len(result):
result = word
return result
Test:
>>> plus_long("Hello!!!!!!!!!!! How are you? I am exhausted.")
Output:
'exhausted'
I see that the other answers don't put punctuation into account, so that using their functions, the result would be 'Hello!!!!!!!!!!!'.
You can find using split and len:
# Longest word
# Reading sentence from user
sentence = input("Enter sentence: ")
# Finding longest word
longest = max(sentence.split(), key=len)
# Displaying longest word
print("Longest word is: ", longest)
print("And its length is: ", len(longest))
The output is:
Enter sentence: Tongue tied and twisted just an earth bound misfit I
Longest word is: twisted
And its length is: 7
Here is your code with an addition that checks the last word (len) when p == -1 just as the loop is going to exit. This addition reported the correct max length if the last word is greater than maximum.
ch=input("donner: ")
def plus_long(ch):
p=ch.find(" ")
if p==-1:
return ch
maximum=""
mot=""
while p!=-1:
mot=ch[:p]
print(mot)
ch=ch[p+1:]
print(ch)
if len(mot)>len(maximum):
maximum=mot
p=ch.find(" ")
# 'ch' now has the last word in a sentence
# it needs to be checked against 'maximum'
if p == -1:
if len(ch) > len(maximum):
maximum = ch
return maximum
print("maximum est: ",plus_long(ch))
You can set p to None if the find method returns -1 so that ch[:p] would slice the rest of the string to get the last word:
def plus_long(ch):
maximum = ""
while True:
p = ch.find(" ")
if p == -1:
p = None
mot = ch[:p]
if len(mot) > len(maximum):
maximum = mot
if p is None:
break
ch = ch[p + 1:]
return maximum
Using find
def plus_long(ch):
longest = ""
i = 0
while i < len(ch):
n = ch.find(" ", i)
if n == -1:
n = len(ch)
if len(longest) < len(ch[i:n]):
longest = ch[i:n]
i = n+1
Test:
print (plus_long("there is a cat on a very big banana tree"))
print (plus_long("there is a cat on a mountain"))
print (plus_long("there"))
Output:
banana
mountain
there
ch=input("donner: ")
def plus_long(ch):
word = ''
maximum = ''
for letter in ch:
if letter == ' ':
if len(maximum) < len(word):
maximum = word
word = ''
else:
word += letter
return maximum
print("maximum est: ",plus_long(ch))
this is a very long and probably the worst method as far as Big 'O' Notation is concerned but it is a simple approach for beginners.
def longWord (sentence):
singleWord = ""
words = []
for letter in sentence:
if letter != " ":
singleWord += letter
else:
words += [singleWord]
singleWord = ""
words += [singleWord]
for i in range(len(words)-1):
biggestWord = ""
if len(words[i]) >= len(words[i+1]):
biggestWord += words[i]
else:
biggestWord += words[i+1]
print(words)
print(biggestWord)
longWord("This is a callback")
OUTPUT -
['This', 'is', 'a', 'callback']
callback
I know you already have a few answers. Here's a code with O(1)
ch=input("donner: ")
prev_pos = 0
max_word = ''
for i, sp in enumerate(ch):
if sp == ' ':
if len(ch[prev_pos:i]) > len(max_word): max_word = ch[prev_pos:i]
prev_pos = i+1
if len(ch[prev_pos:]) > len(max_word): max_word = ch[prev_pos:]
print ('longest word :', max_word, 'length :', len(max_word))
The output for this are:
donner: sentence
longest word : sentence length : 8
donner: this sentence
longest word : sentence length : 8
donner: this is a sentence
longest word : sentence length : 8
donner: this sentence is expectedly very lengthy
longest word : expectedly length : 10
donner: word is lengthy
longest word : lengthy length : 7
I wanted to give you an alternate approach as well. I have added comments for you to understand the code
ch=input("donner: ") #input the sentence
word = '' #capture each word in this variable
wd = [] #store all the words into this list
for sp in ch: #iterate thru the string
if sp != ' ': word += sp #concat to create the word
else:
wd.append(word) #add the word to list
word = '' #reset word
wd.append(word) #add the last word to the list
long_word = max(wd,key=len) #find the longest word
print ('longest word :',long_word, 'length :', len(long_word))

How does .append work in Python 2?

lword = (bword.lower())
word = str(lword)
spaces = []
for spaces in word:
if spaces == ' ':
spaces.append (' ')
else:
spaces.append('_')
print (spaces)
How would this look if it was in Python 2.7?
You made a mistake in your code:
lword = (bword.lower())
word = str(lword)
spaces = []
for character in word: # character is the temporally variable inside the for-loop
if character == ' '
spaces.append(' ')
else:
spaces.append('_')
print (spaces)
This code will give the result what you're expecting.

How to preserve and reverse a string?

Write a function that accepts a string of words separated by spaces
consisting of alphabetic characters and returns a string such that
each word in the input string is reversed while the order of the words
in the input string is preserved. Capitalization does matter here. The
length of the input string must be equal to the length of the output
string i.e. there should be no trailing or leading spaces in your
output string. For example if:
input_string = “this is a sample test”
then the function should return a string such as:
"siht si a elpmas tset"
This is my code:
def preserve_and_reverse (input_str):
list = input_str.split()
print (list)
reverse_character = ""
for i in range (0, len(input_str)):
split_list = list[0:(i + 1)]
print (split_list)
for j in split_list_advance:
reverse_character = reverse_character + split_list[j]
output_str = output_str.append(reverse_character)
output = output_str.replace("", " ")
print (output)
#Main Program
input_str = input("Enter a string: ")
result = preserve_and_reverse (input_str)
print (result)
I am not getting anywhere with the code. Should I try a different approach like traverse each character and when I encounter a white-space just slice the string and then perform a reverse?
Any help would be appreciated.
Split over spaces, reverse each string through map with [::-1] then join them back with ' '.join
>>> s = 'this is a sample test'
>>>
>>> ' '.join(map(lambda s:s[::-1], s.split()))
'siht si a elpmas tset'
This is how I would have done it:
def preserve_and_reverse(input_str):
# Split the String into an Array
list_ = input_str.split(" ")
return_str = ""
# For Each String in the Array
for item in list_:
# Add Reversed String to Return String
return_str += item[::-1] + " "
# Return String without leading/trailing spaces
return return_str.strip()
# Main Program
string_input = input("Enter a string: ")
result = preserve_and_reverse(string_input.strip())
print(result)
Something like this will do (step-by-step):
input_string = "this is a sample test"
words = input_string.split()
nwords = []
for i in words:
rword = ""
for c in reversed(word):
rword += c
nwords.append(rword)
output_string = " ".join(nwords)
print(output_string)
Result:
siht si a elpmas tset
Step by step explanation:
You split your input text into list of string:
words = input_string.split()
You iterate over the words
for word in words):
For each word, you prepare a reversed word rword and build up the reversed word by adding up character from the old word but reversed:
rword = ""
for c in reversed(word):
rword += c
nwords.append(rword)
you rejoin the reversed words - but in order and print it:
output_string = " ".join(nwords)
print(output_string)
Or, more simply:
input_string = "this is a sample test"
words = input_string.split()
output_string = ""
for word in words:
for c in reversed(word):
output_string += c
output_string += " "
print(output_string)
word[::-1] reverses the order of the string variable named word which is obtained by iterating through each split word in the sentence.
>>> ' '.join(word[::-1] for word in input_string.split())
'siht si a elpmas tset'
Step by step:
>>> input_string.split()
['this', 'is', 'a', 'sample', 'test']
>>> [word[::-1] for word in input_string.split()]
['siht', 'si', 'a', 'elpmas', 'tset']
>>> ' '.join(word[::-1] for word in input_string.split())
'siht si a elpmas tset'
All of the other answers so far ignore what happens when extra spaces are between words or at either end of the input string. Please test your code to verify that is works properly. The main function provided below has a few tests that you may want to use to verify your function is working properly, and you may want to add more tests if you find that your code is not behaving correctly:
def main():
print('Running test 1 ...')
text = 'this is a sample test'
par = preserve_and_reverse(text)
assert par == 'siht si a elpmas tset'
print('Running test 2 ...')
text = 'This is a sample TEST'
par = preserve_and_reverse(text)
assert par == 'sihT si a elpmas TSET'
print('Running test 3 ...')
text = 'This string has some extra spaces'
par = preserve_and_reverse(text)
assert par == 'sihT gnirts sah emos artxe secaps'
print('Running test 4 ...')
text = ' check spaces at string ends '
par = preserve_and_reverse(text)
assert par == ' kcehc secaps ta gnirts sdne '
print('Done!')
def preserve_and_reverse(text):
return ' '.join(word[::-1] for word in text.split(' '))
if __name__ == '__main__':
main()
def sample(string):
list=[]
string1=string.split()
for i in string1:
list.append(i[::-1])
print(" ".join(list))
if __name__=="__main__":
input=input("Enter string: ")
sample(input)

Converting a string to array of words - Python

I want to create a function in Python, where input will be the String and input it into an array to be returned.
For example:
Input: "The dog is red"
Output: "The", "dog", "is", "red"
I believe the algorithm should work, but nothing is returned. From what I can assume, the if statement is not detecting the space ( ").
The code is below:
string = input("Input here:")
def token(string):
start = 0
i = 0
token_list = []
for x in range(0, len(string)):
if " " == string[i:i+1]:
token_list = token_list + string[start:i+1]
print string[start:i+1]
start = i + 1
i += 1
return token_list
You can simply split the string.
result=input.split(" ")
or
string = raw_input("Input here:")
def token(string):
start = 0
i = 0
token_list = []
for x in range(0, len(string)):
if " " == string[i:i+1][0]:
token_list.append(string[start:i+1])
#print string[start:i+1]
start = i + 1
i += 1
token_list.append(string[start:i+1])
return token_list
print token(string)
You can modify your function to look like this:
string = input("Input here:")
def token(string):
start, i = 0, 0
token_list = []
for x in range(0, len(string)):
if " " == string[i:i+1]:
token_list.append(string[start:i+1])
start = i + 1
i += 1
token_list.append(string[start:i+1])
return token_list
print token(string)
You need to append only up until i if you don't want to include the trailing space. The second append is necessary because your condition is checking for a space to include the word, but the last word won't have a trailing space, and instead would have an end of line character or null.

Categories