Python 行模式数字和
如何打印以下图案? 如果给出了行和列。 比如说Python 行模式数字和,python,loops,design-patterns,numbers,Python,Loops,Design Patterns,Numbers,如何打印以下图案? 如果给出了行和列。 比如说 x=5 y=6 从x开始,下一行是前一行的总和 55555 5+5+5+5+5=25 那么下一行必须是 25252 output: 55555 25252 16161 15151 13131 99999 有人能帮我写一个程序来解决这个问题吗?你可以用这样的方法 def f(x, y): orig_x = x for _ in range(y): tmp = (str(x)*orig_x)[:orig_x]
x=5
y=6
从x开始,下一行是前一行的总和
55555
5+5+5+5+5=25
那么下一行必须是
25252
output:
55555
25252
16161
15151
13131
99999
有人能帮我写一个程序来解决这个问题吗?你可以用这样的方法
def f(x, y):
orig_x = x
for _ in range(y):
tmp = (str(x)*orig_x)[:orig_x]
x = sum([int(i) for i in tmp])
print(tmp)
f(5,6)
55555
25252
16161
15151
13131
99999
不是最有效的代码,而是
#get the total given the initial number/row
def getSum(number):
total = 0
for num in number:
total += int(num)
return total
#print the row given the number and the number of columns
def printRow(number, columns):
counter = 0
row = ""
while (counter < columns):
for num in number:
row += num
counter += 1
if (counter >= columns):
break
print(row)
return row
x = 5 #initial number
y = 6 #number of rows
m = x
for z in range(y):
n = getSum(str(x))
x = printRow(str(n), m)
#获取给定初始编号/行的总数
def getSum(编号):
总数=0
对于数字中的num:
总数+=int(num)
返回总数
#打印给定行数和列数的行
def打印行(编号、列):
计数器=0
row=“”
while(计数器<列):
对于数字中的num:
行+=num
计数器+=1
如果(计数器>=列):
打破
打印(行)
返回行
x=5#初始编号
y=6#行数
m=x
对于范围(y)内的z:
n=getSum(str(x))
x=打印行(str(n),m)
使用Java的相同模式问题
添加您自己的addDigits()方法
公共静态无效模式(int N,int K){
原始变量N=N;
for(int i=0;i
您尝试过什么吗?你能告诉我们你试过什么吗?我是个学习者。我显然对这个问题一无所知。
public static void pattern(int N, int K) {
var originalN = N;
for (int i = 0; i < K; i++) {
String temp = new String(new char[originalN]).replace("\0", Integer.toString(N));
String newTemp = temp.substring(0, originalN);
System.out.println(newTemp);
N = addDigits(newTemp);
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int N = sc.nextInt();
int K = sc.nextInt();
pattern(N, K);
}