The question was: Return a sentence with the words reversed
>>> master_yoda('I am home')
'home am I'
It will eventually reverse the words of the line.
I am learning and performing Python in Jupyter Notebook.
def master_yoda(string):
l = string.split()``
p = len(string) - 1
final = ''
while p<0:
final = final + ' ' + s[p]
p = p-1
print (final)
master_yoda('Hello my name is Aryan')
The output is nothing..
No syntax errors , but still no output ...
Perhaps you should try this.
def master_yoda(string):
reversed_list = string.split(' ')
reversed_list.reverse()
reversed_string = ' '.join(reversed_list)
print(reversed_string)
master_yoda("i am home")
The big problem with the code is that you were testing for p < 0 but since p starts off with a positive value, the code never enters the while loop. You should really have been testing for p >= 0. The following code should do what you want, they way you seem to want it to:
def master_yoda(string):
l = string.split()
p = len(l) - 1
final = l[p]
p -= 1
while p >= 0:
final += ' ' + l[p]
p -= 1
return final
Note that this implementation fails if an empty string is passed as input. I tried to keep the code in the spirit of your own code and checking for an empty string would make it more complex. The simplest and most robust solution would be:
def master_yoda(string):
return ' '.join(reversed(string.split()))
Related
Hello I have to reorder a string, I am banned from using other types and str methods
So my problem is that I could not figure out how to end my code to get it work with any string
I tried to compare the results with sorted() to check and I am stuck at the first exchange
My code:
i = 0
s1 = "hello"
s2 = sorted(s1)
while (i<len(s1)):
j=i+1
while (j<=len(s1)-1):
if (s1[i] > s1[j]):
s1 = s1[0:i] + s1[j] + s1[i]
j+=1
i+=1
print(s1)
print(s2)
I tried to add + s1[len(s1):] at the end of the operation but
I only had found the result for a single string(that I was testing) adding thisI am really stuck, how can I make it work for all the strings with different lenghts??
Thanks
You're not reconstructing the string correctly when doing s1 = s1[0:i] + s1[j] + s1[i] as you're replacing one character for the other but you omit to actually interchange the two and to add the remains of the splitted string to the end of the new string.
Given what your code looks like, I would do it like this:
i = 0
s1 = "hello"
s2 = sorted(s1)
while i < len(s1):
j = i + 1
while j <= len(s1)-1:
if s1[i] > s1[j]:
s1 = s1[0:i] + s1[j] + s1[i+1:j] + s1[i] + s1[j+1:len(s1)]
j += 1
i += 1
print("".join(s2))
# > 'ehllo'
print(s1)
# > 'ehllo'
Please tell me if anything is unclear!
I am banned from using other types and str methods
Based upon your criteria, your request is impossible. Just accessing the elements of a string requires string methods.
The technique that you are using is very convoluted, hard to read and is difficult to debug. Try running your code in a debugger.
Now given that you are allowed to convert a string to a list (which requires string methods), redesign your code to use simple, easy to understand statements.
The following code first converts the string into a list. Then loops thru the list starting at the beginning and compares each following character to the end. If any character is less then the current character, swap. As you step thru the string, the character swaps will result in a sorted list. At the end convert the list back to a string using join().
msg = 'hello'
s = list(msg)
for i in range(len(s) - 1):
for j in range(i + 1, len(s)):
if s[i] <= s[j]:
continue
# swap characters
s[i], s[j] = s[j], s[i]
print(msg)
print(''.join(s))
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)
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))
I was trying to complete a merge sort in Python. I found when I use middle = (len(x)-1)//2, the right part was in infinity loop and never reached the base case, but if I changed middle = len(x)//2, it worked normally. So why?
The solution does lie in the middle variable. After abit of experimenting I found that using middle = len(alist)//2 fixes the whole program. Despite this not being technically mathematical, it does seem to work.
You could also increase efficiency by replacing the if and else at the start of the mergesort() function with a simple if len(alist) > 1: and then return alist at the end of the function, rather than at the end of each if and else, if that makes sense. (This would also mean you can just replace the com variable with alist).
For reference, heres my code (some variables are renamed):
from random import shuffle
### INIT ###
arr = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]
shuffle(arr)
print("Starting List: " + str(arr))
### SORT ###
# Merge
def merge(left,right):
sorted = []
i, j = 0, 0
while i < len(left) and j < len(right):
if left[i] < right[j]:
sorted.append(left[i])
i += 1
else:
sorted.append(right[j])
j += 1
sorted += right[j:]
sorted += left[i:]
return sorted
# Decomposition
def sort(arr):
#print(arr)
if len(arr) > 1:
middle = len(arr)//2
left = sort(arr[:middle])
right = sort(arr[middle:])
arr = merge(left, right)
return arr
arr = sort(arr)
print("Ending List: " + str(arr))
Good afternoon everyone,
I'm trying to sort out names which are already sorted in alphabetical order. I can't figure out why my program isn't working. Any tips or pointers would be nice. Thanks.
def main():
names = ['Ava Fiscer', 'Bob White', 'Chris Rich', 'Danielle Porter', 'Gordon Pike', 'Hannah Beauregard', 'Matt Hoyle', 'Ross Harrison', 'Sasha Ricci', 'Xavier Adams']
input('Please enter the name to be searched: ', )
binarySearch
main()
def binarySearch(names):
first = 0
last = len(names) - 1
position = -1
found = False
while not found and first <= last:
middle = (first + last) / 2
if names[middle] == value:
found = True
position = middle
elif arr[middle] > value:
last = middle -1
else:
first = middle + 1
return position
What does it mean that the program isn't working? Is it a syntax error or is the problem in the wrong results?
With the code you pasted, there are several indentation problems, but besides that, lines:
input('Please enter the name to be searched: ', )
binarySearch
are also syntactically incorrect, the comma is redundant and only the function name appearing just like that is plain wrong. If you are interested in the correctness of your algorithm, it seems alright, but the boundaries can always be tricky. My code below is working and syntactically correct, if you find it helpful. (names are numbers, but that is irrelevant in this case)
names = [1,2,4,5,6,8,9]
def bs(n):
start = 0
end = len(names)
while end - start > 0:
m = (start+end)/2
if names[m] == n:
return m
elif n < names[m]:
end = m
else:
start = m + 1
return -1
print (bs(1))
print (bs(6))
print (bs(9))
print (bs(3))
print (bs(10))
print (bs(-8))
Another thing I would like to point out is that this kind of binary search is already in the python standard library, the bisect module. However, if you are writing your own for practice or for any other reason that is just fine.
if you are using python 3.* then you are going to want to change
m = (start+end)/2
to
m = (start+end)//2
When you do /2 it outputs a float in 3.*