This is the second day of my participation in the August More text Challenge. For details, see: August More Text Challenge

preface

The thing is, the Nuggets have had a sign-in lottery for about a month and have been clocking in for 31 days.

As shown in the picture, the number of diamonds saved is 23834. (PS: Tests and hand base have already cost some diamonds, there should be about 30,000 diamonds.)

So 23,834 diamonds, 200 diamonds per draw, how many draws are needed?

The answer is simple: round down 119 times. Clicking and waiting on the page every time can be physically taxing.

PS: In fact, the answer is not prepared, later I will tell you the final answer is153Times.

In line with the principle that can write code, do not work, give full play to the advantages of programmers, write a script instead of me lucky draw.

Problem analysis

In a word: Nugget raffle is implemented in the manner of front-end animation + back-end interface implementation. So the real lottery action is to call the interface, the front end display the result of such a logic.

Without further saying that’s the interface that Google Chrome calls when it opens developer tools and looks at the draw. emm….

As shown in figure, in the case of has landed with the interface of https://api.juejin.cn/growth_api/v1/lottery/draw

Code implementation

The above analysis of lucky draw only need to call the lucky draw interface, then directly a circular lucky draw.


import requests
from requests import cookies

class Juejin(object) :

    # Nugget draw URL
    lottery_url = "https://api.juejin.cn/growth_api/v1/lottery/draw"

    def __init__(self, driver_cookies=None, cookie_obj=None) :
        self.session = requests.session()
        if driver_cookies:
            for cookie in driver_cookies:
                cookie_obj = requests.cookies.create_cookie(
                    domain=cookie.get("domain"),
                    name=cookie.get("name"),
                    value=cookie.get("value")
                )
                self.session.cookies.set_cookie(cookie_obj)
        elif cookie_obj:
            self.session.cookies.set_cookie(cookie_obj)
        else:
            raise Exception("Cookie is Blank")

    def request(self, *args, **kwargs) :

        response = self.session.request(*args, **kwargs)
        ifresponse.status_code ! =200:
            raise Exception("Request error")
        return response.json()

    def draw_lottery(self) :
        return self.request("post", self.lottery_url)


def lottery() :

    # Set session ID by yourself
    session_id = ""

    cookie = requests.cookies.create_cookie(
        domain=".juejin.cn",
        name="sessionid",
        value=session_id
    )
    juejin = Juejin(cookie_obj=cookie)

    gift = {}
    num = 1

    while True:
        result = juejin.draw_lottery()
        if result.get("err_no") = =0:
            lottery_name = result.get("data", {}).get("lottery_name")
            if gift.get(lottery_name):
                gift[lottery_name] += 1
            else:
                gift[lottery_name] = 1
            print(F "in the first{num}Lucky Draw results:{lottery_name}")
            num += 1
        else:
            print(result.get("err_msg"))
            break

    print(F "Total number of lucky draws:{num-1}")

    print("The final result of the draw is:")
    for k, v in gift.items():
        print(F "gift:{k}Number: -{v}")
Copy the code

Show the results of the program running (here is the test of the results of ten raffle) :

1st time - Lucky draw result: 66 ore 2nd time - Lucky draw result: 66 ore 3rd time - Lucky draw result: Bug 4th time - Lucky draw result: 66 ore 5th time - Lucky draw result: 66 ore 6th time - Lucky draw result: Bug 7th time - lucky draw result: 66 ore 8th time - Lucky draw result: 66 Ore 9th - Lucky draw result: Bug 10th - Lucky draw result: 66 ore total lucky draw number: {10} Gift: 66 ore ---- number: 7 Gift: Bug ---- number: 3Copy the code

The result of the drawing is displayed

Total diamonds: 23,834 Raffles: 153

Gift -66 Ore: 106 Gift -Bug: 47

To sum up: the probability of extracting 66 ore is 69.28%, and the probability of extracting Bug is 30.72%.

The probability of winning a draw for 10 tests was roughly consistent with that for 153 tests.

Highlights: This test proves that the chances of the Nuggets getting t-shirts, throw pillows and switches are basically zero, so don't be under any illusions.

Thinking and summarizing

  • How to use the program to achieve a similar lottery algorithm?

The way to do it is very simple to customize the interval, so as to control the result of the draw. Here’s a simple demonstration of the code:

import random


# 66 The proportion of ore to Bug is 7:3 [0-700] the random number is 66 ore, [700-1000] is Bug
def draw() :
    temp = random.randint(0.1000)

    if temp < 700:
        return "66 ore"
    else:
        return "Bug"
Copy the code
  • If I have 23,834 diamonds, what is the maximum number of raffles I can draw?

Initialize the number of diamonds
num = 23834

# 66 Probability of diamond acquisition
rate = 0.7

# Number of raffles
count = 0

while num >= 200:
    t, r = divmod(num,200)
    count += t
    num = (66 * t + r) * rate
    
print(count) 
# 153.0
Copy the code