0

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]+ "!")
  • Please show expected output – Jab Oct 17 '21 at 05:58
  • I've mentioned the output in my quesiton .... –  Oct 17 '21 at 06:01
  • 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! –  Oct 17 '21 at 06:01
  • 1
    Does this answer your question? [Single Line Nested For Loops](https://stackoverflow.com/questions/17006641/single-line-nested-for-loops) – bad_coder Oct 17 '21 at 17:22

1 Answers1

1

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.

j1-lee
  • 13,764
  • 3
  • 14
  • 26
  • each person greets whoever was in the list before them . the person before Sara is John , so Sara only say Hi to John... Tom say hi to Sara and then John . –  Oct 17 '21 at 06:03
  • 1
    @Pythonnewby Oh I made a mistake there; please check the updated answer. – j1-lee Oct 17 '21 at 06:05