I have created the following code to scramble the letters in a word (except for the first and last letters), but how would one scramble the letters of the words in a sentence; given the input asks for a sentence instead of a word. Thank you for your time!
import random
def main():
word = input("Please enter a word: ")
print(scramble(word))
def scramble(word):
char1 = random.randint(1, len(word)-2)
char2 = random.randint(1, len(word)-2)
while char1 == char2:
char2 = random.randint(1, len(word)-2)
newWord = ""
for i in range(len(word)):
if i == char1:
newWord = newWord + word[char2]
elif i == char2:
newWord = newWord + word[char1]
else:
newWord = newWord + word[i]
return newWord
main()
May I suggest random.shuffle()?
def scramble(word):
foo = list(word)
random.shuffle(foo)
return ''.join(foo)
To scramble the order of words:
words = input.split()
random.shuffle(words)
new_sentence = ' '.join(words)
To scramble each word in a sentence, preserving the order:
new_sentence = ' '.join(scramble(word) for word in input.split())
If it's important to preserve the first and last letters as-is:
def scramble(word):
foo = list(word[1:-1])
random.shuffle(foo)
return word[0] + ''.join(foo) + word[-1]
Split the sentence into a list of words (and some punctuation) with the split method:
words = input().split()
and then do pretty much the same thing you were doing before, except with a list instead of a string.
word1 = random.randint(1, len(words)-2)
...
newWords = []
...
newWords.append(whatever)
There are more efficient ways to do the swap than what you're doing, though:
def swap_random_middle_words(sentence):
newsentence = list(sentence)
i, j = random.sample(xrange(1, len(sentence) - 1), 2)
newsentence[i], newsentence[j] = newsentence[j], newsentence[i]
return newsentence
If what you actually want to do is apply your one-word scramble to each word of a sentence, you can do that with a loop or list comprehension:
sentence = input().split()
scrambled_sentence = [scramble(word) for word in sentence]
If you want to completely randomize the order of the middle letters (or words), rather than just swapping two random letters (or words), the random.shuffle function is likely to be useful.
Related
def spin_words(sentence):
words = sentence.split(' ')
newwords = []
reverse = []
for word in words:
if len(word) < 5:
newwords.append(word)
elif len(word) >= 5:
newword = list(word)
for letter in newword:
reverse.insert(0, letter)
newwords.append(''.join(reverse))
return ' '.join(newwords)
print(spin_words('Welcome'))
print(spin_words('to'))
print(spin_words('CodeWars'))
print(spin_words('Hey fellow warriors'))
Working on a Codewars kata for python. Need to take a string and reverse any words that are 5 or more characters long. This code works for single words, but once more than one word is 5 or more characters, it adds those words together for each following word. Ex: my 'Hey fellow warriors' comes back as 'Hey wollef sroirrawwollef' . I am just not sure why is is putting different words together and how to fix it. As far as I know, the for loop in the elif should close out for each word. I know it should be simple, just trying to learn what's happening and why. Thank you!
Simple answer:
You have to clear your reversed word:
def spin_words(sentence):
words = sentence.split(' ')
newwords = []
reverse = []
for word in words:
if len(word) < 5:
newwords.append(word)
elif len(word) >= 5:
newword = list(word)
for letter in newword:
reverse.insert(0, letter)
newwords.append(''.join(reverse))
reverse = [] # Clear the list.
return ' '.join(newwords)
print(spin_words('Welcome'))
print(spin_words('to'))
print(spin_words('CodeWars'))
print(spin_words('Hey fellow warriors'))
Output:
emocleW
to
sraWedoC
Hey wollef sroirraw
Nicer answer:
After Ignatius Reilly's comment I made my solution a bit more elegant:
def spin_words(sentence):
words = sentence.split(' ')
newwords = []
for word in words:
if len(word) >= 5:
word = word[::-1]
newwords.append(word)
return ' '.join(newwords)
Here is how I reversed the word.
Output is the same.
this is my code, I want to know where the problem is with this code
And also, instead of removing and, no, i from the list; replace it with a number.
word = input("your sentece in english : ")
Word = word.split()
Word = word.lower()
new_word = ""
delet = ["and","no","i"]
print(Word)
for m in Word:
if m not in delet:
new_word = new_word + m
print(new_word)
Try using enumerate,
for index, m in enumerate(Word): if m in delet: Word[index] = int
Alright, I am scrambling words here and want to store a scrambled array alongside the original array of words.
Initially I create my array:
randomwords = ['pepper', 'lightning', 'bored', 'teeth', 'floor', 'special', 'coffee', 'dopamine']
Then to scramble:
for j in range(len(randomwords)):
word = randomwords[j] # original
newword = ''
for i in range(len(word)):
newchar = random.choice(word)
while(newchar in newword):
newchar = random.choice(word)
newword = newword[:i]+str(newchar)+newword[i:]
shuffledwords.append(newword)
This works for the first word, or if I just have 1 object in the array, but with multiple Pycharm freezes. I don't know what is going on.
Am I creating an infinite loop somehow?
EDIT I need to do this manually, not using shuffle
I am now trying with indices however still have infinite loop:
for j in range(len(randomwords)):
word = randomwords[j] # original
newword = ''
indices = []
for i in range(len(word)):
newchar = random.choice(word)
while(word.index(newchar) in indices):
newchar = random.choice(word)
indices.append(word.index(newchar))
newword = newword[:i]+str(newchar)+newword[i:]
shuffledwords.insert(j, word)
I think you do have an infinite loop.
newchar = random.choice(word)
randomly selects a letter in word.
If word contains duplicate letters, then newword will contain all the letters in word before your for i in range(len(word)) loop is done. That will create an infinite loop with while (newchar in newword)
Consider "pepper":
Imagine in the first 3 iterations you select "p","r" and "e". The for i loop is not yet done, but newchar = random.choice(word) will always select a character already in newword
I would try creating a list of the letters in the word you're scrambling, and then randomly removing one letter at a time from that list, until it is empty.
================================================================
Late edit, but wanted to show 1 way to do this manually....
import random
randomwords = ['pepper', 'lightning', 'bored', 'teeth',
'floor', 'special', 'coffee', 'dopamine']
shuffledwords = []
for j in range(len(randomwords)):
word = randomwords[j] # original word to scramble
newword = '' #scrambled word
num_letters = len(word) #original number of letters in word
for i in range(num_letters):
# pick raandom letter from those still in word
curr_idx = random.randrange(len(word))
newchar = word[curr_idx]
#print (newchar)
# remove chosen letter from original word
if curr_idx == 0:
word = word[1:]
elif curr_idx == len(word)-1:
word = word[0:-1]
else:
word = word[0:curr_idx] + word[curr_idx+1:]
# Add chosen letter to scrambled word
newword = newword[:i]+str(newchar)+newword[i:]
#print(newword)
shuffledwords.append(newword)
This should do it for you!
import random
randomwords = ['pepper', 'lightning', 'bored', 'teeth', 'floor', 'special', 'coffee', 'dopamine']
def scrmble(var):
scrbled=var[:]
random.shuffle(scrbled)
return (scrbled)
newlist = scrmble(randomwords)
print(randomwords, newlist)
This will scramble the words and all the char inside each word.
import random
randomwords = ['pepper', 'lightning', 'bored', 'teeth', 'floor', 'special', 'coffee', 'dopamine']
randomwords = random.sample(randomwords,len(randomwords))
new_word = ""
for word in randomwords:
word1 = random.sample(word, len(word))
new_word = new_word + ''.join(word1) + " "
print(new_word)
Result: "gnhinligt folor lesacpi prpepe ediaopmn hteet ecffoe edorb"
Probelm Description:
sms_encoding() which accepts a sentence and converts it into an abbreviated sentence to be sent as SMS and returns the abbreviated sentence.
Rules are as follows:
a. Spaces are to be retained as is
b. Each word should be encoded separately
If a word has only vowels then retain the word as is
If a word has a consonant (at least 1) then retain only those consonants
My Code:
#PF-Assgn-50
def sms_encoding(data):
#start writing your code here
vowels=set("aeiouAEIOU")
v_list=[]
c_list=[]
final_list=[]
new_string=''
word=data.split()
word2=[]
for i in range(0,len(word)):
ch=word[i]
#print(ch)
if ch in vowels:
v_list.append(ch)
for letter in word[i]:
if letter not in vowels:
c_list.append(letter)
c_list.append(" ")
new_string=''.join(v_list)+''.join(c_list)
final_list.append(new_string)
#print(v_list)
return ' '.join(final_list)
data="Have a Nice Day"
print(sms_encoding(data))
My Output:
aHv **<2spaces>** Nc **<1space>** Dy
Expected Output:
Hv a Nc Dy (contains only 1 space)
You could iterate over words in the sentence taking only consonants only if the word contains atleast one consonant:
data = "Have a Nice Day"
splitted = data.split()
for i, x in enumerate(splitted):
if not all(y in 'aeiou' for y in x.lower()):
splitted[i] = ''.join([y for y in x if y.lower() not in 'aeiou'])
print(' '.join(splitted))
# Hv a Nc Dy
This will work for all cases... retains all except vowels when even 1 character in a string is not vowel.
def sms_encoding(data):
vowels = set("aeiouAEIOU")
words = data.split()
encoded_words = []
for i in range(0,len(words)):
vow_count = 0
cons_word = []
for x in words[i]:
if x in vowels:
vow_count =vow_count+1
elif x not in vowels:
cons_word.append(x)
if vow_count == len(words[i]):
encoded_words.append(words[i])
elif vow_count != len(words[i]):
encoded_words.append("".join(cons_word))
encoded_msg = " ".join(encoded_words)
return encoded_msg
data=input("Kindly enter your message for sms encoding : ")
print(sms_encoding(data))
Try and let me know!
def sms_encoding(data):
vowel = "aeiouAEIOU"
list1 = data.split()
list2 = []
for i in list1:
length=len(i)
if length == 1:
list2.append(i)
list2.append(" ")#to add spaces between the words
else:
count=0
for a in i:
if a in vowel:
count+=1
if count==length: #to check if all the letters are vowels
list2.append(i)
list2.append(" ")
for a in i:
if a not in vowel:
list2.append(a)
list2.append(" ")
list2.pop() #to remove the extra space at the end of the whole sentence
q="".join(list2)
return q
data = "I love Python aeio"
print(sms_encoding(data))
try this code it will work the question is from infytq
def sms_encoding(data):
data=data.lower()
a=data.split()
v1=""
for i in range(0,len(a)):
z=a[i]
v=""
c1=0
for j in z:
if j not in ('a','e','i','o','u'):
v=v+j
elif j in ('a','e','i','o','u'):
c1=c1+1
if(c1!=len(z)):
v1=v1+v+" "
elif(c1==len(z)):
v1=v1+z+" "
word=v1[0:len(v1)-1]
return word
data="I love Python"
print(sms_encoding(data))
def sms_encoding(new_s):
encrypt_string = []
consonant_list = []
vowel_set = set("aeiouAEIOU")
for word in range(0, len(new_s)):
v_letter = new_s[word]
if v_letter in vowel_set:
encrypt_string.append(v_letter)
for letter in v_letter:
if letter not in vowel_set:
consonant = " ".join(letter)
encrypt_string.append(consonant)
encrypt_string.append(" ")
encrypt_string = "".join(encrypt_string)
print(encrypt_string)
s = input("Enter a string ")
new_s = s.split()
sms_encoding(new_s)
I'm a beginner learning the python language and I'm stumped on how take the vowels of a word and replacing them with an underscore.
So far this is what I have come up with and it just doesn't work
word = input("Enter a word: ")
new_word = ""
vowels = "aeiouy"
for letter in word:
if letter != vowels:
new_word += word
else:
new_word += "_"
print(new_word)
You can use string.translate and maketrans.
from string import maketrans
vowels = "aeiouy"
t = "______"
st = "trying this string"
tran = maketrans(vowels, t)
print st.translate(tran)
# Gives tr__ng th_s str_ng
You may also want to check uppercases.
you can use regex
import re
print(re.sub("[aeiouAEIOU]", "_", "abc")) # prints _bc
Make vowels an array with each element it's own letter.
Then do
for letter in word:
if letter in vowels:
letter = "_"
Lists can be used to easily build words, and with .join() you can combine the list items into a single string.
word = 'pizza'
vowels = "aeiouy"
new_word = []
for letter in word:
if letter in vowels:
new_word.append('_')
else:
new_word.append(letter)
print(''.join(new_word))
Here's the same thing in a generator expression:
word = 'pizza'
vowels = "aeiouy"
new_word = ''.join(c if c not in vowels else '_' for c in word)
print(new_word)
To answer why your approach didn't work.
if letter != vowels:
Does not do what you are thinking. It actually compares the letter against a full string "aeiouy". It will always be unequal (e.g. "a" != "aeiouy" is True and so is any other letter).
More likely what you mean was
if letter in vowels:
Which under the hood will iterate over vowels and compare each character to letter, returning True if any of the letters match.
The second mistake is here
new_word += word
You are adding the original word to the new word rather than the letter you just checked. So make that
new_word += letter
The third thing to note is that your logic is the reverse of what you intended. You wanted to replace vowels with _ but your if statement allows vowels into the new word and replaces consonants with the underscore. So if you reverse your if and else clauses.
All up you end up with
word = input("Enter a word: ")
new_word = ""
vowels = "aeiouy"
for letter in word:
if letter in vowels:
new_word += '_'
else:
new_word += letter
print(new_word)
Using a list comprehension and setting vowels as a set object (this is really only valuable for speeding up performance if you have a large list of words over which you're iterating):
>>> vowels = set("aeiouy")
>>> word = 'ampersand'
>>> new_word = "".join([letter if letter not in vowels else "_" for letter in word])
>>> print(new_word)
_mp_rs_nd
If you have Python 3, use str.maketrans to build a string translation table:
vowels = "aeiouy"
vowels += vowels.upper()
tr = str.maketrans(vowels, '_' * len(vowels))
print('Yo, this is a wacky phrase!'.translate(tr))
Shows: __, th_s _s _ w_ck_ phr_s_!
DRAX: I'll do you even better!
def replace_vowels(word):
vowels = ['a', 'e', 'i', 'o', 'u']
for x in (word.lower()):
if x in vowels:
word = word.replace(x, "_")
print(word)
replace_vowels('Stackoverflow')
Output
St_ck_v_rfl_w