python循环报数游戏_Python实现"报数"的两种方法

报数序列是指一个整数序列,按照其中的整数的顺序进行报数,得到下一个数。其前五项如下:

1. 1

2. 11

3. 21

4. 1211

5. 111221

1 被读作  "one 1"  ("一个一") , 即 11。

11 被读作 "two 1s" ("两个一"), 即 21。

21 被读作 "one 2",  "one 1" ("一个二" ,  "一个一") , 即 1211。

给定一个正整数 n ,输出报数序列的第 n 项。

注意:整数顺序将表示为一个字符串。

示例 1:

输入: 1

输出: "1"

示例 2:

输入: 4

输出: "1211"

1:本题其实是简单的规律变换,代码从输入为“2“开始调用transform()函数对报数序列进行变化

class Solution(object):

def countAndSay(self, n):

"""

:type n: int

:rtype: str

"""

basic_count_say = "1"

for num in range(n-1): # 从第二个报数开始计算

basic_count_say = self.transform(basic_count_say) # 调用报数变换函数

return basic_count_say

def transform(self, basic_count_say): # 报数变换

count = 0 # 某个数字连续出现的次数

temp_cha = basic_count_say[0] # 当前数字

new_str = "" # 新的报数序列

for cha in basic_count_say: # 遍历旧的报数序列

if temp_cha == cha: # 相同连续数字累加

count += 1

else: # 出现不相同数字就补充新报数序列

new_str = new_str + str(count) + temp_cha

temp_cha = cha # 清零,从头累加新的数字

count = 1

new_str = new_str + str(count) + temp_cha # 最后一个数字补充到新报数序列中

return new_str

2:递归!!!

def countAndSay(self, n):

"""

:type n: int

:rtype: str

"""

if n==1:

return "1"

s = self.countAndSay(n-1) #!!!!递归

count = 0 # 某个数字连续出现的次数

temp_cha = s[0] # 当前数字

new_str = "" # 新的报数序列

for cha in s: # 遍历旧的报数序列

if temp_cha == cha: # 相同连续数字累加

count += 1

else: # 出现不相同数字就补充新报数序列

new_str = new_str + str(count) + temp_cha

temp_cha = cha # 清零,从头累加新的数字

count = 1

new_str = new_str + str(count) + str(temp_cha) # 最后一个数字补充到新报数序列中

return new_str

算法题来自:https://leetcode-cn.com/problems/count-and-say/description/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Python 中,我们可以使用 threading 模块来创建多线程程序。线程同步是指多个线程之间协调工作,以避免竞态条件(race condition)和死锁(deadlock)等问题。其中一个经典的例子就是报数问题。 假设有两个线程 A 和 B,它们交替报数,从 1 开始,每次加 1,直到 10,然后停止。线程 A 报数时输出 "A: 1","A: 2","A: 3",...,线程 B 报数时输出 "B: 1","B: 2","B: 3",...,并且 A 和 B 的报数交替进行。 下面是一种使用 threading.Condition 来实现线程同步的方法: ```python import threading class Counter: def __init__(self): self.count = 0 self.cond = threading.Condition() def inc(self): with self.cond: while self.count >= 10: self.cond.wait() self.count += 1 print(threading.current_thread().name, ':', self.count) self.cond.notify_all() def worker(counter): for i in range(10): counter.inc() counter = Counter() t1 = threading.Thread(target=worker, args=(counter,)) t2 = threading.Thread(target=worker, args=(counter,)) t1.start() t2.start() t1.join() t2.join() ``` 在这个例子中,Counter 类封装了一个计数器和一个 Condition 对象。每个线程运行 worker 函数,该函数通过 counter.inc() 方法来递增计数器。在 inc() 方法中,使用 with self.cond: 语句来获取 Condition 锁,并在 while 循环中等待计数器小于 10。如果计数器已经达到 10,当前线程会调用 self.cond.wait() 方法进入等待状态,直到其他线程通过 self.cond.notify_all() 方法来唤醒它。如果计数器小于 10,当前线程会递增计数器,并输出当前线程名和计数器值,然后调用 self.cond.notify_all() 方法来唤醒其他线程。最后,主线程等待两个工作线程结束后退出。 这样,就可以实现线程同步,保证两个线程交替报数,避免了竞态条件和死锁问题。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值