首页 > 编程知识 正文

用于k的汇合python,集合里面的k是什么意思

时间:2023-12-27 22:26:35 阅读:324545 作者:EMBN

本文目录一览:

用python输入k个正整数,其中每个数都是大于等于1,小于等于10的数。编写程序?

while True:

k = input('请输入大于等于1或者小于等于10的数字,用空格隔开')

if k == 'exit':

print('程序已退出')

break

ls = k.split(' ')

for item in ls:

if not item.isdigit():

print("请输入数字")

break

elif int(item) 1 or int(item) 10:

print('输入的数字不合法')

print('您输入的是', k)

PYTHON问题要用这些钱来支付K元,最少要用多少张纸币?程序输入K,输出纸币组合。

package TanXin;

/*钱币找零问题 */

/* 这个问题在我们的日常生活中就更加普遍了。假设1元、2元、5元、10元、20元、50元、100元的纸币分别有c0, c1, c2, c3, c4, c5, c6张。现在要用这些钱来支付K元,至少要用多少张纸币?用贪心算法的思想,很显然,每一步尽可能用面值大的纸币即可。在日常生活中我们自然而然也是这么做的。在程序中已经事先将Value按照从小到大的顺序排好。*/

public class QianBiZhaoLing {

public static void main(String[] args) {

//人民币面值集合

int[] values = { 1, 2, 5, 10, 20, 50, 100 };

//各种面值对应数量集合

int[] counts = { 3, 1, 2, 1, 1, 3, 5 };

//求442元人民币需各种面值多少张

int[] num = change(442, values, counts);

print(num, values);

}

public static int[] change(int money, int[] values, int[] counts) {

//用来记录需要的各种面值张数

int[] result = new int[values.length];

for (int i = values.length - 1; i = 0; i--) {

int num = 0;

//需要最大面值人民币张数

int c = min(money / values[i], counts[i]);

//剩下钱数

money = money - c * values[i];

//将需要最大面值人民币张数存入数组

num += c;

result[i] = num;

}

return result;

}

/**

* 返回最小值

*/

private static int min(int i, int j) {

return i j ? j : i;

}

private static void print(int[] num, int[] values) {

for (int i = 0; i values.length; i++) {

if (num[i] != 0) {

System.out.println("需要面额为" + values[i] + "的人民币" + num[i] + "张");

}

}

}

}

kmeans算法用Python怎么实现

from math import pi, sin, cos

from collections import namedtuple

from random import random, choice

from copy import copytry:

    import psyco

    psyco.full()

except ImportError:

    pass

FLOAT_MAX = 1e100

class Point:

    __slots__ = ["x", "y", "group"]

    def __init__(self, x=0.0, y=0.0, group=0):

        self.x, self.y, self.group = x, y, group

def generate_points(npoints, radius):

    points = [Point() for _ in xrange(npoints)]

    # note: this is not a uniform 2-d distribution

    for p in points:

        r = random() * radius

        ang = random() * 2 * pi

        p.x = r * cos(ang)

        p.y = r * sin(ang)

    return points

def nearest_cluster_center(point, cluster_centers):

    """Distance and index of the closest cluster center"""

    def sqr_distance_2D(a, b):

        return (a.x - b.x) ** 2  +  (a.y - b.y) ** 2

    min_index = point.group

    min_dist = FLOAT_MAX

    for i, cc in enumerate(cluster_centers):

        d = sqr_distance_2D(cc, point)

        if min_dist  d:

            min_dist = d

            min_index = i

    return (min_index, min_dist)

'''

points是数据点,nclusters是给定的簇类数目

cluster_centers包含初始化的nclusters个中心点,开始都是对象-(0,0,0)

'''

def kpp(points, cluster_centers):

    cluster_centers[0] = copy(choice(points)) #随机选取第一个中心点

    d = [0.0 for _ in xrange(len(points))]  #列表,长度为len(points),保存每个点离最近的中心点的距离

    for i in xrange(1, len(cluster_centers)):  # i=1...len(c_c)-1

        sum = 0

        for j, p in enumerate(points):

            d[j] = nearest_cluster_center(p, cluster_centers[:i])[1] #第j个数据点p与各个中心点距离的最小值

            sum += d[j]

        sum *= random()

        for j, di in enumerate(d):

            sum -= di

            if sum  0:

                continue

            cluster_centers[i] = copy(points[j])

            break

    for p in points:

        p.group = nearest_cluster_center(p, cluster_centers)[0]

'''

points是数据点,nclusters是给定的簇类数目

'''

def lloyd(points, nclusters):

    cluster_centers = [Point() for _ in xrange(nclusters)]  #根据指定的中心点个数,初始化中心点,均为(0,0,0)

    # call k++ init

    kpp(points, cluster_centers)   #选择初始种子点

    # 下面是kmeans

    lenpts10 = len(points)  10

    changed = 0

    while True:

        # group element for centroids are used as counters

        for cc in cluster_centers:

            cc.x = 0

            cc.y = 0

            cc.group = 0

        for p in points:

            cluster_centers[p.group].group += 1  #与该种子点在同一簇的数据点的个数

            cluster_centers[p.group].x += p.x

            cluster_centers[p.group].y += p.y

        for cc in cluster_centers:    #生成新的中心点

            cc.x /= cc.group

            cc.y /= cc.group

        # find closest centroid of each PointPtr

        changed = 0  #记录所属簇发生变化的数据点的个数

        for p in points:

            min_i = nearest_cluster_center(p, cluster_centers)[0]

            if min_i != p.group:

                changed += 1

                p.group = min_i

        # stop when 99.9% of points are good

        if changed = lenpts10:

            break

    for i, cc in enumerate(cluster_centers):

        cc.group = i

    return cluster_centers

def print_eps(points, cluster_centers, W=400, H=400):

    Color = namedtuple("Color", "r g b");

    colors = []

    for i in xrange(len(cluster_centers)):

        colors.append(Color((3 * (i + 1) % 11) / 11.0,

                            (7 * i % 11) / 11.0,

                            (9 * i % 11) / 11.0))

    max_x = max_y = -FLOAT_MAX

    min_x = min_y = FLOAT_MAX

    for p in points:

        if max_x  p.x: max_x = p.x

        if min_x  p.x: min_x = p.x

        if max_y  p.y: max_y = p.y

        if min_y  p.y: min_y = p.y

    scale = min(W / (max_x - min_x),

                H / (max_y - min_y))

    cx = (max_x + min_x) / 2

    cy = (max_y + min_y) / 2

    print "%%!PS-Adobe-3.0n%%%%BoundingBox: -5 -5 %d %d" % (W + 10, H + 10)

    print ("/l {rlineto} def /m {rmoveto} defn" +

           "/c { .25 sub exch .25 sub exch .5 0 360 arc fill } defn" +

           "/s { moveto -2 0 m 2 2 l 2 -2 l -2 -2 l closepath " +

           "   gsave 1 setgray fill grestore gsave 3 setlinewidth" +

           " 1 setgray stroke grestore 0 setgray stroke }def")

    for i, cc in enumerate(cluster_centers):

        print ("%g %g %g setrgbcolor" %

               (colors[i].r, colors[i].g, colors[i].b))

        for p in points:

            if p.group != i:

                continue

            print ("%.3f %.3f c" % ((p.x - cx) * scale + W / 2,

                                    (p.y - cy) * scale + H / 2))

        print ("n0 setgray %g %g s" % ((cc.x - cx) * scale + W / 2,

                                        (cc.y - cy) * scale + H / 2))

    print "n%%%%EOF"

def main():

    npoints = 30000

    k = 7 # # clusters

    points = generate_points(npoints, 10)

    cluster_centers = lloyd(points, k)

    print_eps(points, cluster_centers)

main()

5.按要求写出Python 表达式。(1)将整数k 转换成实数。(2)求实数x 的小数部分

(1)float(k)

(2)x-int(x)

num=float("请输入实数:")

intpart=int(num)

decimalpart=num-intpart

print "实数%f 整数部分:%d 小数部分:%f"%(num,intpart,decimalpart

扩展资料:

Python的表达式写法与C/C++类似。只是在某些写法有所差别。

主要的算术运算符与C/C++类似。+, -, *, /, //, **, ~, %分别表示加法或者取正、减法或者取负、乘法、除法、整除、乘方、取补、取余。, 表示右移和左移。

, |, ^表示二进制的AND, OR, XOR运算。, , ==, !=, =, =用于比较两个表达式的值,分别表示大于、小于、等于、不等于、小于等于、大于等于。在这些运算符里面,~, |, ^, , , 必须应用于整数。

参考资料来源:百度百科-Python

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。