简体   繁体   English

同时打印x次-Python

[英]Simultaneously printing x number of times - Python

I've been given a task to write a program that prints 'y' and 'n' a specified number of times. 我被赋予编写打印“ y”和“ n”指定次数的程序的任务。 We have to use the starting code provided; 我们必须使用提供的起始代码;

def my_string(size):
    #Code here...
    return out_string

print(my_string(3))  #Would print 'yny'
print(my_string(8))  #Would print 'ynynynyn'

But I have no idea where to start. 但是我不知道从哪里开始。

I've thought of looping though adding to a running total, and until that number is met then it will create a list of characters which would then be printed, however this seemed to be a problem because I was not able to figure out how to get the wanted length of the string.. :-L 我曾考虑过将循环添加到运行总计中,直到满足该数字,然后它将创建一个字符列表,然后将其打印出来,但是这似乎是一个问题,因为我无法弄清楚如何获得所需的字符串长度..:-L

def my_string(size):
    length = size
    times = 0
    current_print = [ ] 
    while times != length:
        current_print.append("y")
        times = times + 1
        current_print.append("n")
        times = times + 1

    return out_string

I kind of got lost after this point. 在这之后我有点迷路了。 Any guidance with this task would be much appreciated! 任何有关此任务的指导将不胜感激! Thank you! 谢谢!

In python you can simply do 在python中,您可以简单地执行

def my_string(size):
    out_string = ('yn' * size)[:size]
    return out_string

Try this: 尝试这个:

def my_string(size):
    times = 0
    current_print = ""
    while times < length:
        current_print += ("y", "n")[times % 2]

You could also use list-comprehension: 您还可以使用list-comprehension:

def my_string(size):
    return "".join(("y", "n")[x % 2] for x in range(size))

Another option: 另外一个选项:

def my_string(size):
    return ("yn" * (size // 2)) + ("y" * (size % 2))

This would do the trick: 这将达到目的:

def my_string(size):
    if size % 2 == 0:
        return 'yn' * (size / 2)
    else:
        return 'yn' * (size / 2) + 'y'

If size is an even number, we print 'yn' size/2 times. 如果size是偶数,则打印'yn'size size/2次。 If size is an odd number, we print 'yn' size/2 times plus another 'y'. 如果size是一个奇数,我们将打印'yn'size size/2次,再加上一个'y'。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM