高级Python代码帮助

时间:2014-08-09 06:21:44

标签: python

我正在尝试完成一个Python代码,它计算每个节拍并放置一个X,如果它可以被一个数字整除。

示例:

Divisions: 3
Divisible by: 2
Divisible by: 3
Divisible by: 4
Number of beats to print: 10
 1:
 2:X
 3: X
 4:X X
 5:
 6:XX
 7:
 8:X X
 9: X
10:X

你看到2如何被2整除,所以它在第一列打印一个X?并且6可以被2和3整除,所以它在第一列和第二列上打印一个X?我需要帮助:)

这是我的代码到目前为止,任何人都可以完成它或帮我完成它?我想我需要将第二个循环放在另一个循环中,因为我需要循环从1到c的数字,为每个节拍计算它是否可以被每个d(list1中的数字)整除。我可能需要将循环增量b从1增加到c。

我的解决方法:

list1 = []
a = int(input("Divisions: "))
for b in range(1,a+1):
  z = int(input("Divisible by: "))
  list1.append(z)
c = int(input("Number of beats to print: "))
for e in range(1,c+1):
  for d in list1:
    remainder = b%d
    if remainder == 0:
      print(" "+str(e)+":","X")

2 个答案:

答案 0 :(得分:2)

divs = [int(input('Divisible by: ')) for _ in range(int(input('Divisions: ')))]
for beat in range(1, int(input('Number of beats to print: ')) + 1):
    print '%2d:%s' % (beat, ''.join(
        'X' if (beat % div) == 0 else ' ' for div in divs).rstrip())

使用您提供的测试用例:

Divisions: 3
Divisible by: 2
Divisible by: 3
Divisible by: 4
Number of beats to print: 10
 1:
 2:X
 3: X
 4:X X
 5:
 6:XX
 7:
 8:X X
 9: X
10:X

答案 1 :(得分:0)

list1 = []
a = int(input("Divisions: "))
for b in range(1,a+1):
  z = int(input("Divisible by: "))
  list1.append(z)

c = int(input("Number of beats to print: "))

for e in range(1,c+1):
  print('%3d:'%(e), end='')
  string=''
  for d in list1:
    remainder = e%d
    if remainder == 0:
      string += 'X'
    else:
      string += ' '
  print(string.rstrip())