how to shift a string to right and reverse it in python? - python

Shift word to right and then reverse it.
You should take a word shift to right and reverse it then return as follows:
>>> shift_reverse('Introduction to Computer Programming')
gnimmargorP noitcudortnI ot retupmoC
I tried using this method to find the above answer but it doesnt seem to work
Please help :(
s= "I Me You"
def shift_reverse(s):
l= s.split()
new_str= ' '.join(l[-1:] + l[:-1])
new_str = new_str[::-1]
return (new_str)
print (shift_reverse(s))
but the print i get is
[evaluate untitled-3.py]
eM I uoY

You need to reverse each of the re-ordered list:
reordered = l[-1:] + l[:-1]
new_str = ' '.join(word[::-1] for word in reordered)

You can join a generator expression that generates reversed words in the rotated split list:
>>> s = 'Introduction to Computer Programming'
>>> ' '.join(w[::-1] for w in (lambda l: l[-1:] + l[:-1])(s.split()))
'gnimmargorP noitcudortnI ot retupmoC'

Here is a step by step with the functions:
Create shift function to move last word to beginning:
def shift(sentence):
words = sentence.split()
return ' '.join([words[-1]] + words[:-1])
Create reverse function to reverse all words in a sentence (uses list comprehension):
def reverse(sentence):
return ' '.join([word[::-1] for word in sentence.split()])
Create shift_reverse to reverse all words and then shift the last on to the start:
def shift_reverse(sentence):
return shift(reverse(sentence))
Result:
shift_reverse('Introduction to Computer Programming')
Output:
'gnimmargorP noitcudortnI ot retupmoC'

In new_str = new_str[::1], you're reversing the entire string, character per character.
ghi abc def
fed cba ihg
You have to reverse each word in the list of words.
def shift_reverse(string):
words = string.split()
shifted_words = [words[-1]] + words[:-1]
return ' '.join([word[::-1] for word in shifted_words])

You can shift the string over, the reverse each item:
>>> phrase = 'Introduction to Computer Programming'
>>> new = ' '.join([word[::-1] for word in [phrase.split()[-1]]+phrase.split()[:-1]])
>>> print new
gnimmargorP noitcudortnI ot retupmoC
>>>

def shift_reverse(s):
rev = ["".join(reversed(word)) for word in s.split(" ")]
return "{} {}".format(rev.pop(), " ".join(rev))
reverse all the strings, pop the last off the list of reversed words and join the remainder.

This should work for you
s= "Introduction to Computer Programming"
def shift_reverse(s):
l= s.split()
l = [l.pop()]+ l
return ' '.join(i[::-1] for i in l)
print (shift_reverse(s))
output:
gnimmargorP noitcudortnI ot retupmoC

Related

Wrong output in function

Hi I'am totally new to programmering and i have just jumped into it.
The problem i am trying to solve is to make a function that standardized an adress as input.
example:
def standardize_address(a):
numbers =[]
letters = []
a.replace('_', ' ')
for word in a.split():
if word. isdigit():
numbers. append(int(word))
elif word.isalpha():
letters.append(word)
s = f"{numbers} {letters}"
return s
Can someone help me explain my error and give me a "pro" programmers solution and "noob" (myself) solution?
This is what i should print:
a = 'New_York 10001'
s = standardize_address(a)
print(s)
and the output should be:
10001 New York
Right now my output is:
[10001] ['New', 'York']
Issues
strings are immutable so you need to keep the replace result, so do a = a.replace('_', ' ') or chain it before the split call
You need to concatenate the lists into one numbers + letters then join the elements with " ".join()
don't convert the numeric to int, that's useless and would force you to convert them back to str in the " ".join
def standardize_address(a):
numbers = []
letters = []
for word in a.replace('_', ' ').split():
if word.isdigit():
numbers.append(word)
elif word.isalpha():
letters.append(word)
return ' '.join(numbers + letters)
Improve
In fact you want to sort the words regarding the isdigit condition, so you can express that with a sort and the appropriate sorted
def standardize_address(value):
return ' '.join(sorted(value.replace('_', ' ').split(),
key=str.isdigit, reverse=True))
numbers and letters are both lists of strings, and if you format them they'll be rendered with []s and ''s appropriately. What you want to do is to replace this:
s = f"{numbers} {letters}"
return s
with this:
return ' '.join(numbers + letters)
numbers + letters is the combined list of number-strings and letter-strings, and ' '.join() takes that list and turns it into a string by putting ' ' between each item.

How to acces the next value in for loop

So im trying to get first letters of words(excluding first word, i already solved that) in a sentence.
But it appends spaces to the list.
Would appreciate if you help.
Here's the code:
lst = []
for t in (input()):
if t == " ":
lst.append(t)
print(*lst, sep="")
input1: asd dfd yjs
output1: dy
just this:
''.join([s[0] for s in input().split()[1:]])
step by step:
if input() returns asd dfd yjs
split string (more):
input().split() # output: ['asd', 'dfd', 'yjs']
sub list (more):
input().split()[1:] # output: ['dfd', 'yjs']
one line loop (more):
[s[0] for s in ['dfd', 'yjs']] # output: ['d', 'y']
sub string (more):
s="dfd"
s[0] # output: d
concat list of strings (more):
''.join(['d', 'y']) # output: dy
You're getting spaces because that's what you asked for. Read your code out loud and it will probably make sense:
if t == " ":
lst.append(t)
If t is a space, append it to lst
Seems clear that you will only get spaces.
You want the character after t to be appended. There's two ways to do that using your for loop method: 1) if t is a space, append the next character; 2) if the previous character was a space, append t. Here's how you might implement #2:
lst = []
prev_char = None
for t in (input()):
if prev_char == " ":
lst.append(t)
prev_char = t
print(*lst, sep="")
This will print the first character of ever word except the first word. Initialize last_char to a space to include the first word.
You may
split your sentence into words using x.split()
remove the first word, using a slice [1:] (from index 1 to the end)
then keep only the first char of each word and concatenate it to a result string
x = input(">")
result = ""
for word in x.split()[1:]:
result += word[0]
print(result) # dy
Using a generator and str.join :
x = input(">")
result = ''.join(word[0] for word in x.split()[1:])
You could use str.split:
lst = [s[0] for s in input().split()[1:]]
A simple example:
lst = []
get_next = False
for t in input():
if t == " ":
get_next = True
elif get_next:
lst.append(t)
get_next = False
print(*lst, sep="")
A lot great answers already and this is good case for split. If you specifically need to collect the next token after a special token in a stream of tokens, here are some other options:
inp = "asd dfd yjs"
lst = []
for a, b in zip(inp[:-1],inp[1:]):
if a == " ":
lst.append(b)
print(*lst, sep="")
# With comprehensions - my choice
print("".join([b for a, b in zip(inp[:-1],inp[1:]) if a == " "]))
# With functional approach
from functools import reduce
from operator import add, itemgetter
def has_prior_space(x):
return x[0] == " "
print(reduce(add, map(itemgetter(1), filter(has_prior_space, zip(inp[:-1], inp[1:])))))
In Python 3.10, there will be a new pairwise iterator that does this type of "2 at a time" iteration specifically: zip(inp[:-1],inp[1:])
Use Array join():
''.join(lst)

Pig Latin In Python Conversion

def convert_pig_latin(pig):
first_letter = pig[0]
#Check if Vowel
if first_letter in 'aeiou':
pig_word = pig + 'ay'
else:
pig_word = pig[1:] + first_letter + 'ay'
print('Pig Latin:',pig_word)
So basically, this only works for 1 single word input. Let's say the user enters a sentence, it won't work which is obvious. This code is in my functions tab, and my main module of course runs it with an input sentence given. Could someone please help me out how it'll take a whole sentence instead of just one word -.- Tried using a for loop but messed it up.
Appreciate it, thanks!
You could use a list comprehension here:
def pig_latin(sentence):
return ' '.join([s + 'ay' if s[0] in 'aeiou' else s[1:] + s[0] + 'ay' for s in sentence.split()])
print(pig_latin("convert all the words"))
Output:
onvertcay allay hetay ordsway
You could also keep your current approach where the function converts a single word, and use map():
>>> def pig_latin_word(s):
... return s + 'ay' if s[0] in 'aeiou' else s[1:] + s[0] + 'ay'
...
>>> ' '.join(map(pig_latin_word, "convert all the words".split()))
'onvertcay allay hetay ordsway'
>>>
Convert the string into a list of strings:
words = pig.split(' ')
Then you would run a for loop on the list:
for word in words:
#run your conversation code on each word
Then join the list back into a string:
pig = ' '.join(words)

Removing the square brackets, commas and single quote?

Python 3. I am trying to return the function so that It would take a single word and convert it to Cow Latin. I want to get rid of the square bracket, the comma and single apostrophes when I run my function.
My function is:
alpha = list("bcdfghjklmnpqrstvwxyz")
def cow_latinify_word(word):
if word[0].lower() in alpha:
lista = (word.lower())
return lista[1:] + lista[0] + "oo"
else:
return word + "moo"
def cow_latinify_sentence(sentence):
words = sentence.split();
return [cow_latinify_word(word) for word in words]
when I test the function with
cow_latin = cow_latinify_sentence("Cook me some eggs")
print(cow_latin)
I get ['ookcoo', 'emoo', 'omesoo', 'eggsmoo'] but I want ookcoo emoo omesoo eggsmoo
Just add an asterisk before the variable name to unpack the list and feed its elements as positional arguments to print.
print(*cow_latin)
Use ' '.join(list) for concatenating the list elements into a string.
In your code:
alpha = list("bcdfghjklmnpqrstvwxyz")
def cow_latinify_word(word):
if word[0].lower() in alpha:
lista = (word.lower())
return lista[1:] + lista[0] + "oo"
else:
return word + "moo"
def cow_latinify_sentence(sentence):
words = sentence.split();
return ' '.join([cow_latinify_word(word) for word in words])
Your function cow_latinify_sentence returns a list of strings you need to join with spaces to get your desired output:
print(" ".join(cow_latin))
Let's define our variables:
>>> consonants = "bcdfghjklmnpqrstvwxyz"
>>> sentence = "Cook me some eggs"
Find the cow-latin:
>>> ' '.join(word[1:] + word[0] + 'oo' if word[0] in consonants else word + 'moo' for word in sentence.lower().split())
'ookcoo emoo omesoo eggsmoo'

Python cleaning words in a sentence

I am trying to write a function that accepts a string (sentence) and then cleans it and returns all alphabets, numbers and a hypen. however the code seems to error. Kindly know what I am doing wrong here.
Example: Blake D'souza is an !d!0t
Should return: Blake D'souza is an d0t
Python:
def remove_unw2anted(str):
str = ''.join([c for c in str if c in 'ABCDEFGHIJKLNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890\''])
return str
def clean_sentence(s):
lst = [word for word in s.split()]
#print lst
for items in lst:
cleaned = remove_unw2anted(items)
return cleaned
s = 'Blake D\'souza is an !d!0t'
print clean_sentence(s)
You only return last cleaned word!
Should be:
def clean_sentence(s):
lst = [word for word in s.split()]
lst_cleaned = []
for items in lst:
lst_cleaned.append(remove_unw2anted(items))
return ' '.join(lst_cleaned)
A shorter method could be this:
def is_ok(c):
return c.isalnum() or c in " '"
def clean_sentence(s):
return filter(is_ok, s)
s = "Blake D'souza is an !d!0t"
print clean_sentence(s)
A variation using string.translate which has the benefit ? of being easy to extend and is part of string.
import string
allchars = string.maketrans('','')
tokeep = string.letters + string.digits + '-'
toremove = allchars.translate(None, tokeep)
s = "Blake D'souza is an !d!0t"
print s.translate(None, toremove)
Output:
BlakeDsouzaisand0t
The OP said only keep characters, digits and hyphen - perhaps they meant keep whitespace as well?

Categories

Resources