本文目錄一覽:
- 1、用python輸入k個正整數,其中每個數都是大於等於1,小於等於10的數。編寫程序?
- 2、PYTHON問題要用這些錢來支付K元,最少要用多少張紙幣?程序輸入K,輸出紙幣組合。
- 3、kmeans演算法用Python怎麼實現
- 4、5.按要求寫出Python 表達式。(1)將整數k 轉換成實數。(2)求實數x 的小數部分
用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