0

Can I simplify this code? Do i make things harder than they need to be?

Sample input: 2 Scott jones bob ryan Output: SJ BR number_of_names = int(input("enter number of names: ")) ask_for_names = 0 names_list = [] while ask_for_names < number_of_names: new_name = input("enter new name:") names_list.append(new_name) ask_for_names +=1 string_output = "" space_counter = 0 for name in names_list: x = name.split() for letter in x: string_output += letter[0] space_counter +=1 if space_counter % 2 == 0: string_output += " " print(string_output.upper())

12th May 2021, 6:58 AM
Scott
7 odpowiedzi
+ 1
From the next time, please save the code in the Code Playground and link it here. That makes it easier to reference line numbers. Answer: Instead of using a while loop, you can just use a for loop to loop on range(0, number_of_names). That way you don't need the extra 'ask_for_names' variable. So line 2 & 8 can be removed and thw while-loop can be changed to `for _ in range(number_of_names):` ('_' is a valid variable name commonly used to denote variables that are never used) The inner for-loop on line 15-19 is quite useless. You can change it to a single line `string_output += x[0][0] + x[1][0] + " "` If you do this, you can also remove the 'space_counter' variable. Don't worry too much about this. You'll learn how to wirte shorter code with experience. For example, one could also easily make a oneliner out of this (not recommended) `print( *( ((x := input("enter new name: ").split())[0][0] + x[1][0]).upper() for _ in range(int(input("enter number of names: )) ) ))`
12th May 2021, 7:24 AM
XXX
XXX - avatar
+ 1
Mohan 333 "a := b" is an expression and can be used anywhere (just like using the '+' or '-' operator).
12th May 2021, 5:20 PM
XXX
XXX - avatar
0
a=[input().split() for i in range(int(input()))] for j in a: for k in j: print(k[0].upper(),end='') print(end=' ')
12th May 2021, 7:36 AM
˜”*°•.˜”*°• Mohan 333 •°*”˜.•°*”˜
˜”*°•.˜”*°• Mohan 333 •°*”˜.•°*”˜ - avatar
0
XXX How you used the Walrus operator inside the tuple comprehension?
12th May 2021, 7:45 AM
˜”*°•.˜”*°• Mohan 333 •°*”˜.•°*”˜
˜”*°•.˜”*°• Mohan 333 •°*”˜.•°*”˜ - avatar
12th May 2021, 8:44 AM
˜”*°•.˜”*°• Mohan 333 •°*”˜.•°*”˜
˜”*°•.˜”*°• Mohan 333 •°*”˜.•°*”˜ - avatar
0
Awsome thanks for the knowledge its good to see how python can make a soloution with such short code!
12th May 2021, 9:03 AM
Scott
0
XXX but we cant using the += ,*= . Why? And any alternate operator are to do these operations?
12th May 2021, 6:56 PM
˜”*°•.˜”*°• Mohan 333 •°*”˜.•°*”˜
˜”*°•.˜”*°• Mohan 333 •°*”˜.•°*”˜ - avatar