I have come up with the following code but unfortunately its only removing 1 character from my string.
import random
string = 'HelloWorld!'
def remove_random_character(phrase):
character_number = random.randint(0, len(phrase))
remover = f'{phrase[:character_number - 1]}_{phrase[character_number:]}'
for _ in range(8):
sliced_phrase = remover
print(sliced_phrase)
remove_random_character(string)
I thought that the for loop will take care of this but unfortunately it did not. but every time it loops it just refreshes the sliced_phrase variable. but I do not know how to store the last version of the loop, for that to be edited. So how can I can I remove multiple random characters from a string?
You can iterate over every letter in your string and decide do you need to remove it:
import random
string = 'HelloWorld!'
output = ''.join([s for s in string if random.random() < 0.7])
Test:
Heloold!
elloWld!
loWorld
import random
def remove_random_char(string):
char_index_to_remove = random.randint(0, len(string)-1)
string = string.replace(string[char_index_to_remove], '', 1)
return string
string = 'HelloWorld!'
times_to_iterate = 4
for i in range(times_to_iterate):
string = remove_random_char(string)
What about:
import random
def remove_random_character(phrase, n_remove):
for num in random.sample(range(0, len(phrase)), n_remove):
phrase = phrase[:num] + '_' + phrase[num + 1:]
return phrase
Then to remove, say, 3 random characters:
string = 'HelloWorld!'
new_phrase = remove_random_character(string, 3)
import random
phrase = 'HelloWorld!'
num_of_missing_chars = 4
def random_char_remover(string: str, num_missing_char: int):
def index_remover(string: str):
char_index_to_remove = random.randint(0, len(string)-1)
string = string.replace(string[char_index_to_remove], '_', 1)
return string
for i in range(num_missing_char):
string = index_remover(string)
print(string)
random_char_remover(phrase, num_of_missing_chars)
Thanks guys this is what I got finally after reviewing all your answers and using a bit of all of them. it may be a little simplified from my end but I only work with code that I can understand.
:)
Related
I’m new to computer science and really stuck on this question so any help would be great :).
Firstly I was given the following global variable:
ARROWS = ‘<>^v’
The idea is to create a function that takes in a string and an integer (n). The function should then replace the first n number of characters with ‘X’. So far this is easy, however, the problem is that the characters should ONLY be replaced if it is a part of the global variable ARROWS. If it isn’t, it should not be modified but still counts as one of the n numbers. The following exemplifies what needs to be done:
>>>function(‘>>.<>>...’, 4)
‘XX.X>>...’
>>>function(‘>..>..>’, 6)
‘X..X..>’
>>>function(‘..>>>.’, 2)
‘..>>>.’
Please help :)
Hi it seems to me (if you want to avoid using libraries) that you can iterate over the characters in the string and do comparisons to decide if the character needs to be changed. Here is some sample code which should help you.
ARROWS = '<>^v'
def replace_up_to(in_str, n):
# store the new character in this list
result = []
for i, char in enumerate(in_str):
# decide if we need to change the char
if i < n and char in ARROWS:
result.append("X")
continue
result.append(char)
# return a new string from our result list
return "".join(result)
The solution is very straightforward. Hope this helps. :)
ARROWS = "<>^v"
arrows_set = set(ARROWS)
def function(word, n):
newWord = ""
for i in range(0, len(word)):
if word[i] in arrows_set and i < n:
newWord += 'X'
else:
newWord += word[i]
return newWord
print(function(">>.<>>...", 4))
print(function(">..>..>", 6))
You can use the re module to match a regex set of your arrows.
import re
txt_to_replace = "aa^aaa<>aaa>"
x= re.sub(r'[<>^v]', 'X', txt_to_replace ,3 )
# x is now aaXaaaXXaaa>
You can use re.sub() to replace any of the characters in ARROW.
To limit it to the first N characters of the input string, perform the replacement on a slice and concatenate that with the remainder of the input string.
import re
def replace_arrow(string, limit):
arrows_regex = r'[<>^v]'
first_n = string[:limit]
rest = string[limit:]
return re.sub(arrows_regex, 'X', first_n) + rest
This is my string:
keyword = "qatarworldcup"
I mean my string should be qqatarworldcup, qatarworldcupp or qatarrworlddcup
This should be pretty easy to do if you break it up into parts.
Select a random letter from the word.
import random
letter_index = random.randint(0, len(keyword)-1)
Split the word into two parts at the letter you picked.
before, after = keyword[:letter_index], keyword[letter_index:]
Join the two parts, adding an extra instance of the selected letter
result = before + keyword[letter_index] + after
If your strings are big enough, or you're doing this multiple times, you could see a speedup from reducing the number of string concatenations, because that's an O(N) operation on account of the immutability of strings. Since the selected letter already exists in the word, you can split it such that the selected letter is the last character of before and the first character of after. Then, you only need a single concatenationThanks to #Mechanic Pig for your comment:
before, after = keyword[:letter_index+1], keyword[letter_index:]
result = before + after
from random import randint
keyword = "qatarwordcup"
idx = randint(0, len(keyword) - 1)
keyword = keyword[:idx] + keyword[idx] + keyword[idx:]
I'd do it like this
import random
#Find random position in string
r = random.randint(0, len(keyword) - 1)
#Create new string with added character at random position
newStr = keyword[:r] + keyword[r] + keyword[r:]
Iteration through index-character pairs, apply the condition on each "term" with the ternary operator and join everything together.
import random
# fix random number generator (for testing only!)
random.seed(190)
keyword = "qatarworldcup"
# random index
r = random.randint(0, len(keyword)-1)
out = ''.join(char * 2 if i == r else char for i, char in enumerate(keyword))
print(out)
#qaatarworldcup
Need to generate random string as follows
first 5 strings should be alphabet in caps
Next 4 should be integers and
one alphabet at last
output i need examples:
ACCE1664Z
BCED1782V
FBCR9126N
it is generating random string.
from string import ascii_uppercase, digits
import random
def generatestr():
str0= random.sample(ascii_uppercase,4)+random.sample(digits,4)+random.sample(ascii_uppercase,1)
return ''.join(str0)
print(generatestr())
Improvement from #ComplicatedPhenomenon's Answer
Visit here for more string constants (e.g. ascii_uppercase).
Suppose the last alphabet is also in caps.
import random
def generatestr():
alphabet = []
for letter in range(65, 91):
alphabet.append(chr(letter))
num = [str(i) for i in range(10)]
str0= random.sample(alphabet,4)+random.sample(num,4)+random.sample(alphabet,1)
return ''.join(str0)
generatestr()
import random
import string
def randomString(charLength, intLength):
letters = string.ascii_uppercase
numbers = list(range(0,9))
charArray = ""
numArray= ""
for i in range(max(charLength,intLength)):
if i < charLength:
charArray = charArray + random.choice(letters)
if i < intLength:
numArray = numArray + str(random.choice(numbers))
return (charArray + numArray + random.choice(letters))
print(randomString(5,4))
Beginner python coder here, keep things simple, please.
So, I need this code below to scramble two letters without scrambling the first or last letters. Everything seems to work right up until the scrambler() function.
from random import randint
def wordScramble(string):
stringArray = string.split()
for word in stringArray:
if len(word) >= 4:
letter = randint(1,len(word)-2)
point = letter
while point == letter:
point = randint(1, len(word)-2)
word = switcher(word,letter,point)
' '.join(stringArray)
return stringArray
def switcher(word,letter,point):
word = list(word)
word[letter],word[point]=word[point],word[letter]
return word
print(wordScramble("I can't wait to see how this turns itself out"))
The outcome is always:
I can't wait to see how this turns itself out
Since you are a beginner, I tried to change your code as little as possible. Mostly you are expecting changes to word to change the contents or your list stringArray. The comments mark the changes and reasons.
from random import randint
def wordScramble(myString): # avoid name clashes with python modules
stringArray = myString.split()
for i, word in enumerate(stringArray): # keep the index so we can update the list
if len(word) >= 4:
letter = randint(1,len(word)-2)
point = letter
while point == letter:
point = randint(1, len(word)-2)
stringArray[i] = switcher(word,letter,point) # update the array
return ' '.join(stringArray) # return the result of the join
def switcher(word,letter,point):
word = list(word)
word[letter],word[point]=word[point],word[letter]
return ''.join(word) # return word back as a string
print(wordScramble("I can't wait to see how this turns itself out"))
Because there had to be a cleaner (and better documented) way to do this:
from random import sample
def wordScramble(sentence):
# Split sentence into words; apply switcher to each; rejoin into a sentence
return ' '.join([switcher(x) for x in sentence.split()])
def switcher(word):
if len(word) <= 3: # Don't bother if not enough letters to scramble
return word
# Pick 2 positions from interior of word
a,b = sorted(sample( xrange(1,len(word)-1), 2 ))
# Re-assemble word with out 2 positions swapped using bits before, between & after them
return word[:a] + word[b] + word[a+1:b] + word[a] + word[b+1:]
print wordScramble("I can't wait to see how this turns itself out")
As an example, lets say I wanted to list the frequency of each letter of the alphabet in a string. What would be the easiest way to do it?
This is an example of what I'm thinking of... the question is how to make allTheLetters equal to said letters without something like allTheLetters = "abcdefg...xyz". In many other languages I could just do letter++ and increment my way through the alphabet, but thus far I haven't come across a way to do that in python.
def alphCount(text):
lowerText = text.lower()
for letter in allTheLetters:
print letter + ":", lowertext.count(letter)
The question you've asked (how to iterate through the alphabet) is not the same question as the problem you're trying to solve (how to count the frequency of letters in a string).
You can use string.lowercase, as other posters have suggested:
import string
allTheLetters = string.lowercase
To do things the way you're "used to", treating letters as numbers, you can use the "ord" and "chr" functions. There's absolutely no reason to ever do exactly this, but maybe it comes closer to what you're actually trying to figure out:
def getAllTheLetters(begin='a', end='z'):
beginNum = ord(begin)
endNum = ord(end)
for number in xrange(beginNum, endNum+1):
yield chr(number)
You can tell it does the right thing because this code prints True:
import string
print ''.join(getAllTheLetters()) == string.lowercase
But, to solve the problem you're actually trying to solve, you want to use a dictionary and collect the letters as you go:
from collections import defaultdict
def letterOccurrances(string):
frequencies = defaultdict(lambda: 0)
for character in string:
frequencies[character.lower()] += 1
return frequencies
Use like so:
occs = letterOccurrances("Hello, world!")
print occs['l']
print occs['h']
This will print '3' and '1' respectively.
Note that this works for unicode as well:
# -*- coding: utf-8 -*-
occs = letterOccurrances(u"héĺĺó, ẃóŕĺd!")
print occs[u'l']
print occs[u'ĺ']
If you were to try the other approach on unicode (incrementing through every character) you'd be waiting a long time; there are millions of unicode characters.
To implement your original function (print the counts of each letter in alphabetical order) in terms of this:
def alphCount(text):
for character, count in sorted(letterOccurrances(text).iteritems()):
print "%s: %s" % (character, count)
alphCount("hello, world!")
the question is how to make
allTheLetters equal to said letters
without something like allTheLetters =
"abcdefg...xyz"
That's actually provided by the string module, it's not like you have to manually type it yourself ;)
import string
allTheLetters = string.ascii_lowercase
def alphCount(text):
lowerText = text.lower()
for letter in allTheLetters:
print letter + ":", lowertext.count(letter)
If you just want to do a frequency count of a string, try this:
s = 'hi there'
f = {}
for c in s:
f[c] = f.get(c, 0) + 1
print f
For counting objects, the obvious solution is the Counter
from collections import Counter
import string
c = Counter()
for letter in text.lower():
c[letter] += 1
for letter in string.lowercase:
print("%s: %d" % (letter, c[letter]))
Do you mean using:
import string
string.ascii_lowercase
then,
counters = dict()
for letter in string.ascii_lowercase:
counters[letter] = lowertext.count(letter)
All lowercase letters are accounted for, missing counters will have zero value.
using generators:
counters =
dict( (letter,lowertext.count(letter)) for letter in string.ascii_lowercase )
Something like this?
for letter in range(ord('a'), ord('z') + 1):
print chr(letter) + ":", lowertext.count(chr(letter))
Main question is "iterate through the alphabet":
import string
for c in string.lowercase:
print c
How get letter frequencies with some efficiency and without counting non-letter characters:
import string
sample = "Hello there, this is a test!"
letter_freq = dict((c,0) for c in string.lowercase)
for c in [c for c in sample.lower() if c.isalpha()]:
letter_freq[c] += 1
print letter_freq
How about this, to use letters, figures and punctuation (all usable to form a Django key):
import random
import string
chars = string.letters + string.digits + string.punctuation
chars_len = len(chars)
n = 40
print(''.join([chars[random.randint(0, chars_len)] for i in range(n)]))
Example result: coOL:V!D+P,&S*hzbO{a0_6]2!{4|OIbVuAbq0:
Just use:
import string
string.lowercase
string.uppercase
or
string.letters[:26]
string.letters[26:]
This is what I do:
import string
for x in list(string.lowercase):
print x