搜索最接近的数字和给定数字的算法

时间:2018-02-08 00:43:29

标签: python algorithm

E.g。我们有[2, 5, 8, 10]和给定的16个数。因此,最接近的数字(到给定数字的最短距离)将是2 + 5 + 10 = 17

或者,我们有[1, 2, 5, 7]和给定数量的11。在这种情况下:1 + 2 + 7 = 10

3 个答案:

答案 0 :(得分:1)

对子集求和问题使用动态编程 - 但将总和表填充到S+Max(set)-1值。然后选择最接近S-th的填充条目并恢复加数。

答案 1 :(得分:0)

好吧,如果我们有一个包含n个元素的给定集合from matplotlib import pyplot as plt from matplotlib import animation,rc import pandas as pd fig = plt.figure() df=pd.read_csv(...) df.dropna(axis="columns", how="any", inplace=True) df.columns.values[1] = 'Y' line, = plt.plot(df['X'][:1], df['Y'][:1],color='g',lw='0.5') scatter = plt.scatter(df['X'][0], df['Y'][0],10,facecolor='r',edgecolor='r') def animate(n): x,y=df['X'][:n+1], df['Y'][:n+1] line.set_data(x,y) scatter.set_offsets([df['X'][n], df['Y'][n]]) plt.gca().relim() plt.gca().autoscale_view() anim = animation.FuncAnimation(fig, animate,frames=len(df['X']), interval=100) plt.show() ,我们可以采用A的所有排列,这些排列都是n。对于每个排列,计算总和并将其保存在地图中,如下所示:subsets of A。然后,要找到与给定数字最接近的和,迭代所有键,并跟踪哪个绝对值最小sum => permutation,如果找到较小的值,则保存abs(given_number - current_key)。最后,查找该密钥的排列,这就是你如何得到你搜索过的集合。

答案 2 :(得分:0)

const functions = require('firebase-functions');

const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);

exports.helloWorld = functions.https.onRequest((request, response) => {
    response.send("Hello from Firebase and browniePointsBeta!");
});

exports.sendPushNotifications = functions.https.onRequest((req, res) => {
    res.send("Attempting to send push notification....")
    console.log("Logger --- trying to send push notification....")

    var fcmToken = "dlwIIdEGtzY:APA91bEckWNnjW_D7vOB1ipwYTkOMAOJSdnOmyafCZ5MN5eGoZtx02PnYbJ2LGxfXWyR6Nx3zKvUqyb8N6atk8Z-oFEWsJYyvrd74AvIr0dMmvwlYHRxYz5PpXZ5iFW26H4ZJ2PQ8paa";

    var payload = {
        notification: {
            title: "Push notification title here!",
            body: "Body of push notification here!"
        }
    };

    admin.messaging().sendToDevice(fcmToken, payload)
        .then(function(response) {
            // See the MessagingDevicesResponse reference documentation for
            // the contents of response.
            console.log("Successfully sent message:", response);
            // return true
        })
        .catch(function(error) {
            console.log("Error sending message:", error);
            // return true
        });
})