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())
7 Réponses
+ 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: )) ) ))`
+ 1
Mohan 333
"a := b" is an expression and can be used anywhere (just like using the '+' or '-' operator).
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=' ')
0
XXX
How you used the Walrus operator inside the tuple comprehension?
0
Awsome thanks for the knowledge its good to see how python can make a soloution with such short code!
0
XXX but we cant using the += ,*= .
Why?
And any alternate operator are to do these operations?