Scratch lottery function - python

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]}')

Related

random alphabet chooser with no repeats (python)

import random
alphabet = ['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']
iterations = 1
running = True
def random_picker():
random_choice = random.choice(alphabet)
iterations =+ 1
print(random_choice)
while running == True:
if iterations <=26:
random_picker()
else:
running == False
I'm trying to get a different random letter through each iteration, through all 26. Each letter picked needs to update the random_choice variable.
Your program will continue looping until 26 letters are returned. Since you want a different letter on each iteration, it's probably easier to shuffle the alphabet array and loop over it instead of trying to choose a random letter in each iteration:
random.shuffle(alphabet)
Paul M. EDIT - Here is an example of how you might use it to achieve the desired effect:
from string import ascii_lowercase
from random import shuffle
alphabet = list(ascii_lowercase)
shuffle(alphabet)
for char in alphabet:
print(char)
Output:
j
m
z
w
k
y
d
f
l
c
u
b
t
s
e
p
x
g
a
r
n
h
i
q
o
v
>>>

Python: TypeError: unsupported operand type(s) for +: 'Random' and 'str'

I'm entering a code where a word is randomly generated. But it says TypeError and that random can't be matched with string
I've tried rewriting code multiple times but it didn't work.
Code:
import random
from random import *
Letters = ['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']
LettersInWord = Random()
Points = 0
print(LettersInWord + " is number of letters in word")
for index in range(LettersInWord):
Word = Letters[Random.random(0, 25)]
Guess = input("Enter Word You Think It Is (You will get a point everytime
one or more of your letters match with the word. Your turn will end when
you enter a letter that is not in the word: ")
for letter in Guess:
if letter == letter in Word:
Points = Points + 1
if Guess == Word:
print("Congratulations, you won. End program and restart to
try again.")
Guess = input("Well done, try again")
Random() is a random-number generator, not a number itself.
letters_in_word = randint(1,25) # random number between 1 and 25, inclusive
(Capitalized names are conventionally reserved for class names. Use snake case identifiers for ordinary variables.)
Continuing from the comments:
from random import *
Letters = ['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']
while True:
letters_in_word = randint(1,25)
Points = 0
Word = []
print("{} is number of letters in word".format(letters_in_word))
for index in range(0, letters_in_word):
Word.append(Letters[randint(0, 25)])
Guess = input("Press Q/q to exit or Enter Word You Think It Is (You will get a point everytime one or more of your letters match with the word. Your turn will end when you enter a letter that is not in the word: ")
if Guess.lower() == 'q':
break
print(Word)
if Guess in Word:
Points = 100 # assuming
print("Congratulations, you won. End program and restart to try again.\nTotal Points: {}".format(Points))
break
else:
for letter in Guess:
if letter in Word:
Points = Points + 1
print("Total Points: {}".format(Points))
OUTPUT:
10 is number of letters in word
Press Q/q to exit or Enter Word You Think It Is (You will get a point everytime one or more of your letters match with the word. Your turn will end when you enter a letter that is not in the word: pak
['f', 't', 'l', 'b', 'd', 'k', 'e', 'p', 'd', 'n']
Total Points: 2
9 is number of letters in word
Press Q/q to exit or Enter Word You Think It Is (You will get a point everytime one or more of your letters match with the word. Your turn will end when you enter a letter that is not in the word: dirt
['z', 'i', 'k', 'p', 'z', 'j', 'r', 't', 'd']
Congratulations, you won. End program and restart to try again.
Total Points: 100
Process finished with exit code 0

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!

Whats happening this code. Anagram as a substring in a string

I found this question posted on here, but couldn't comment or ask a question, so I am creating a new question.
The original post stated the following:
t = "abd"
s = "abdc"
s trivially contains t. However, when you sort them, you get the strings abd and abcd, and the in comparison fails. The sorting gets other letters in the way.
Instead, you need to step through s in chunks the size of t.
t_len = len(t)
s_len = len(s)
t_sort = sorted(t)
for start in range(s_len - t_len + 1):
chunk = s[start:start+t_len]
if t_sort == sorted(chunk):
# SUCCESS!!
In the for loop why are they taking S-len then subtracting t_len? Why are they adding 1 at the end?
alvits and d_void already explained the value of start; I won't repeat that.
I strongly recommend that you learn some basic trace debugging. Insert some useful print statements to follow the execution. For instance:
Code:
t = "goal"
s = "catalogue"
t_len = len(t)
s_len = len(s)
t_sort = sorted(t)
print "lengths & sorted", t_len, s_len, t_sort
for start in range(s_len - t_len + 1):
chunk = s[start:start+t_len]
print "LOOP start=", start, "\tchunk=", chunk, sorted(chunk)
if t_sort == sorted(chunk):
print "success"
Output:
lengths & sorted 4 9 ['a', 'g', 'l', 'o']
LOOP start= 0 chunk= cata ['a', 'a', 'c', 't']
LOOP start= 1 chunk= atal ['a', 'a', 'l', 't']
LOOP start= 2 chunk= talo ['a', 'l', 'o', 't']
LOOP start= 3 chunk= alog ['a', 'g', 'l', 'o']
success
LOOP start= 4 chunk= logu ['g', 'l', 'o', 'u']
LOOP start= 5 chunk= ogue ['e', 'g', 'o', 'u']
Does that help illustrate what's happening in the loop?

How to count the letters in a word? [duplicate]

This question already has answers here:
Letter Count on a string
(12 answers)
Closed 5 years ago.
I am trying to make a Python script which counts the amount of letters in a randomly chosen word for my Hangman game.
I already looked around on the web, but most thing I could find was count specific letters in a word. After more looking around I ended up with this, which does not work for some reason. If someone could point out the errors, that'd be greatly appreciated.
wordList = ["Tree", "Fish", "Monkey"]
wordChosen = random.choice(wordList)
wordCounter = wordChosen.lower().count['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']
print(wordCounter)
Are you looking for collections.Counter?
>>> import collections
>>> print(collections.Counter("Monkey"))
Counter({'M': 1, 'y': 1, 'k': 1, 'o': 1, 'n': 1, 'e': 1})
>>> print(collections.Counter("Tree"))
Counter({'e': 2, 'T': 1, 'r': 1})
>>> c = collections.Counter("Tree")
>>> print("The word 'Tree' has {} distinct letters".format(len(c)))
The word 'Tree' has 3 distinct letters
>>> print("The word 'Tree' has {} instances of the letter 'e'".format(c['e']))
The word 'Tree' has 2 instances of the letter 'e'
First off, your code contains an error that is rather important to understand:
wordChosen.lower().count['a', 'b'] #...
count is a function and so it requires you to surround its parameters with parentheses and not square brackets!
Next you should try to refer to Python Documentation when using a function for the first time. That should help you understand why your approach will not work.
Now to address your problem. If you want to count the number of letters in your string use len(wordChosen) which counts the total number of characters in the string.
If you want to count the frequencies of each letter a few methods have already been suggested. Here is one more using a dictionary:
import string
LetterFreq={}
for letter in string.ascii_lowercase:
LetterFreq[letter] = 0
for letter in wordChosen.lower():
LetterFreq[letter] += 1
This has the nice perk of defaulting all letters not present in the word to a frequency of 0 :)
Hope this helps!
Problem:The count method only takes in one argument and you are trying to pass a whole list.
Solution:Simply iterate over all the letters, then test if they are in the string before you print them and their amount.
import random
wordList = ["Tree", "Fish", "Monkey"]
wordChosen = random.choice(wordList)
letters = ['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']
for letter in letters:
if letter in wordChosen.lower():
amount = str(wordChosen.lower().count(letter))
print(letter + " : " + amount)
Result:If the random word chosen is "Tree":
e : 2
r : 1
t : 1
Conclusion:Using collections is definitely a more effective method, but I believe the way I have shown above creates more of the output you were looking for.

Categories

Resources