I want to make a program, the output like
I am confused concerning for n
looping, my code right now looks like this
def menu(n):
return append(n, 0, 0)
def append(n, parent, label):
if n == 0:
return 1
elif n > 0:
id = (n-n)+1
parent = input("parent :")
label = input("label :")
print(id)
print(parent)
print(label)
menu(n-1)
menu(
int(input())
)
Can anyone help me how to make output using n input?
Based on my understanding of your code, I tried to apply it in a different code. Here is my simple suggestion:
ndata = int(input("total of input: "))
data = {'id': [], 'parent': [], 'label': []}
for i in range(ndata):
parent = int(input("parent: "))
label = input("label: ")
data['id'].append(i+1)
data['parent'].append(parent)
data['label'].append(label)
# print data
print('### print data ###')
print(f'total of data: {ndata}')
for i in range(len(data['id'])):
print(data['id'][i], data['parent'][i], data['label'][i])
If you run it on your terminal, you can input the data dan print the output. Here is my case:
total of input: 8
parent: 0
label: menu_1
parent: 0
label: menu_2
parent: 1
label: menu_3
parent: 1
label: menu_4
parent: 2
label: menu_5
parent: 3
label: menu_6
parent: 0
label: menu_7
parent: 2
label: menu_8
### print data ###
total of data: 8
1 0 menu_1
2 0 menu_2
3 1 menu_3
4 1 menu_4
5 2 menu_5
6 3 menu_6
7 0 menu_7
8 2 menu_8
Here is a demo reading the lines from a list in the code. Presumably, you can figure out how to read from a file instead.
lines = [
'8',
'1 0 menu_1',
'2 0 menu_2',
'3 1 menu_3',
'4 1 menu_4',
'5 2 menu_5',
'6 3 menu_6',
'7 0 menu_7',
'8 2 menu_8',
]
toplevel = []
index = {}
for line in lines[1:]:
idx, parent, name = line.strip().split()
new = [name, []]
index[idx] = new
if parent == '0':
toplevel.append( new )
else:
pitem = index[parent]
pitem[1].append( new )
def print_menu( level, items ):
for item in items:
print( ' '*level*4 + item[0] )
print_menu( level+1, item[1] )
print_menu( 0, toplevel )
Output:
[timr@Tims-Pro:~/src]$ python x.py
menu_1
menu_3
menu_6
menu_4
menu_2
menu_5
menu_8
menu_7
[timr@Tims-Pro:~/src]$
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.