I have a python program with following logic & I can't get the nested loops right :( first line: number of friends? second line: enter each person name in same line separated by space [in a list] . this is how the greetings will go:
input:
3
John Sara Tom
output:
Sara: Hi John!
Tom: Hi Sara!
tom: Hi John!
John: bye guys!
Sara: bye John!
Tom: Bye John!
Sara: Bye guys!
Tom: Bye Sara!
Tom: Bye guys!
the greetings(Hi) starts with the second person in the list obviously; the nested loop will iterate from the newest person in the list to the first person (descending order)
and same thing should follow for saying goodbye ?(can this be done using list comprehension?!)
n=int(input())
user=list(input().split())
for i in range(2,n):
for j in range(i-1,1,-1):
print(user[i-1] ": Hi " user[j-1] "!")
for i in range(n):
print(user[i-1] ": Bye guys!")
for j in range(i 1):
print(user[j-1] ": Bye " user[i-1] "!")
CodePudding user response:
Your code is in the right direction. Meticulous treatment of for
and indexing would finish it. Try the following:
n = 3 # n = input('How many friends? ')
names = 'John Sara Tom'.split() # names = input('Who are they? ').split()
for i in range(1, n):
for j in range(i - 1, -1, -1):
print(f'{names[i]}: Hi {names[j]}!')
for i in range(n):
print(f'{names[i]}: Bye guys!')
for j in range(i 1, n):
print(f'{names[j]}: Bye {names[i]}!')
Output:
Sara: Hi John!
Tom: Hi Sara!
Tom: Hi John!
John: Bye guys!
Sara: Bye John!
Tom: Bye John!
Sara: Bye guys!
Tom: Bye Sara!
Tom: Bye guys!
As for list comprehension, of course you can do that:
his = [f'{names[i]}: Hi {names[j]}!' for i in range(1, n) for j in range(i - 1, -1, -1)]
byes = [f'{names[i]}: Bye guys!' '\n'
'\n'.join(f'{names[j]}: Bye {names[i]}!' for j in range(i 1, n))
for i in range(n)]
print('\n'.join(his))
print('\n'.join(byes))
But apparently this is way less readable.