Adding Random Characters Between Characters in a String (Python) [closed] - python

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I'm trying to add random letters after each letter in a given range, but they aren't in complete randomness.
def add_letters(org,num):
new_word = ''
for i in org:
randomLetter = random.choice(string.ascii_letters) * num
new_word += i
new_word += randomLetter
return new_word
original = 'Hello!'
for num in range(1,5):
#scramble the word using 'num' extra characters
scrambled = add_letters(original,num)
#output
print("Adding",num,'random characters to',original,'->',scrambled)
some of the results will have the same letter repeating multiple times like "HAAAAeiiiilzzzzlBBBBoSSSS!jjjj". Instead, they should be random.

You used *sum, which only generate randomLetter once and repeat the result letter for sum times. It's not repeat the random generation. So the result repeated.
It should be a loop or list-comprehension to generate mutiple randomLetter.
fixed code:
import random
import string
def add_letters(org,num):
new_word = ''
for i in org:
randomLetter = "".join(random.choice(string.ascii_letters) for _ in range(num))
new_word += i
new_word += randomLetter
return new_word
original = 'Hello!'
for num in range(1,5):
#scramble the word using 'num' extra characters
scrambled = add_letters(original,num)
#output
print("Adding",num,'random characters to',original,'->',scrambled)
result:
Adding 1 random characters to Hello! -> HNemldlgos!z
Adding 2 random characters to Hello! -> HVTeGYlYLlxdonV!GM
Adding 3 random characters to Hello! -> HqjbeQyOlgfHlAwqoyCj!PRq
Adding 4 random characters to Hello! -> HyFoLeyHUzlExGelVLlAoOhyz!EuzW

Related

How do I put characters inbetween characters [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 months ago.
Improve this question
word2 = input("put in the word you want me to repeat: ")
letter = ""
print("The original string is: " + word2)
for x in range(len(word2)):
letter += word2[x]
So if i put in "dwas" it will just print "dwas". How do I make it print "d-ww-aaa-ssss"?
You can use enumerate passing the string value from input, and the start value as 1, then repeat the characters n times, and finally join by -:
>>> print('-'.join(v*i for v,i in enumerate(inp,1)))
d-ww-aaa-ssss
By composiing built-in functions:
s = "hallo"
new_s = '-'.join(map(str.__mul__, s, range(1, len(s)+1)))
print(new_s)
#h-aa-lll-llll-ooooo
A for loop approach similar to the one in the question
s = "hallo"
# construct the output character per character
new_s = ''
# iterate over (index, character)-pairs, index start from 1
for i, char in enumerate(s, 1):
# add to output i-times the same character followed by -
new_s += f'{char*i}-'
# remove the last character (always the -)
new_s = new_s.rstrip('-')
# check result
print(new_s)

How do you check a string so that it contains only certain amount of numbers and characters [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed last year.
Improve this question
Hi all was wondering how I make a program to check a string so that it only contains 2 or 3 numbers and 4 letters.
Example
string = input("Please enter a string: ") #example string would be HY21 4KK
if
string contains 2-3 characters
string contains 4 letters
print("This is valid")
else
Print("This is invalid")
the simpler the better, because im really new to programming
I would simply loop through all letters, sum how many there are, and the same for all digits, and then check if it matches your conditions, something like this:
import string
# string.ascii_lowercase is "abdcdef..."
# string.ascii_uppercase is "ABCDEF..."
# so string.ascii_lowercase + string.ascii_uppercase will be all lowercase letter, and then all uppercase letters.
# string.digits is "01234567890"
e = input("Please enter a string: ")
# Here we will sum the number of appearances of every letter, lower case or upper case, in the English alphabet
# to get the total number of letters in e:
letter_count = sum(e.count(i) for i in string.ascii_lowercase + string.ascii_uppercase)
# Same here except with all digits:
digit_count = sum(e.count(i) for i in string.digits)
if digit_count in [2, 3] and letter_count == 4:
print("This is valid")
else:
print("This is invalid")

replace text python 2 leters replace [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I only want to change the text when there are both letters
def replaceonce(s, letters = '', replacewith=''):
letters = set(letters)
res = ''
for l in s:
if l in letters:
res += replacewith
letters.remove(l)
replacewith = ''
else:
res += l
return res
print(replaceonce('yday',letters='ya',replacewith='z'))
this code change to zdy although there is a letter and is not in text
print(replaceonce('yday',letters='ya',replacewith='z'))
output
ydz or dyz or zyd all combinations are ok fine
I want the text to change as well
that it will look like this
azdry
output
or another order of letters
zdrz
if two letters will appear in the text to change only if there are both letters, so y + and in this example
The following code returns the expected outputs for both the examples:
def findIndexes(string, letters):
indexes = []
for c in letters:
for i in range(len(string)):
if string[i] == c:
indexes.append(i)
break
return indexes
def replaceonce(s, letters = '', replacewith=''):
allPresent = True
toRet = ''
# checking if all letters' chars are in s
for c in letters:
if c not in s:
allPresent = False
break
if allPresent:
# this block make the substitution
# getting the index of first occurrence of each
# letters' char inside the s string
indexes = findIndexes(s, letters)
for i in range(len(s)):
if i not in indexes:
toRet += s[i]
toRet += replacewith
return toRet
Your examples make the substitution for one occurrence of the letters string, even if the string is splitted somewhere inside the s. Then the idea is: find the index where this chars are and skip all of them when reconstruct the s string. At the end of code, add the replaceWith at the end of reconstructed string.
I hope that I understood correctly your question that, by the way, was not very clear.

Alphabatic Anagrams doesn't work with words that contains letters with multiple occurence [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
Hello how are you? I have a challenge https://www.codewars.com/kata/53e57dada0cb0400ba000688/solutions/python and I've stuck on it for a 2 days, I created the first solution but it was slow(using itertools.permutations), and then I've make this block of code.
import math
def listPosition(word):
n = 0
wlsort = list(word)
wlsort.sort()
wcopy = word
while wcopy:
for i in range(wlsort.index(wcopy[0])):
n += math.factorial(len(wlsort) - 1)
wlsort.pop(wlsort.index(wcopy[0]))
wcopy = wcopy[1:]
return n + 1
but it doesn't work with words like test bookkeeper, Do you have any hints, or idea on how to solve it?
I think my problem is that when I have a word like car it will brute-force it like ->
acr, arc...
and if i have caar it will brute-force it like ->
aacr, aarc and it doesn't do acar because it is brute-forcing alphabetically.
Here is my attempt. It's quite straightforward, if you read the req. carefully. Please let me know if you have any questions.
from math import factorial as fact
def listPosition(word):
count = 0
while len(word):
first = word[0]
uniqs = set(word)
possibles = fact(len(word))
for ch in uniqs:
possibles /= fact(word.count(ch))
for ch in uniqs:
if ch < first:
count += possibles/len(word) * word.count(ch)
word = word[1:]
return count + 1

Letter counter II [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
A couple days ago, I made a program that allowed me to pick a letter from a string and it would tell me how many times a chosen letter appeared. Now I want to use that code to create a program that takes all the letters and counts how many times each letter appears. For example, if I put "dog" in as my string, I would want the program to say that d appears once, o appears once, and g appears once. Here is my current code below.
from collections import Counter
import string
pickedletter= ()
count = 0
word = ()
def count_letters(word):
global count
wordsList = word.split()
for words in wordsList:
if words == pickedletter:
count = count+1
return count
word = input("what do you want to type? ")
pickedletter = input("what letter do you want to pick? ")
print (word.count(pickedletter))
from collections import Counter
def count_letters(word):
counts = Counter(word)
for char in sorted(counts):
print char, "appears", counts[char], "times in", word
I'm not sure why you're importing anything for this, especially Counter. This is the approach I would use:
def count_letters(s):
"""Count the number of times each letter appears in the provided
specified string.
"""
results = {} # Results dictionary.
for x in s:
if x.isalpha():
try:
results[x.lower()] += 1 # Case insensitive.
except KeyError:
results[x.lower()] = 1
return results
if __name__ == '__main__':
s = 'The quick brown fox jumps over the lazy dog and the cow jumps over the moon.'
results = count_letters(s)
print(results)

Categories

Resources