将此Python程序更改为具有函数def()

时间:2017-12-08 09:39:42

标签: python function

以下Python程序翻了几次硬币,然后报告最长的一系列头尾。我试图将此程序转换为使用函数的程序,因此它使用的代码基本上更少。我是编程的新手,我的老师要求我们这样做,但我不知道该怎么做。我知道我应该有函数接受2个参数:字符串或列表,以及要搜索的字符。该函数应该返回一个整数作为函数的值,该整数是该字符串中该字符的最长序列。该功能不应接受用户的输入或输出。

import random

print("This program flips a coin several times, \nthen reports the longest 
series of heads and tails")

cointoss = int(input("Number of times to flip the coin: "))

varlist = [] 
i = 0
varstring = ' '

 while i < cointoss:
    r = random.choice('HT')

    varlist.append(r)
    varstring = varstring + r
    i += 1

print(varstring)

print(varlist)

print("There's this many heads: ",varstring.count("H"))
print("There's this many tails: ",varstring.count("T"))
print("Processing input...")

i = 0
longest_h = 0
longest_t = 0
inarow = 0
prevIn = 0

while i < cointoss:
    print(varlist[i])
    if varlist[i] == 'H':
        prevIn += 1
        if prevIn > longest_h:
            longest_h = prevIn
        print("",longest_h,"")

        inarow = 0

    if varlist[i] == 'T':
        inarow += 1
        if inarow > longest_t:
            longest_t = inarow
        print("",longest_t,"")

        prevIn = 0

    i += 1
print ("The longest series of heads is: ",longest_h)

print ("The longest series of tails is: ",longest_t)

如果这个问题太多,那么任何解释性的帮助都会非常好。我到目前为止所有的一切是:

def flip (a, b):
    flipValue = random.randint

但它几乎没有。

3 个答案:

答案 0 :(得分:0)

首先,你需要一个翻转硬币x次的功能。这是一种可能的实施方式,有利于random.choice超过random.randint

def flip(x):
  result = []
  for _ in range(x):
    result.append(random.choice(("h", "t")))
  return result

当然,您也可以从我们应该选择的参数作为参数传递。

接下来,您需要一个函数来查找某个列表中某个值的最长序列:

def longest_series(some_value, some_list):
  current, longest = 0, 0
  for r in some_list:
    if r == some_value:
      current += 1
      longest = max(current, longest)
    else:
      current = 0
  return longest

现在你可以按正确的顺序调用这些:

# initialize the random number generator, so we get the same result
random.seed(5)

# toss a coin a hundred times
series = flip(100)

# count heads/tails
headflips = longest_series('h', series)
tailflips = longest_series('t', series)

# print the results
print("The longest series of heads is: " + str(headflips))
print("The longest series of tails is: " + str(tailflips))

输出:

>> The longest series of heads is: 8
>> The longest series of heads is: 5

编辑:使用flip删除了yield实施,这使得代码很奇怪。

答案 1 :(得分:0)

import random
def Main():
    numOfFlips=getFlips()
    outcome=flipping(numOfFlips)
    print(outcome)
def getFlips():
    Flips=int(input("Enter number if flips:\n"))
    return Flips
def flipping(numOfFlips):
    longHeads=[]
    longTails=[]
    Tails=0
    Heads=0
    for flips in range(0,numOfFlips):
        flipValue=random.randint(1,2)
        print(flipValue)
        if flipValue==1:
            Tails+=1
            longHeads.append(Heads) #recording value of Heads before resetting it
            Heads=0
        else:
            Heads+=1
            longTails.append(Tails)
            Tails=0
    longestHeads=max(longHeads) #chooses the greatest length from both lists
    longestTails=max(longTails)
    return "Longest heads:\t"+str(longestHeads)+"\nLongest tails:\t"+str(longestTails)  
Main()

我不太明白你的代码是如何工作的,所以我在函数中创建的代码也是如此,可能有单独改进代码的方法,但我已将代码移到函数

答案 2 :(得分:0)

计算最长的跑步次数

让我们看看您的要求

  

我应该让函数接受2个参数:字符串或列表,

或者,稍微概括一下序列

  

和一个角色

再一次,我们一般会说项目

  

搜索。函数应该返回,作为的值     function,一个整数,是该字符的最长序列     在那个字符串中。

我要求的功能实现,完成doc 字符串,是

def longest_run(i, s):                                                      
    'Counts the longest run of item "i" in sequence "s".'
    c, m = 0, 0
    for el in s:
        if el==i:
            c += 1
        elif c:
            m = m if m >= c else c
            c = 0
    return m

我们将c c urrent run)和m m 最终运行到目前为止)初始化为零, 然后我们循环,查看参数 s 等于el的每个 el ement s

逻辑很简单,但对于elif c:,其块在运行结束时执行(因为c大于零且逻辑上为True),但不是前一项(不是当前的那个)不等于i。节省的费用很少,但节省了......

翻转硬币(以及更多......)

我们如何模拟翻转 n 币?我们抽象问题并认识到翻转 n 硬币对应于从可能结果的集合中选择(对于硬币, head tail n 次。

实际上,标准库的random模块具有完全这个问题的答案

In [52]: random.choices?
Signature: choices(population, weights=None, *, cum_weights=None, k=1)
Docstring:
Return a k sized list of population elements chosen with replacement.

If the relative weights or cumulative weights are not specified,
the selections are made with equal probability.
File:      ~/lib/miniconda3/lib/python3.6/random.py
Type:      method

我们的实施旨在隐藏细节,可能是

def roll(n, l):       
    '''Rolls "n" times a dice/coin whose face values are listed in "l".

    E.g., roll(2, range(1,21)) -> [12, 4] simulates rolling 2 icosahedron dices.
'''              
    from random import choices
    return choices(l, k=n)

把它放在一起

def longest_run(i, s):                                                      
    'Counts the longest run of item "i" in sequence "s".'
    c, m = 0, 0
    for el in s:
        if el==i:
            c += 1
        elif c:
            m = m if m >= c else c
            c = 0
    return m
def roll(n, l):       
    '''Rolls "n" times a dice/coin whose face values are listed in "l".

    E.g., roll(2, range(1,21)) -> [12, 4] simulates rolling 2 icosahedron dices.
'''              
    from random import choices
    return choices(l, k=n)

N = 100 # n. of flipped coins
h_or_t = ['h', 't']
random_seq_of_h_or_t = flip(N, h_or_t)
max_h = longest_run('h', random_seq_of_h_or_t)
max_t = longest_run('t', random_seq_of_h_or_t)