【每日一题1106】握手次数

:mage:t2: 有一天,哈利波特参加宴会来的比较早,闲的无聊就开始数宾客们互相握手的次数。于是他想到一个疑问,如果任意两位之间握手,不能重复,最少最少需要多少人能握完呢?请编写一个函数,接收一个代表握手次数的数字n,返回所需的最少人数。任意两个人之间最多只能握手一次。

示例:
输入:1,输出:2。
输入:6,输出:4。

题目难度:中等
题目来源:codewars: Handshake problem

def handshakes(n: int) -> int:
    pass

assert handshakes(1) == 2
assert handshakes(3) == 3
assert handshakes(6) == 4
assert handshakes(7) == 5
def handshakes(n:int):
    res=0
    for i in range(1,n+1):
        res=res+i
        if res>=n:
            return i+1
#思路:n个人不重复互相握手的最大次数是可以计算的n-1+n-2+...+1,只要握手次数小于这个值,且大于n-1个人的最大握手次数,就输出n

def handshakes(n: int) → int:
p = 1
times = 0

while (p):
    times = times + (p - 1)
    if (times >= n):
        return p
        break
    else:
        p = p + 1
def handshakes(n: int) -> int:
    times = 1
    count = 2
    while times < n:
        times += count
        count += 1
    return count


assert handshakes(1) == 2
assert handshakes(3) == 3
assert handshakes(6) == 4
assert handshakes(7) == 5

# 总次数=1+2+...+n-2+n-1
def handshakes(n:int) -> int:
	count = 0
	for i in range(0,n+1):
		count += i
		if count>=n:
			return i+1
1 Like
def handshakes(n: int) -> int:
    if n==0:
        return 1
    index = 1
    while True:
        if index*(index-1)//2 >= n and (index-1)*(index-2)//2 < n:
            break
        index += 1
    return index

排列组合问题,A(n,2)

1 Like
def handshakes(n: int) -> int:
    num = 2
    while True:
        handshake_list = [(i, j) for i in range(1, num + 1) for j in range(i + 1, num + 1)]
        if len(handshake_list) >= n:
            return num
        num += 1


assert handshakes(1) == 2
assert handshakes(3) == 3
assert handshakes(6) == 4
assert handshakes(7) == 5
1 Like
def handshakes(n: int) -> int:
    ren=0
    while ren*(ren-1)/2<n:
        ren+=1
    return ren

assert handshakes(1) == 2
assert handshakes(3) == 3
assert handshakes(6) == 4
assert handshakes(7) == 5
def handshakes(n: int) -> int:
    for renshu in range(n+1):
        shakesCountS = sum([i for i in range(1,renshu+1)])
        shakesCountM = sum([i for i in range(1,renshu+2)])

        if n >shakesCountS and n <=shakesCountM:
            return renshu+2

assert handshakes(1) == 2
assert handshakes(3) == 3
assert handshakes(6) == 4
assert handshakes(7) == 5
def handshakes(n: int) -> int:
    people = 1
    minus = 1
    while n>0:
        n = n - minus
        minus += 1
        people += 1
    return people

看了一圈,感觉就我的方法笨

# 转化为求有多少条线,需要多少点的题目
def handshakes(n: int) -> int:
   pre_point = n
   while(cal_line(pre_point)>=n):
       pre_point -= 1
   return pre_point+1

# 计算有点,可以画出多少线
def cal_line(point:int) -> int:
    if point < 2: return 0
    elif point == 2: return 1
    else: return cal_line(point-1)+point-1

关闭