Lottery win predictor - python

I am a beginner in Python and I think I need some help with my program. Any kind of help or advice would be appreciated:)
You can see the program below, when I run it it gets stuck on the part of comparing the random ticket with the winning ticket(win_combination).
from random import choice
#Winning ticket
win_combination = input("Enter the winning combination of 4 numbers(1-digit-numbers): ")
while len(win_combination) != 4:
if len(win_combination) > 4:
win_combination = input("Reenter a shorter combination(4 one-digit-numbers): ")
elif len(win_combination) < 4:
win_combination = input("Reenter a longer combination(4 one-digit-numbers): ")
print(f"Winning combination is {win_combination}.")
#Specifying range of numbers to choose from
range = range(0, 10)
#Making a fake comparison-ticket to start of the loop
random_ticket = [0, 0]
random_ticket_string = f"{random_ticket[0]}{random_ticket[1]}{random_ticket[2]}{random_ticket[3]}"
#Params for the loop
n_tries = 0
n_guesses = 1
while random_ticket_string != win_combination:
while n_tries > 4:
random_ticket.clear()
number = choice(range)
random_ticket.append(number)
n_tries += 1
n_guesses += 1
random_ticket_string = f"{random_ticket[0]}{random_ticket[1]}"
if random_ticket_string == win_combination:
chance_to_win = f"{(1 / n_guesses) * 100}%"
print("Estimated percent to win is " + chance_to_win + ", it took " + f"{n_guesses} to match the winning combination.")
else:
n_tries = 0

Related

Python "Dice Game"

I want to create a simple game in which two players "roll the dice against each other". Winner is whoever gets one number three times in a row. I tried many different ways but in the end I always struggled with the evaluation.
How can I determine which player got one specific number 3-times in a row? Thanks for your advice!
import random
#Initialisieren der Variablen
wurf1_1 = 0
wurf2_1 = 0
gewuerfelt_s1 = []
gewuerfelt_s2 = []
n = 1
while (True):
#Bestimmen der Augenzahlen des Würfels
wurf1_1 = random.randint(1,6)
wurf2_1 = random.randint(1,6)
print("Spiel " + str(n) + ":\tSpieler 1: " + str(wurf1_1) + "; Spieler 2: " + str(wurf2_1))
gewuerfelt_s1.append(wurf1_1)
gewuerfelt_s2.append(wurf2_1)
wurf1_2 = random.randint(1,6)
wurf2_2 = random.randint(1,6)
n += 1
print("Spiel " + str(n) + ":\tSpieler 1: " + str(wurf1_2) + "; Spieler 2: " + str(wurf2_2))
if (wurf1_2 == gewuerfelt_s1[0]):
gewuerfelt_s1.append(wurf1_2)
wurf1_3 = random.randint(1,6)
n += 1
print("Spiel " + str(n) + ":\tSpieler 1: " + str(wurf1_3) + "; Spieler 2: " + str(wurf2_2))
if wurf1_3 == gewuerfelt_s1[1]:
print("Spieler 1 hat dreimal hintereinander die Zahl", gewuerfelt_s1[1], "gewürfelt. Sieger!")
break
else:
del gewuerfelt_s1[:]
continue
else:
del gewuerfelt_s1[:]
continue
Don't delete elements from your list. You can check the most recently appended elements of a list by indexing from the end
The last element of a list is:
my_list[-1]
The second last is:
my_list[-2]
So for each roll after the second roll, you can check:
my_list[-1] == my_list[-2] == my_list[-3]
(Can't comment, low rep)
First of all, make a function that will simulate the dice, it should return an integer number between [1,6] and should be generated using easily available (pseudo)random functions.
Once this is done, Declare variables, continous1, continous2, prev1, prev2.
The prev variables would store the prev dice role answer for that player if the current turn is the same as the prev for that player, increasing the continuous count. The first to reach the 3 is your answer. Use a while loop to simulate this.
Here is the code
import random
continous1 = 0
continous2 = 0
prev1 = 0
prev2 = 0
while continous1 != 3 and continous2 != 3:
person1 = random.randint(1,6)
person2 = random.randint(1,6)
if person1 == prev1:
continous1 += 1
else:
continous1 = 0
if person2 == prev2:
continous2 += 1
else:
continous2 = 0
prev1 = person1
prev2 = person2
# Note that even if both persons win the game at the same time, the first person will be chosen as the winner
if continous1 == 3:
print("Person 1 won the game")
else:
print("Person 2 won the game")
Check this pseudo code
PlayGame()
{
bool gameover = false;
int turns ;
player1_values = []
player2_values = []
While(!gameover)
{
player1_values.Add(getrandon(1,6));
player2_values.Add(getrandon(1,6));
bool player1_won = Check(player1_values);
if(!player1_won && player1_values.Count == 3)
player1_values.Clear();
bool player2_won = Check(player2_values);
if(!player1_won && player2_values.Count == 3)
player2_values.Clear();
gameover = player1_won || player2_won;
}
}
Check(values)
{
if(values.Count < 3)
return false;
int num = values[0];
for(int i = 1;i<3;i++)
{
if(values[i] != num)
return false;
}
return true;
}

Some Math, and more functions in define statements

I'm new to python, and I'm trying here to make some math, in Quanity, and balance. But that function in define, don't do anything to balance, and quanity. When I print them they are still the stock.
Ballance = 7000 # 7K DEMO
# SANDELYS
Indica_WEED_QUANITY = 600
AMAZON_QUANITY = 18
STEAM_GIFT50_QUANITY = 4
# Price
STEAM_GIFT50_PRICE_PER1 = 50 # Each
Indica_WEED_PRICE_PER1 = 8
Amazon_Prime_PRICE_PER1 = 25 # Each
def PickForShopItem():
ShopPick = int(input("~ PRODUCT ID = "))
if ShopPick == 1:
clear()
while True:
Pasirinxm = input("Would You like to continue buying ~ Indica WEED KUSH * ?\n* Y/N: ")
if "Y" in Pasirinxm or "y" in Pasirinxm:
clear()
BuyKiekis = int(input("~ How many you would to buy of " + Indica_WEED_NAME + "?\n "))
Indica_WEED_QUANITY - BuyKiekis # Atimam Ir paliekam sandari mazesni
Bendra_Suma = ( BuyKiekis * Indica_WEED_PRICE_PER1)
print(Bendra_Suma)
Ballance = 500
print(Ballance - Bendra_Suma)
print("Sandelio Kiekis po pirkimo " + str(Indica_WEED_QUANITY))
print(Ballance)
break
elif "N" in Pasirinxm or "n" in Pasirinxm:
print("xuine iseina")
break
elif " " in Pasirinxm or len(Pasirinxm) < 1:
print("PLease dont do shit")
continue
break
elif ShopPick == 2:
print("Darai")
elif ShopPick == 3:
print("hgelo")
Indica_WEED_NAME = "~ Indica WEED KUSH *
I think the problem you have is that:
Indica_WEED_QUANITY - BuyKiekis
does not update the variable "Indica_WEED_QUANITY" (and you have the same problem in the line print(ballance - BendraSuma))
In Python, that statement will just work out a value, but you aren't telling the program to save or store it anywhere. Do this:
Indica_WEED_QUANITY = Indica_WEED_QUANITY - BuyKiekis
Python also allows you to do this with a -= operator:
Indica_WEED_QUANITY -= BuyKiekis
will update Indica_WEED_QUANITY by subtracting the BuyKeikis amounts.

Python Credit Card Validation

I'm a beginner Python learner and I'm currently working on Luhn Algorithm to check credit card validation. I wrote most of the code, but I'm stuck with 2 errors I get 1st one is num is referenced before assignment. 2nd one I'm getting is object of type '_io.TextIOWrapper' has no len(). Further help/ guidance will be greatly appreciated.
These are the steps for Luhn Algorithm (Mod10 Check)
Double every second digit from right to left. If this “doubling” results in a two-digit number, add the two-digit
number to get a single digit.
Now add all single digit numbers from step 1.
Add all digits in the odd places from right to left in the credit card number.
Sum the results from steps 2 & 3.
If the result from step 4 is divisible by 10, the card number is valid; otherwise, it is invalid.
Here's what my output is supposed to be
Card Number Valid / Invalid
--------------------------------------
3710293 Invalid
5190990281925290 Invalid
3716820019271998 Valid
37168200192719989 Invalid
8102966371298364 Invalid
6823119834248189 Valid
And here is the code.
def checkSecondDigits(num):
length = len(num)
sum = 0
for i in range(length-2,-1,-2):
number = eval(num[i])
number = number * 2
if number > 9:
strNumber = str(number)
number = eval(strNumber[0]) + eval(strNumber[1])
sum += number
return sum
def odd_digits(num):
length = len(num)
sumOdd = 0
for i in range(length-1,-1,-2):
num += eval(num[i])
return sumOdd
def c_length(num):
length = len(num)
if num >= 13 and num <= 16:
if num [0] == "4" or num [0] == "5" or num [0] == "6" or (num [0] == "3" and num [1] == "7"):
return True
else:
return False
def main():
filename = input("What is the name of your input file? ")
infile= open(filename,"r")
cc = (infile.readline().strip())
print(format("Card Number", "20s"), ("Valid / Invalid"))
print("------------------------------------")
while cc!= "EXIT":
even = checkSecondDigits(num)
odd = odd_digits(num)
c_len = c_length(num)
tot = even + odd
if c_len == True and tot % 10 == 0:
print(format(cc, "20s"), format("Valid", "20s"))
else:
print(format(cc, "20s"), format("Invalid", "20s"))
num = (infile.readline().strip())
main()
You just forgot to initialize num
def main():
filename = input("What is the name of your input file? ")
infile= open(filename,"r")
# initialize num here
num = cc = (infile.readline().strip())
print(format("Card Number", "20s"), ("Valid / Invalid"))
print("------------------------------------")
while cc!= "EXIT":
even = checkSecondDigits(num)
odd = odd_digits(num)
c_len = c_length(num)
tot = even + odd
if c_len == True and tot % 10 == 0:
print(format(cc, "20s"), format("Valid", "20s"))
else:
print(format(cc, "20s"), format("Invalid", "20s"))
num = cc = (infile.readline().strip())
First, maybe you should remove the extra characters:
def format_card(card_num):
"""
Formats card numbers to remove any spaces, unnecessary characters, etc
Input: Card number, integer or string
Output: Correctly formatted card number, string
"""
import re
card_num = str(card_num)
# Regex to remove any nondigit characters
return re.sub(r"\D", "", card_num)
After check if credit card is valid using the Luhn algorithm:
def validate_card(formated_card_num):
"""
Input: Card number, integer or string
Output: Valid?, boolean
"""
double = 0
total = 0
digits = str(card_num)
for i in range(len(digits) - 1, -1, -1):
for c in str((double + 1) * int(digits[i])):
total += int(c)
double = (double + 1) % 2
return (total % 10) == 0
This is a very simpler version of code it is based on lunh's algorithm
def validator(n):
validatelist=[]
for i in n:
validatelist.append(int(i))
for i in range(0,len(n),2):
validatelist[i] = validatelist[i]*2
if validatelist[i] >= 10:
validatelist[i] = validatelist[i]//10 + validatelist[i]%10
if sum(validatelist)%10 == 0:
print('This a valid credit card')
else:
print('This is not valid credit card')
def cardnumber():
result=''
while True:
try:
result = input('Please enter the 16 digit credit card number : ')
if not (len(result) == 16) or not type(int(result) == int) :
raise Exception
except Exception:
print('That is not a proper credit card number. \nMake sure you are entering digits not characters and all the 16 digits.')
continue
else:
break
return result
def goagain():
return input('Do you want to check again? (Yes/No) : ').lower()[0] == 'y'
def main():
while True:
result = cardnumber()
validator(result)
if not goagain():
break
if __name__ == '__main__':
main()
Old thread but the answer concerns me... and the real issue wasn't identified.
Actually, the error is that you have used the identifier (num) for the parameter when defining checkSecondDigits as the identifier/name of the argument when calling the function in the mainline. The function should be called in main() by
even = checkSecondDigits(cc) so the value in cc (which is the argument) is passed into num (as the parameter) for use within the function.
The same rookie error is made with odd_digits and cc_length.
This question (and the initially suggested answer) demonstrates a fundamental mis-understanding of passing arguments to parameters...
The suggested 'declaring' of num just hides this error/misunderstanding and also obfuscates the local and global scopes of num (which should only be local) and cc (which is global) so whilst the suggestion works in this case, it works for the wrong reason and is poor style and bad programming.
Further,
num should not appear anywhere in main() as it should be local to (only appear inside of) the functions called...
The last line in this code should be the same as the first, but the last line incorrectly assigns the data to num instead of cc
cc = (infile.readline().strip())
print(format("Card Number", "20s"), ("Valid / Invalid"))
print("------------------------------------")
while cc!= "EXIT":
even = checkSecondDigits(num)
odd = odd_digits(num)
c_len = c_length(num)
tot = even + odd
if c_len == True and tot % 10 == 0:
print(format(cc, "20s"), format("Valid", "20s"))
else:
print(format(cc, "20s"), format("Invalid", "20s"))
num = (infile.readline().strip())
you can use my code for card validation it is 100% dynamic because of the card structure is stored in CSV file, so it is easy to update here is the code on GitHub profile, python file link, code explanation file link and CSV for datafile link
python code:
# -*- coding: utf-8 -*-
"""
Created on Tue Sep 10 20:55:30 2019
#author: Preyash2047#gmail.com
"""
import csv
import numpy as np
#csv file imported and storf in reader
reader = csv.DictReader(open("card_data.csv"))
#input card number
card_number = input("Enter the card No: ")
#global variable declaration
min_digits=0
max_digits=0
card_number_list = list(card_number)
card_number_list_reverse=card_number_list[::-1]
card_number_length=len(card_number_list)
first_digit = int(card_number_list[0])
#global variable for final output
card_provider_list_number = 0
result_found = False
card_number_digits = 0
mit_name=""
#list
start=[]
end=[]
name=[]
c_d=[]
number_length=[]
min_max_digits_list=[]
#append the list from csv
for raw in reader:
start.append(raw['start'])
end.append(raw['end'])
name.append(raw['name'])
c_d.append(raw['c_d'])
number_length.append(raw['number_length'])
#initialize the value of min_digits & max_digits
def min_max_digits():
global min_digits
global max_digits
for i in range(len(start)):
available_length=number_length[i].split(',')
for j in range(len(available_length)):
min_max_digits_list.append(available_length[j])
min_max_digits_array = np.array(min_max_digits_list)
np.unique(min_max_digits_array)
min_digits=int(min(min_max_digits_array))
max_digits=int(max(min_max_digits_array))
#list to int
def list_to_int(noofdigits):
str1 = ""
return int(str1.join(noofdigits))
#card validation
def iin_identifier():
first_six_digit = list_to_int(card_number_list[0:6])
for i in range(len(start)):
if(first_six_digit >= int(start[i]) and first_six_digit <= int(end[i])):
available_length=number_length[i].split(',')
for j in range(len(available_length)):
if(card_number_length == int(available_length[j])):
global card_provider_list_number
card_provider_list_number = i
global card_number_digits
card_number_digits = available_length[j]
global result_found
result_found = True
#Major Industry Identifier (MII) identification
def mit_identifier():
global first_digit
global mit_name
switcher = {
1: "Airlines",
2: "Airlines",
3: "Travel and Entertainment",
4: "Banking and Financial Services",
5: "Banking and Financial Services",
6: "Merchandising and Banking",
7: "Petroleum",
8: "Health care, Telecommunications",
9: "National Assignment"
}
mit_name=switcher.get(first_digit, "MIT Identifier Not Found")
#Luhn Algorithm or modulo-10 Algorithm
def luhn_algorithm():
for i in range(card_number_length):
if(i%2!=0 and i!=0):
card_number_list_reverse[i]=int(card_number_list_reverse[i])*2
#print(str(i)+" "+ str(card_number_list_reverse[i]))
if(len(str(card_number_list_reverse[i]))==2):
even_number_2=list(str(card_number_list_reverse[i]))
card_number_list_reverse[i] = int(even_number_2[0])+int(even_number_2[1])
#print("\tsubsum "+str(i)+" "+str(card_number_list_reverse[i]))
else:
card_number_list_reverse[i]=int(card_number_list_reverse[i])
division_int = int(sum(card_number_list_reverse)/10)
division_float=sum(card_number_list_reverse)/10
if(division_int-division_float==0):
return True
#initial level number length validation
def card_number_validation():
min_max_digits()
if(card_number_length>= min_digits and card_number_length <= max_digits and first_digit != 0):
iin_identifier()
mit_identifier()
if(result_found and luhn_algorithm()):
print("\nEntered Details are Correct\n")
print("\nHere are the some details we know about you card")
print("\nNo: "+card_number)
print("\nIssuing Network: "+name[card_provider_list_number])
print("\nType: "+c_d[card_provider_list_number]+" Card")
print("\nCategory of the entity which issued the Card: "+mit_name)
else:
print("\nCard Number is Invalid\nPlease renter the number!\n")
else:
print("\nCard Number is Invalid\n")
#method called to run program
card_number_validation()
n = input("Enter 16-digit Credit Card Number:")
lst = []
for i in range(16):
lst.append(n[i])
# print(lst)
# list1 = n.split()
# print(list1)
def validate_credit_card():
global lst
if len(lst) == 16:
for i in range(0, len(lst)):
lst[i] = int(lst[i])
# print(lst)
last = lst[15]
first = lst[:15]
# print(first)
# print(last)
first = first[::-1]
# print(first)
for i in range(len(first)):
if i % 2 == 0:
first[i] = first[i] * 2
if first[i] > 9:
first[i] -= 9
sum_all = sum(first)
# print(first)
# print(sum_all)
t1 = sum_all % 10
t2 = t1 + last
if t2 % 10 is 0:
print("Valid Credit Card")
else:
print("Invalid Credit Card!")
else:
print("Credit Card number limit Exceeded!!!!")
exit()
if __name__ == "__main__":
validate_credit_card()

Python Never - Ending While Loop [duplicate]

This question already has answers here:
How to test multiple variables for equality against a single value?
(31 answers)
Closed 6 years ago.
Currently I'm working in Python to try and simulate a set in a match of tennis based on player probabilities. There's a while loop that's never ending in my "ftsix" (firsttosixpoints) function, but I can't figure out what the bug is because my logic isn't sound. I've been working on the problem for a few hours but I can't seem to find the solution.
P.S - please play nice
#One set in tennis = 1st to 6 games
#One game = 1st to four points
#Serve switches after each game.
def main():
printIntro()
probA, probB = getInputs()
gamesA, gamesB = ftsix(probA, probB)
if gamesA > gamesB:
print"Player A has won with", gamesA, "to player B's", gamesB, "."
else:
print "Player B has won with", gamesB,"to player A's", gamesA, "."
def printIntro():
print "This is a simulation of 1 tennis set based on player probabilities!"
def getInputs():
probA = input("What is the probability that player A will win?: ")
probB = input("What is the probability that player B will win?: ")
return probA, probB
def ftsix(probA, probB):
#First one to six games = one set
x = 0
gamesA = 0
gamesB = 0
while gamesA or gamesB != 6:
if x % 2 == 0 or x == 0:
serving = "A"
else:
serving = "B"
#This is one game, not in a seperate function because I couldn't figure out how to change serve inside the function!
pointsA = 0
pointsB = 0
while pointsA or pointsB != 4:
if serving == "A":
if probA >= random():
pointsA = pointsA + 1
else:
pointsB = pointsB + 1
if serving == "B":
if probB >= random():
pointsB = pointsB + 1
else:
pointsA = pointsA + 1
if pointsA > pointsB:
gamesA = gamesA + 1
else:
gamesB = gamesB + 1
x = x + 1
return gamesA, gamesB
I think your syntax in the while loops is incorrect. You need a full conditional on each side of the or, for example:
while gamesA != 6 and gamesB != 6:
You need to change your loop to terminate when either gamesA or gamesB reaches 6:
while gamesA != 6 and games != 6:

New Hangman Python

I am working on a Hangman game, but I am having trouble replacing the dashes with the guessed letter. The new string just adds on new dashes instead of replacing the dashes with the guessed letter.
I would really appreciate it if anyone could help.
import random
import math
import os
game = 0
points = 4
original = ["++12345","+*2222","*+33333","**444"]
plusortimes = ["+","*"]
numbers = ["1","2","3"]
#FUNCTIONS
def firstPart():
print "Welcome to the Numeric-Hangman game!"
def example():
result = ""
ori = random.choice(original)
for i in range(2,len(ori)):
if i % 2 == 0:
result = result + ori[i] + ori[0]
else:
result = result + ori[i] + ori[1]
return ori
# def actualGame(length):
#TOP LEVEL
firstPart()
play = raw_input("Do you want to play ? Y - yes, N - no: ")
while (play == "Y" and (points >= 2)):
game = game + 1
points = points
print "Playing game #: ",game
print "Your points so far are: ",points
limit = input("Maximum wrong guesses you want to have allowed? ")
length = input("Maximum length you want for the formulas (including symbols) (must be >= 5)? ")
result = "" #TRACE
ori = random.choice(original)
for i in range(2,len(ori)):
if i % 2 == 0:
result = result + ori[i] + ori[0]
else:
result = result + ori[i] + ori[1]
test = eval(result[:-1])
v = random.choice(plusortimes) #start of randomly generated formula
va = random.choice(plusortimes)
formula = ""
while (len(formula) <= (length - 3)):
formula = formula + random.choice(numbers)
formula2 = str(v + va + formula)
kind = ""
for i in range(2,len(formula2)):
if i % 2 == 0:
kind = kind + formula2[i] + formula2[0]
else:
kind = kind + formula2[i] + formula2[1]
formula3 = eval(kind[:-1])
partial_fmla = "------"
print " (JUST TO TRACE, the program invented the formula: )" ,ori
print " (JUST TO TRACE, the program evaluated the formula: )",test
print "The formula you will have to guess has",length,"symbols: ",partial_fmla
print "You can use digits 1 to 3 and symbols + *"
guess = raw_input("Please enter an operation symbol or digit: ")
a = 0
new = ""
while a<limit:
for i in range(len(formula2)):
if (formula2[i] == partial_fmla[i]):
new = new + partial_fmla[i]
elif (formula2[i] == guess):
new[i] = guess
else:
new[i] =new + "-"
a = a+1
print new
guess = raw_input("Please enter an operation symbol or digit: ")
play = raw_input("Do you want to play ? Y - yes, N - no: ")
The following block seems problematic:
elif (formula2[i] == guess):
new[i] = guess
else:
new[i] =new + "-"
Python does not allow modification of characters within strings, as they are immutable (cannot be changed). Try appending the desired character to your new string instead. For example:
elif formula2[i] == guess:
new += guess
else:
new += '-'
Finally, you should put the definition of new inside the loop directly under, as you want to regenerate it after each guess.

Categories