Printing even characters in a string and ignoring white strings - python

I need something like this
accepted_string: An apple a day keeps the doctor away
resultant_string: Aapedyepteotrwy
And for this I have written this code:
accepted_string = input("enter")
add = ''
for count in range(0, len(accepted_string), 2):
if accepted_string[count] == " ":
count += 1
add = add + accepted_string[count]
else:
add = add + accepted_string[count]
print(add)
But this is giving me different output while passing the above sample input. The logic is also correct, then where is the error? I have to skip to next character whenever I encounter a whitespace. Please help me as I am new to this

Simple string slicing with prior replacement:
>>> s = "An apple a day keeps the doctor away"
>>> s.replace(" ", "")[::2]
'Aapedyepteotrwy'

you can remove space before hands instead of doing in for loop and make it list to convert in into array
Code:
accepted_string = input("enter")
add = ''
accepted_string = list(accepted_string.replace(" ", ""))
print(accepted_string)
for count in range(0, len(accepted_string), 2):
add = add + accepted_string[count]
print(add)
output:
['A', 'n', 'a', 'p', 'p', 'l', 'e', 'a', 'd', 'a', 'y', 'k', 'e', 'e', 'p', 's', 't', 'h', 'e', 'd', 'o', 'c', 't', 'o', 'r', 'a', 'w', 'a', 'y']
Aapedyepteotrwy
2nd code:
accepted_string = input("enter")
add = ''
char_count = 1
for count in range(0, len(accepted_string)):
if accepted_string[count] != " ":
char_count += 1
if char_count % 2 == 0:
add = add + accepted_string[count]
# add = add + accepted_string[count]
# else:
# add = add + accepted_string[count]
print(add)
output:
Aapedyepteotrwy

Related

Inserting breaks in variables over a certain length

So basically what I want to do is if the random string of characters generated is over 6 chars long it adds a space in a random place in that string and then the remaining ones are added on after the space so for example: raw output: "aoneicse", what I want : "aoneic se" or "aone icse".
Here is my code:
import random
alist = [' ', 'a', 'b', 'c', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
blist = [' ', 'a', 'b', 'c', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
clist = [' ', 'a', 'b', 'c', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
# define the 3 words
a = ''.join(random.choices(alist, k = random.randint(2,8)))
b = ''.join(random.choices(blist, k = random.randint(2,8)))
c = ''.join(random.choices(clist, k = random.randint(2,8)))
# each letter is a certain word, if this word exceeds 6 characters add a space in a random place
if a length = > 6:
asp = [a + " "]
if b length = > 6:
bsp = [b + " "]
if c length = > 6:
csp = [c + " "]
# or something along the lines of this i guess
This code does not currently work, BTW.
You don't need to create a list of strings with every letter of the alphabet, there's already a string module that does that for you:
import string
print(' ' + string.ascii_lowercase)
# Outputs abcdefghijklmnopqrstuvwxyz
You also don't need to create three different variables, you can just use a single one and use that:
import string
base_str = ' ' + string.ascii_lowercase
Then, you can use a list to generate your words based on this string:
import random
import string
base_str = ' ' + string.ascii_lowercase
words = [''.join(random.choices(base_str, k=random.randint(2,8))) for _ in range(3)]
Now, just apply your space requirement to each word:
import random
import string
base_str = ' ' + string.ascii_lowercase
words = [''.join(random.choices(base_str, k=random.randint(2,8))) for _ in range(3)]
new_words = []
for word in words:
if len(word) < 6:
new_word = word
else:
pos = random.randrange(len(word))
new_word = word[:pos] + ' ' + word[pos:]
new_words.append(new_word)
Using random.seed(0), new_words is equal to ['j xazmxvz', 'oxmg', 'buzns pcb'].
Don't join the choices immediately. Generate the list, and if it is long enough, pick an index in the middle (sufficiently far from either end, depending on your needs), and perform a slice assignment to the empty list at that position. Then join the list into a single string.
import string
a = random.choices(string.ascii_lowercase, k=random.randint(2,8))
if len(a) > 6:
# Adjust the arguments to randint as desired
x = random.randint(2, len(a) - 2)
a[x:x] = ' '
a = ''.join(a)
import random
character = list(map(chr, range(ord('a'), ord('z') + 1)))
def get_char():
return character[random.randint(0, len(character) - 1)]
def gen_word(min_len, max_len):
word = [get_char() for _ in range(random.randint(min_len, max_len))]
if len(word) > 6:
word[random.randint(1, len(word) - 2)] = ' '
return ''.join(word)
for i in range(10):
print(gen_word(4, 10))
Iā€™d use slices to return a space, sliced-in at the right spot; Something along the lines of:
def split(input_str):
if len(input_str) > 6:
space_at = rand(0,len(input_str))
return input_str[:space_at] + ā€˜ ā€˜ + input_str[space_at:]
else:
return input_str

Scratch lottery function

I am working on a scratch lottery command on my python game.
My Scratch lottery function is below.
def lottery(player_money):
print('scratch lottery :')
print('price: 500')
print('wins :')
print(' all 6 same : $100000')
print(' all 5 same : $50000')
print(' all 4 same : $10000')
print(' all 3 same : $1000')
print(' all 2 same : $300')
print('do you want to buy it?? yes/no')
buy = input('> ')
if buy == 'no':
print('please come back later!!')
return player_money
elif buy == 'yes':
print('_____________')
lottery_results = ['x', 'o', 'p', 'k', 'm', 'e', 'a', 'w']
a = random.choice(lottery_results)
b = random.choice(lottery_results)
c = random.choice(lottery_results)
d = random.choice(lottery_results)
e = random.choice(lottery_results)
f = random.choice(lottery_results)
print('| ' + a + ' | ' + b + ' | ' + c + ' |')
print('|_' + d + '_|_' + e + '_|_' + f + '_|')
if...
I Have no idea what to put after
if...
I don't want to make if for all possible solutions since that would be like 2 million ifs.
I want to make it like below
If 2 of the str in a or b or c or d or e or f is the same:
print('Since 2 matched, you won $300!')
player_money += 300
return player_money
I don't know how to code(ify) the phrase that goes after if and the phrase that goes after if that I put in wouldn't work and there would be a error
Any suggestions on how I could make this work?
You're off to a good start, but there is something that could make your life a lot easier. Firstly, lets use random.choices to create a list from the possible letters:
import random
pool = ['x', 'o', 'p', 'k', 'm', 'e', 'a', 'w']
results = random.choices(pool, k=len(pool))
Note: k can be any integer - it determines the length of the resulting list
This is going to yield a list with random letters from the pool:
['e', 'x', 'a', 'm', 'x', 'k', 'o', 'p']
Now, you can think about how you can build your if statement off of a list.
If 2 of the str in a or b or c or d or e or f is the same:
This sounds like a job for iteration. Remember, we don't have the variables a, b, c, etc. anymore; rather, they're stored in a list.
for letter in pool:
if results.count(letter) > 1:
# match found
Above, you iterate through the pool variable, which holds all of the possible values. On every loop of that iteration, we check if the current letter that resides inside the pool list exists more than once in the results list. This means that there was a match.
More
You can dynamically increase the player's money count with only a few lines if you keep a list of the possible winnings that correspond with a certain number of matches. For example,
winnings = [100, 200, 300, 400, 500, 600, 700, 800]
Here, 100 is chosen if there are two of the same letter (1 match). If there are three of the same letter (2 matches), 200 is chosen.
player_money = 0
for letter in pool:
result_count = results.count(letter)
player_money += winnings[result_count-2] if result_count > 1 else 0
Above, the line winnings[result_count-2] if result_count > 1 else 0 determines how much the player should receive based off of their matches. We have to subtract 2 from result_count because, remember, python indexing starts from 0, and if there are two of the same letter in the resulting list (1 match), we need to subtract 2 to make it 0, which selects the correct winnings.
If you want to go by your own code then, You can use Counter.
from itertools import Counter
then you can use it like:
Counter([a,b,c,d,e,f]))
to check if any of the values is 2.
Use random.sample() to gather 6 results in a single line.
Then we can simply loop over the sample and check if each draw exists in lottery_results. It also may be better to store the winnings in a dict so we can easily retrieve the amount without too much hassle.
import random
winnings = {6: 100000, 5: 50000, 4: 10000, 3: 1000, 2: 300}
lottery_results = ['x', 'o', 'p', 'k', 'm', 'e', 'a', 'w']
user_numbers = random.sample(lottery_results, 6)
#['m', 'k', 'e', 'a', 'x', 'p']
matches = 0
for draw in user_numbers:
if draw in lottery_results:
matches += 1
print(f'Congrats! You matched {matches} and won ${winnings[matches]}')
#Congrats! You matched 6 and won $100000
You have further issues with the way you have set out to achieve your goal. You're generating the results for the draw from the results of the house. This means you will always match 6.
We can show this by implementing a possible_draws to generate both our results and user draws from. We will use the alphabet as an example.
import string
possible_draws = list(string.ascii_lowercase)
#['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
lottery_results = random.sample(possible_draws, 8)
#['x', 'h', 'o', 'p', 'j', 'n', 'm', 'c']
user_draws = random.sample(possible_draws, 6)
#['h', 'r', 'u', 't', 'f', 'n']
matches = 0
for draw in user_draws:
if draw in lottery_results:
matches += 1
if matches < 2:
print('No win this time!')
else:
print(f'Congrats! You matched {matches} and won ${winnings[matches]}')

Why are these loop outputs different?

I am working on a task where I need to sort and remove the duplicate letters in a string. I ended up with the function doing what I wanted but out of shear luck. I don't know why these lines of code produce different outputs. Could someone help me understand?
def format_string(string1):
sorted1 = sorted(string1)
print(sorted1)
i = 0
while i < len(sorted1) - 1:
if sorted1[i] == sorted1[i + 1]:
del sorted1[i + 1]
else:
i += 1
return sorted1
print(format_string("aretheyhere"))
['a', 'e', 'e', 'e', 'e', 'h', 'h', 'r', 'r', 't', 'y']
['a', 'e', 'h', 'r', 't', 'y']
#This did what I wanted. but these seemingly similar lines don't.
def format_string(string1):
sorted1 = sorted(string1)
print(sorted1)
i = 0
j = i + 1
while i < len(sorted1) - 1:
if sorted1[i] == sorted1[j]:
del sorted1[j]
else:
i += 1
return sorted1
print(format_string("aretheyhere"))
['a', 'e', 'e', 'e', 'e', 'h', 'h', 'r', 'r', 't', 'y']
['a', 'y']
def format_string(string1):
sorted1 = sorted(string1)
print(sorted1)
i = 0
while i < len(sorted1) - 1:
if sorted1[i] == sorted1[i + 1]:
del sorted1[i + 1]
i += 1
return sorted1
print(format_string("aretheyhere"))
['a', 'e', 'e', 'e', 'e', 'h', 'h', 'r', 'r', 't', 'y']
['a', 'e', 'e', 'h', 'r', 't', 'y']
What are the crucial differences here that change the output?
The variable j doesn't increment because it's not updated inside your while loop, i.e. changing the value of i after setting the value of j to i+1 does not change the value of j. For example, this function would give the same result as the first one because the value of j is updated inside the while loop:
def format_string(string1):
sorted1 = sorted(string1)
print(sorted1)
i = 0
while i < len(sorted1) - 1:
j = i + 1
if sorted1[i] == sorted1[j]:
del sorted1[j]
else:
i += 1
return sorted1
print(format_string("aretheyhere"))

How to write code that checks to see if item is negative before split?

Hey so I have a polyalphabetic cipher and it's working great but I am running into the issue of having all my inputs on one line. The inputs would be the shift;secretWord; and message. I need to find a way to check if an input is solely a negative number and if it is I need the code to exit. I also need to find a way to make my code keep looping until the negative condition is met.
alpha = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i',
'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q',
'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
shiftChange = 0
secretWord = 0
da_message = 0
shiftChange = int(shiftChange)
inputs = []
shiftChange, secretWord, da_message = input('').split(";")
da_message = da_message.lower()
inputs.append(shiftChange)
inputs.append(secretWord)
inputs.append(da_message)
secretWord = secretWord.lower()
secretWord = secretWord * len(da_message)
cypherText = ''
symbol = ' '
count = 0
for letter in da_message:
if letter in alpha:
shift = alpha.index(secretWord[count]) + int(shiftChange)
letterIndex = alpha.index(letter) + 1
cypherLetter = alpha[(letterIndex+shift)%26]
cypherText = cypherText + cypherLetter
count = count + 1
print(cypherText.upper())
Use int().
The int() raises a ValueError for anything that isn't, entirely, an integer. Trap this error using a try-except loop and then if the error is raised, then execute the rest of your code. (since it is an alphanumeric) Otherwise, compare it if it is less than 0 and exit if true.
Below is a modified version of your code that solves both of your problems.
The while True ensures the program continues to loop until the negative number is found, which in turn causes it to exit the entire program.
alpha = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i',
'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q',
'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
shiftChange = 0
secretWord = 0
da_message = 0
cypherText = ''
symbol = ' '
count = 0
shiftChange = int(shiftChange)
inputs = []
while True:
shiftChange, secretWord, da_message = input('enter:').split(";")
da_message = da_message.lower()
inputs.append(shiftChange)
inputs.append(secretWord)
inputs.append(da_message)
secretWord = secretWord.lower()
secretWord = secretWord * len(da_message)
for i in range(len(inputs)):
try:
temp = int(inputs[i])
except ValueError:
for letter in da_message:
if letter in alpha:
shift = alpha.index(secretWord[count]) + int(shiftChange)
letterIndex = alpha.index(letter) + 1
cypherLetter = alpha[(letterIndex+shift)%26]
cypherText = cypherText + cypherLetter
count = count + 1
print(cypherText.upper())
if temp < 0:
exit()
Hope this helps!

Iterating through list, ignoring duplicates

I've written a program that attempts to find a series of letters (toBeFound - these letters represent a word) in a list of letters (letterList), however it refuses to acknowledge the current series of 3 letters as it counts the 'I' in the first list twice, adding it to the duplicate list.
Currently this code returns "incorrect", when it should return "correct".
letterList= ['F','I', 'I', 'X', 'O', 'R', 'E']
toBeFound = ['F', 'I', 'X']
List = []
for i in toBeFound[:]:
for l in letterList[:]:
if l== i:
letterList.remove(l)
List.append(i)
if List == toBeFound:
print("Correct.")
else:
print("Incorrect.")
letterList and toBeFound are sample values, the letters in each can be anything. I can't manage to iterate through the code and successfully ensure that duplicates are ignored. Any help would be greatly appreciated!
Basically, you're looking to see if toBeFound is a subset of letterList, right?
That is a hint to use sets:
In [1]: letters = set(['F','I', 'I', 'X', 'O', 'R', 'E'])
In [2]: find = set(['F', 'I', 'X'])
In [3]: find.issubset(letters)
Out[3]: True
In [4]: find <= letters
Out[4]: True
(BTW, [3] and [4] are different notations for the same operator.)
I think this would solve your problem. Please try it and let me know
letterList= ['F','I', 'I', 'X', 'O', 'R', 'E']
toBeFound = ['F', 'I', 'X']
found_list = [i for i in toBeFound if i in letterList]
print("Correct" if toBeFound == found_list else "Incorrect")
You could make the initial list a set, but if you want to look up a word like 'hello' it wont work because you'll need both l's.
One way to solve this is to use a dictionary to check and see how we are doing so far.
letterList = ['H', 'E', 'L', 'X', 'L', 'I', 'O']
toBeFound = ['H', 'E', 'L', 'L', 'O']
# build dictionary to hold our desired letters and their counts
toBeFoundDict = {}
for i in toBeFound:
if i in toBeFoundDict:
toBeFoundDict[i] += 1
else:
toBeFoundDict[i] = 1
letterListDict = {} # dictionary that holds values from input
output_list = [] # dont use list its a reserved word
for letter in letterList:
if letter in letterListDict: # already in dictionary
# if we dont have too many of the letter add it
if letterListDict[letter] < toBeFoundDict[letter]:
output_list.append(letter)
# update the dictionary
letterListDict[letter] += 1
else: # not in dictionary so lets add it
letterListDict[letter] = 1
if letter in toBeFoundDict:
output_list.append(letter)
if output_list == toBeFound:
print('Success')
else:
print('fail')
How about this: (I tested in python3.6)
import collections
letterList= ['F','I', 'I', 'X', 'O', 'R', 'E']
toBeFound = ['F', 'I', 'X']
collections.Counter(letterList)
a=collections.Counter(letterList) # print(a) does not show order
# but a.keys() has order preserved
final = [i for i in a.keys() if i in toBeFound]
if final == toBeFound:
print("Correct")
else:
print("Incorrect")
If you're looking to check if letterList has the letters of toBeFound in the specified order and ignoring repeating letters, this would be a simple variation on the old "file match" algorithm. You could implement it in a non-destructive function like this:
def letterMatch(letterList,toBeFound):
i= 0
for letter in letterList:
if letter == toBeFound[i] : i += 1
elif i > 0 and letter != toBeFound[i-1] : break
if i == len(toBeFound) : return True
return False
letterMatch(['F','I', 'I', 'X', 'O', 'R', 'E'],['F', 'I', 'X'])
# returns True
On the other hand, if what you're looking for is testing if letterList has all the letters needed to form toBeFound (in any order), then the logic is much simpler as you only need to "check out" the letters of toBeFound using the ones in letterList:
def lettermatch(letterList,toBeFound):
missing = toBeFound.copy()
for letter in letterList:
if letter in missing : missing.remove(letter)
return not missing
As requested.
letterList= ['F','I', 'I', 'X', 'O', 'R', 'E']
toBeFound = ['F', 'I', 'X']
List = []
for i in toBeFound[:]:
for l in set(letterList):
if l== i:
List.append(i)
if List == toBeFound:
print("Correct.")
else:
print("Incorrect.")
This prints correct. I made the letterList a set! Hope it helps.
One simple way is to just iterate through toBeFound, and look for each element in letterList.
letterList= ['F','I', 'I', 'X', 'O', 'R', 'E']
toBeFound = ['F', 'I', 'X']
found = False
for x in letterList:
if x not in toBeFound:
found = False
break
if found:
print("Correct.")
else:
print("Incorrect.")

Categories

Resources