用於k的匯合python,集合裡面的k是什麼意思

本文目錄一覽:

用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.0\n%%%%BoundingBox: -5 -5 %d %d” % (W + 10, H + 10)

    print (“/l {rlineto} def /m {rmoveto} def\n” +

           “/c { .25 sub exch .25 sub exch .5 0 360 arc fill } def\n” +

           “/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

原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/187800.html

(0)
打賞 微信掃一掃 微信掃一掃 支付寶掃一掃 支付寶掃一掃
小藍的頭像小藍
上一篇 2024-11-28 06:27
下一篇 2024-11-28 06:27

相關推薦

  • 如何查看Anaconda中Python路徑

    對Anaconda中Python路徑即conda環境的查看進行詳細的闡述。 一、使用命令行查看 1、在Windows系統中,可以使用命令提示符(cmd)或者Anaconda Pro…

    編程 2025-04-29
  • Python列表中負數的個數

    Python列表是一個有序的集合,可以存儲多個不同類型的元素。而負數是指小於0的整數。在Python列表中,我們想要找到負數的個數,可以通過以下幾個方面進行實現。 一、使用循環遍歷…

    編程 2025-04-29
  • Python計算陽曆日期對應周幾

    本文介紹如何通過Python計算任意陽曆日期對應周幾。 一、獲取日期 獲取日期可以通過Python內置的模塊datetime實現,示例代碼如下: from datetime imp…

    編程 2025-04-29
  • Python周杰倫代碼用法介紹

    本文將從多個方面對Python周杰倫代碼進行詳細的闡述。 一、代碼介紹 from urllib.request import urlopen from bs4 import Bea…

    編程 2025-04-29
  • Python中引入上一級目錄中函數

    Python中經常需要調用其他文件夾中的模塊或函數,其中一個常見的操作是引入上一級目錄中的函數。在此,我們將從多個角度詳細解釋如何在Python中引入上一級目錄的函數。 一、加入環…

    編程 2025-04-29
  • 蝴蝶優化演算法Python版

    蝴蝶優化演算法是一種基於仿生學的優化演算法,模仿自然界中的蝴蝶進行搜索。它可以應用於多個領域的優化問題,包括數學優化、工程問題、機器學習等。本文將從多個方面對蝴蝶優化演算法Python版…

    編程 2025-04-29
  • Python清華鏡像下載

    Python清華鏡像是一個高質量的Python開發資源鏡像站,提供了Python及其相關的開發工具、框架和文檔的下載服務。本文將從以下幾個方面對Python清華鏡像下載進行詳細的闡…

    編程 2025-04-29
  • python強行終止程序快捷鍵

    本文將從多個方面對python強行終止程序快捷鍵進行詳細闡述,並提供相應代碼示例。 一、Ctrl+C快捷鍵 Ctrl+C快捷鍵是在終端中經常用來強行終止運行的程序。當你在終端中運行…

    編程 2025-04-29
  • Python字典去重複工具

    使用Python語言編寫字典去重複工具,可幫助用戶快速去重複。 一、字典去重複工具的需求 在使用Python編寫程序時,我們經常需要處理數據文件,其中包含了大量的重複數據。為了方便…

    編程 2025-04-29
  • Python程序需要編譯才能執行

    Python 被廣泛應用於數據分析、人工智慧、科學計算等領域,它的靈活性和簡單易學的性質使得越來越多的人喜歡使用 Python 進行編程。然而,在 Python 中程序執行的方式不…

    編程 2025-04-29

發表回復

登錄後才能評論