Everyone should have dreamed of winning the lottery! I use Python to realize your fantasy. If you win, remember to divide me!

Posted by lanrat on Fri, 28 Jan 2022 15:40:22 +0100


I think everyone should be the same as Xiaobian. Xiaobian usually spends a few yuan to buy a few notes when he passes by the lottery shop! After all, what if you want to win the prize, right! Then who still works, although it may be equivalent to a house! But it's all money!

But often they don't win, or about five yuan! Hahaha, maybe it's not my turn to win this prize!

Well, no more digressions! Today is about technology, not lottery! After all, that thing depends on luck and life, hahaha! Just have fun

Demand introduction

The demand is mainly to analyze the historical data of the lottery. The name of the lottery is:

 

1. Speed airship 2. Speed racing

The customer's demand is based on the situation of the first two phases of the lottery. If there are two oblique numbers equal, then buy the lottery at the same position in the third phase,

For high-speed airships, if the equal number is 1-5, then buy 6-10; if the equal number is 6-10, then buy 1-5;

For speed cars, if the equal number is 1-5, buy 1-5. If the equal number is 6-10, buy 6-10.

 

 

 

 

Then, according to this scheme, it is possible to win, but it is also possible not to win. Therefore, the customer hopes that I can count the number of times and corresponding time of winning a prize only after purchasing lottery tickets for 6 consecutive times or more in 100 days. For this case, we will analyze it in detail below.

 

2, Taking the airship as an example, the data are analyzed

 

(here, we first use Jupyter Notebook for analysis, and then, after obtaining the results, we use pychar for complete program design.)

1. Get the data of one day. Open the interface shown in the figure below to get the website and request header: ①. Website (website of historical data)

 

 

 

② . request header

 

 

 

Then we write code in the program to obtain data:

 

 

 

 

 

 

Then carry out certain pretreatment:

 

 

 

2. Start the day's data analysis

Here we show the code directly:

def reverse_list(lst):
    """
    Order of quasi exchange list
    :param lst: Original list
    :return: New list
    """
    return [ele for ele in reversed(lst)]
 
 
 
low_list = ["01", "02", "03", "04", "05"]
# Set a list of smaller numbers
high_list = ["06", "07", "08", "09", "10"]
# Set a list of larger numbers
N = 0
# Set a number N to record how many issues can be purchased
n = 0
# Set a number n to record how many lottery tickets were hit
record_number = 1  
# Set a judgment value of recorded data
list_data_number = []
# Set up an empty list to store the number of consecutive hang ups in a day
dict_time_record = {}
# Set up an empty dictionary to store the time node when the number of periods that are hung up meets the listed conditions
for k in range(1152):  
    # Loop through all data points
    if k < 1150:
        new_result1 = reverse_list(new_response["result"]["data"])[k]  
        # Phase I data
        new_result2 = reverse_list(new_response["result"]["data"])[k + 1]  
        # Phase II data
        new_result3 = reverse_list(new_response["result"]["data"])[k + 2]  
        # Phase III data
        data1 = new_result1['preDrawCode'].split(',')
        # Phase I data
        data2 = new_result2['preDrawCode'].split(',')
        # Phase II data
        data3 = new_result3['preDrawCode'].split(',')
        # Phase III data
        for m in range(10):
            # Through the cycle to judge whether the purchase conditions are met, and realize certain functions
            if m == 0:
                if data2[0] == data1[1]:  
                    # If equal, end the loop
                    N += 1
                    # The number of periods that can be purchased should be increased by one
                    if (data2[0] in low_list and data3[0] in low_list) or (data2[0] in high_list and data3[0] in high_list):
                        n += 1
                        # The number of hit periods should be increased by one
                        # If you hit, this round ends and the next round starts
                        list_data_number.append(record_number)
                        if f"{record_number}" in dict_time_record.keys():
                            # If you already have this key, the value is added to the time point
                            dict_time_record[f"{record_number}"].append(new_result3['preDrawTime'][11:])
                        else:
                            # If there is no key, add a key value pair, the value is a list, and the initialization is the current time
                            dict_time_record[f"{record_number}"] = [new_result3['preDrawTime'][11:]]
                        record_number = 1  
                        # Initialize the start of the next round
                    else:
                        record_number += 1  
                        # If you don't hit, you should increase the number by one
                    break  
                    # If equal conditions are met, the loop is ended
            elif m == 9:  
                # Similar to the above algorithm
                if data2[9] == data1[8]:  
                    # If equal
                    N += 1
                    if (data2[9] in low_list and data3[9] in low_list) or (data2[9] in high_list and data3[9] in high_list):
                        n += 1
                        list_data_number.append(record_number)
                        if f"{record_number}" in dict_time_record.keys():
                            dict_time_record[f"{record_number}"].append(new_result3['preDrawTime'][11:])
                        else:
                            dict_time_record[f"{record_number}"] = [new_result3['preDrawTime'][11:]]
                        record_number = 1
                    else:
                        record_number += 1
                    break
            else:  
                # Similar to the above algorithm
                if data2[m] == data1[m + 1] or data2[m] == data1[m - 1]:  
                    # If equal
                    N += 1
                    if (data2[m] in low_list and data3[m] in low_list) or (data2[m] in high_list and data3[m] in high_list):
                        n += 1
                        list_data_number.append(record_number)
                        if f"{record_number}" in dict_time_record.keys():
                            dict_time_record[f"{record_number}"].append(new_result3['preDrawTime'][11:])
                        else:
                            dict_time_record[f"{record_number}"] = [new_result3['preDrawTime'][11:]]
                        record_number = 1
                    else:
                        record_number += 1
                    break
print(f"date:{new_response['result']['data'][0]['preDrawTime'][:10]},The total number of ladders is{N}individual,Altogether{n}Hit times,Altogether{N - n}Hang up for the first time")
# Print time, and the number of periods that can be purchased, the number of hit periods, and the number of missed periods
list_data_number.sort()
# Sort by size
dict_record = {}
# Set an empty dictionary for recording
for i in list_data_number:
    if f"{i}" in dict_record.keys():  # Determine whether this number already exists?
        dict_record[f"{i}"] += 1
        # If so, it will add one by itself
    else:  # If not, it is created and assigned a value equal to 1
        dict_record[f"{i}"] = 1
        # Create a new dictionary element and assign a value of 1
for j in dict_record.keys():
    if (int(j) >= 6) and (int(j) < 15):
        # The actual results show that we need data greater than or equal to 6 periods, but there is no data greater than 15. Therefore, there is such a relationship
        print(f"buy{j}The number of times to win the prize is{dict_record[j]}")
        # Print relevant information
        print(dict_time_record[j])
        str0 = ""
        for letter in dict_time_record[j]:
            str0 += letter
            str0 += ", "
        print(str0)
        # Print relevant information

The display of operation results is shown in the figure below:

 

 

 

 

3. Multi day data analysis of cycle date:

First, set up an event list to record which days of data need to be counted:

code:

data_list = []
for h in range(31):
    data_list.append(f'1-{h + 1}')
for h in range(28):
    data_list.append(f'2-{h + 1}')
for h in range(31):
    data_list.append(f'3-{h + 1}')
for h in range(20):
    data_list.append(f'4-{h + 1}')

Through the above code, we realize the setting of the time list, and then we cycle through the list to access the lottery data on different dates, that is, we get the data at different times, and then use the above analysis method for data analysis, that is, we can get the results of lottery data analysis for many days.

 

4. Write data to Excel table

Here, we can use xlwt module to write excel tables. There is no need to elaborate on the specific writing.

3, Complete code presentation

 

The following is the complete code:

import requests
import chardet
import json
import xlwt  # Corresponding module of excel data processing
 
 
def reverse_list(lst):
    """
    Order of quasi exchange list
    :param lst: Original list
    :return: New list
    """
    return [ele for ele in reversed(lst)]
 
 
data_list = []
for h in range(31):
    data_list.append(f'1-{h + 1}')
for h in range(28):
    data_list.append(f'2-{h + 1}')
for h in range(31):
    data_list.append(f'3-{h + 1}')
for h in range(20):
    data_list.append(f'4-{h + 1}')
 
 
wb = xlwt.Workbook()  # Create excel table
sh = wb.add_sheet('Lottery analysis and data processing')  # Create a form
sh.write(0, 0, "date")
sh.write(0, 1, "Number of ladders")
sh.write(0, 2, "Number of hits")
sh.write(0, 3, "Number of hangs")
sh.write(0, 4, "6 Number of times")
sh.write(0, 5, "6 Time in time")
sh.write(0, 6, "7 Number of times")
sh.write(0, 7, "7 Time in time")
sh.write(0, 8, "8 Number of times")
sh.write(0, 9, "8 Time in time")
sh.write(0, 10, "9 Number of times")
sh.write(0, 11, "9 Time in time")
sh.write(0, 12, "10 Number of times")
sh.write(0, 13, "10 Time in time")
sh.write(0, 14, "11 Number of times")
sh.write(0, 15, "11 Time in time")
sh.write(0, 16, "12 Number of times")
sh.write(0, 17, "12 Time in time")
sh.write(0, 18, "13 Number of times")
sh.write(0, 19, "13 Time in time")
sh.write(0, 20, "14 Number of times")
sh.write(0, 21, "14 Time in time")
# wb.save('test4.xls')
 
 
sheet_seek_position = 1
# Set the initial position of the table to 1
for data in data_list:
    low_list = ["01", "02", "03", "04", "05"]
    high_list = ["06", "07", "08", "09", "10"]
    N = 0
    n = 0
    url = f'https://api.api68.com/pks/getPksHistoryList.do?date=2021-{data}&lotCode=10037'
    headers = {
        'User-Agent':
            'Mozilla/5.0 (Windows NT 10.0; Win64; x64) '
            'AppleWebKit/537.36 (KHTML, like Gecko) '
            'Chrome/90.0.4430.72 Safari/537.36'
    }
    response = requests.get(url=url, headers=headers)
    response.encoding = chardet.detect(response.content)['encoding']
    new_response = json.loads(response.text)
    sh.write(sheet_seek_position, 0, new_response['result']['data'][0]['preDrawTime'][:10])
    # Write the time at the first position of the table, which means: data
    record_number = 1  # A judgment value of recorded data, set to the first time, should be placed on the outermost
    list_data_number = []
    # Set up an empty list to store the number of consecutive sessions in a day
    dict_time_record = {}
    for k in range(1152):
        # record_number = 1, it should be put outside
        # A judgment value of recorded data, set to the first time
        if k < 1150:
            new_result1 = reverse_list(new_response["result"]["data"])[k]
            new_result2 = reverse_list(new_response["result"]["data"])[k + 1]
            new_result3 = reverse_list(new_response["result"]["data"])[k + 2]
            data1 = new_result1['preDrawCode'].split(',')
            data2 = new_result2['preDrawCode'].split(',')
            data3 = new_result3['preDrawCode'].split(',')
            for m in range(10):
                if m == 0:
                    if data2[0] == data1[1]:
 
                        N += 1
                        if (data2[0] in low_list and data3[0] in high_list) or (data2[0] in high_list and data3[0] in low_list):
                            n += 1
                            # If you hit, this round ends and the next round starts
                            list_data_number.append(record_number)
 
                            if f"{record_number}" in dict_time_record.keys():
                                dict_time_record[f"{record_number}"].append(new_result3['preDrawTime'][11:])
                            else:
                                dict_time_record[f"{record_number}"] = [new_result3['preDrawTime'][11:]]
 
 
                            # print(record_number)
                            record_number = 1  # initialization
                        else:
                            record_number += 1  # No, add one to the number
                            # Self plus one
                        break
                elif m == 9:
                    if data2[9] == data1[8]:
                        N += 1
                        if (data2[9] in low_list and data3[9] in high_list) or (data2[9] in high_list and data3[9] in low_list):
                            n += 1
                            list_data_number.append(record_number)
 
                            if f"{record_number}" in dict_time_record.keys():
                                dict_time_record[f"{record_number}"].append(new_result3['preDrawTime'][11:])
                            else:
                                dict_time_record[f"{record_number}"] = [new_result3['preDrawTime'][11:]]
 
 
                            # print(record_number)
                            record_number = 1
                        else:
                            record_number += 1
                        break
                else:
                    if data2[m] == data1[m + 1] or data2[m] == data1[m - 1]:
                        N += 1
                        if (data2[m] in low_list and data3[m] in high_list) or (data2[m] in high_list and data3[m] in low_list):
                            n += 1
                            list_data_number.append(record_number)
 
                            if f"{record_number}" in dict_time_record.keys():
                                dict_time_record[f"{record_number}"].append(new_result3['preDrawTime'][11:])
                            else:
                                dict_time_record[f"{record_number}"] = [new_result3['preDrawTime'][11:]]
 
 
                            # print(record_number)
                            record_number = 1
                        else:
                            record_number += 1
                        break
    print(f"date:{new_response['result']['data'][0]['preDrawTime'][:10]},The total number of ladders is{N}individual,Altogether{n}Hit times,Altogether{N - n}Hang up for the first time")
    sh.write(sheet_seek_position, 1, N)
    sh.write(sheet_seek_position, 2, n)
    sh.write(sheet_seek_position, 3, N - n)
 
    # new_list_data_number = list_data_number.sort()
    list_data_number.sort()
    # Sort
    dict_record = {}
    # Set empty dictionary
 
    for i in list_data_number:
        if f"{i}" in dict_record.keys():  # Determine whether this number already exists?
            dict_record[f"{i}"] += 1
            # If so, it will add one by itself
        else:  # If not, it is created and assigned a value equal to 1
            dict_record[f"{i}"] = 1
            # Create a new dictionary element and assign a value of 1
    # print(dict_record)
    # print(f "how many times did you win the lottery?"
    # print(f "buying lottery tickets according to our rules:")
    for j in dict_record.keys():
        if (int(j) >= 6) and (int(j) < 15):
            print(f"buy{j}The number of times to win the prize is{dict_record[j]}")
            print(dict_time_record[j])
            str0 = ""
            for letter in dict_time_record[j]:
                str0 += letter
                str0 += ", "
            print(str0)
            sh.write(sheet_seek_position, 4 + (int(j) - 6) * 2, dict_record[j])
            # Write several times
            sh.write(sheet_seek_position, 4 + (int(j) - 6) * 2 + 1, str0[:-2])  
            # Note that this should be changed to - 2
            # Write the corresponding time several times
            # print(j)
    sheet_seek_position += 1
    # After each writing, the position should be wrapped to the next line, so as to facilitate the writing of the next line
 
 
# preservation
wb.save('Analysis results of extreme speed airship lottery.xls')

Display of operation results:

 

Exhibit 1

 

 

 

 

Exhibit 2

 

 

 

Thus, we solved the data analysis of the lottery ticket of the high-speed airship

Then, we only need to change the algorithm a little bit, and the other parts are exactly the same, so that we can realize the data analysis of speed racing.

The modified code is listed below:

            for m in range(10):
                if m == 0:
                    if data2[0] == data1[1]:
 
                        N += 1
                        if (data2[0] in low_list and data3[0] in low_list) or (data2[0] in high_list and data3[0] in high_list):
                            n += 1
                            # If you hit, this round ends and the next round starts
                            list_data_number.append(record_number)
 
                            if f"{record_number}" in dict_time_record.keys():
                                dict_time_record[f"{record_number}"].append(new_result3['preDrawTime'][11:])
                            else:
                                dict_time_record[f"{record_number}"] = [new_result3['preDrawTime'][11:]]
 
 
                            # print(record_number)
                            record_number = 1  # initialization
                        else:
                            record_number += 1  # No, add one to the number
                            # Self plus one
                        break
                elif m == 9:
                    if data2[9] == data1[8]:
                        N += 1
                        if (data2[9] in low_list and data3[9] in low_list) or (data2[9] in high_list and data3[9] in high_list):
                            n += 1
                            list_data_number.append(record_number)
 
                            if f"{record_number}" in dict_time_record.keys():
                                dict_time_record[f"{record_number}"].append(new_result3['preDrawTime'][11:])
                            else:
                                dict_time_record[f"{record_number}"] = [new_result3['preDrawTime'][11:]]
 
 
                            # print(record_number)
                            record_number = 1
                        else:
                            record_number += 1
                        break
                else:
                    if data2[m] == data1[m + 1] or data2[m] == data1[m - 1]:
                        N += 1
                        if (data2[m] in low_list and data3[m] in low_list) or (data2[m] in high_list and data3[m] in high_list):
                            n += 1
                            list_data_number.append(record_number)
 
                            if f"{record_number}" in dict_time_record.keys():
                                dict_time_record[f"{record_number}"].append(new_result3['preDrawTime'][11:])
                            else:
                                dict_time_record[f"{record_number}"] = [new_result3['preDrawTime'][11:]]
 
 
                            # print(record_number)
                            record_number = 1
                        else:
                            record_number += 1
                        break

summary

 

I have to say that this requirement is indeed relatively simple, but in the process of completing this task, I did learn something I didn't pay much attention to before. At the same time, I have skillfully mastered some programming skills. Although the reward for this relatively simple work will not be too high, I think I have learned a lot and grown a lot in this process. Therefore, no matter what I say, it is still very good.

How to get the source code:

① More than 3000 Python e-books ② Python development environment installation tutorials ③ Python 400 self-study videos ④ common vocabulary of software development ⑤ Python learning roadmap ⑥ project source code case sharing. If you can use it, you can take it away directly, In my QQ technical exchange group, group number: 754370353 (pure technical exchange and resource sharing, advertising is not allowed) is taken away by self-help Click here to receive

 

Thank you for reading! If there is help, you can pay a little attention!

 

 

Topics: Python Java Big Data Data Analysis list